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/GlobalISel/MIPatternMatch.h" 28 #include "llvm/CodeGen/MachineFunction.h" 29 #include "llvm/CodeGen/MachineLoopInfo.h" 30 #include "llvm/IR/DiagnosticInfo.h" 31 #include "llvm/IR/IntrinsicInst.h" 32 #include "llvm/IR/IntrinsicsAMDGPU.h" 33 #include "llvm/IR/IntrinsicsR600.h" 34 #include "llvm/Support/CommandLine.h" 35 #include "llvm/Support/KnownBits.h" 36 37 using namespace llvm; 38 39 #define DEBUG_TYPE "si-lower" 40 41 STATISTIC(NumTailCalls, "Number of tail calls"); 42 43 static cl::opt<bool> DisableLoopAlignment( 44 "amdgpu-disable-loop-alignment", 45 cl::desc("Do not align and prefetch loops"), 46 cl::init(false)); 47 48 static cl::opt<bool> VGPRReserveforSGPRSpill( 49 "amdgpu-reserve-vgpr-for-sgpr-spill", 50 cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true)); 51 52 static cl::opt<bool> UseDivergentRegisterIndexing( 53 "amdgpu-use-divergent-register-indexing", 54 cl::Hidden, 55 cl::desc("Use indirect register addressing for divergent indexes"), 56 cl::init(false)); 57 58 static bool hasFP32Denormals(const MachineFunction &MF) { 59 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 60 return Info->getMode().allFP32Denormals(); 61 } 62 63 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 64 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 65 return Info->getMode().allFP64FP16Denormals(); 66 } 67 68 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 69 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 70 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 71 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 72 return AMDGPU::SGPR0 + Reg; 73 } 74 } 75 llvm_unreachable("Cannot allocate sgpr"); 76 } 77 78 SITargetLowering::SITargetLowering(const TargetMachine &TM, 79 const GCNSubtarget &STI) 80 : AMDGPUTargetLowering(TM, STI), 81 Subtarget(&STI) { 82 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 83 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 84 85 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 86 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 87 88 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 89 90 const SIRegisterInfo *TRI = STI.getRegisterInfo(); 91 const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class(); 92 93 addRegisterClass(MVT::f64, V64RegClass); 94 addRegisterClass(MVT::v2f32, V64RegClass); 95 96 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 97 addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96)); 98 99 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 100 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 101 102 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 103 addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128)); 104 105 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 106 addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160)); 107 108 addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass); 109 addRegisterClass(MVT::v6f32, TRI->getVGPRClassForBitWidth(192)); 110 111 addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass); 112 addRegisterClass(MVT::v3f64, TRI->getVGPRClassForBitWidth(192)); 113 114 addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass); 115 addRegisterClass(MVT::v7f32, TRI->getVGPRClassForBitWidth(224)); 116 117 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass); 118 addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256)); 119 120 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass); 121 addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256)); 122 123 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass); 124 addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512)); 125 126 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass); 127 addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512)); 128 129 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass); 130 addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024)); 131 132 if (Subtarget->has16BitInsts()) { 133 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 134 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 135 136 // Unless there are also VOP3P operations, not operations are really legal. 137 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 138 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 139 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 140 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 141 } 142 143 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 144 addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024)); 145 146 computeRegisterProperties(Subtarget->getRegisterInfo()); 147 148 // The boolean content concept here is too inflexible. Compares only ever 149 // really produce a 1-bit result. Any copy/extend from these will turn into a 150 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 151 // it's what most targets use. 152 setBooleanContents(ZeroOrOneBooleanContent); 153 setBooleanVectorContents(ZeroOrOneBooleanContent); 154 155 // We need to custom lower vector stores from local memory 156 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 157 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 158 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 159 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 160 setOperationAction(ISD::LOAD, MVT::v6i32, Custom); 161 setOperationAction(ISD::LOAD, MVT::v7i32, Custom); 162 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 163 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 164 setOperationAction(ISD::LOAD, MVT::i1, Custom); 165 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 166 167 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 168 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 169 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 170 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 171 setOperationAction(ISD::STORE, MVT::v6i32, Custom); 172 setOperationAction(ISD::STORE, MVT::v7i32, Custom); 173 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 174 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 175 setOperationAction(ISD::STORE, MVT::i1, Custom); 176 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 177 178 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 179 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 180 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 181 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 182 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 183 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 184 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 185 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 186 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 187 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 188 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 189 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand); 190 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand); 191 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand); 192 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand); 193 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand); 194 195 setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand); 196 setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand); 197 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand); 198 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand); 199 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand); 200 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand); 201 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand); 202 203 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 204 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 205 206 setOperationAction(ISD::SELECT, MVT::i1, Promote); 207 setOperationAction(ISD::SELECT, MVT::i64, Custom); 208 setOperationAction(ISD::SELECT, MVT::f64, Promote); 209 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 210 211 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 212 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 213 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 214 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 215 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 216 217 setOperationAction(ISD::SETCC, MVT::i1, Promote); 218 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 219 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 220 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 221 222 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 223 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 224 setOperationAction(ISD::TRUNCATE, MVT::v3i32, Expand); 225 setOperationAction(ISD::FP_ROUND, MVT::v3f32, Expand); 226 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand); 227 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand); 228 setOperationAction(ISD::TRUNCATE, MVT::v5i32, Expand); 229 setOperationAction(ISD::FP_ROUND, MVT::v5f32, Expand); 230 setOperationAction(ISD::TRUNCATE, MVT::v6i32, Expand); 231 setOperationAction(ISD::FP_ROUND, MVT::v6f32, Expand); 232 setOperationAction(ISD::TRUNCATE, MVT::v7i32, Expand); 233 setOperationAction(ISD::FP_ROUND, MVT::v7f32, Expand); 234 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand); 235 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand); 236 setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand); 237 setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand); 238 239 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 240 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 241 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 242 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 243 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 244 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 245 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 246 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 247 248 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 249 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 250 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 251 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 252 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 253 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 254 255 setOperationAction(ISD::UADDO, MVT::i32, Legal); 256 setOperationAction(ISD::USUBO, MVT::i32, Legal); 257 258 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 259 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 260 261 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 262 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 263 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 264 265 #if 0 266 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 267 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 268 #endif 269 270 // We only support LOAD/STORE and vector manipulation ops for vectors 271 // with > 4 elements. 272 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 273 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 274 MVT::v3i64, MVT::v3f64, MVT::v6i32, MVT::v6f32, 275 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, 276 MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) { 277 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 278 switch (Op) { 279 case ISD::LOAD: 280 case ISD::STORE: 281 case ISD::BUILD_VECTOR: 282 case ISD::BITCAST: 283 case ISD::EXTRACT_VECTOR_ELT: 284 case ISD::INSERT_VECTOR_ELT: 285 case ISD::EXTRACT_SUBVECTOR: 286 case ISD::SCALAR_TO_VECTOR: 287 break; 288 case ISD::INSERT_SUBVECTOR: 289 case ISD::CONCAT_VECTORS: 290 setOperationAction(Op, VT, Custom); 291 break; 292 default: 293 setOperationAction(Op, VT, Expand); 294 break; 295 } 296 } 297 } 298 299 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 300 301 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 302 // is expanded to avoid having two separate loops in case the index is a VGPR. 303 304 // Most operations are naturally 32-bit vector operations. We only support 305 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 306 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 307 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 308 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 309 310 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 311 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 312 313 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 314 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 315 316 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 317 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 318 } 319 320 for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) { 321 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 322 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32); 323 324 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 325 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32); 326 327 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 328 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32); 329 330 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 331 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32); 332 } 333 334 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) { 335 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 336 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32); 337 338 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 339 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32); 340 341 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 342 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32); 343 344 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 345 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32); 346 } 347 348 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) { 349 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 350 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32); 351 352 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 353 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32); 354 355 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 356 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32); 357 358 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 359 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32); 360 } 361 362 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) { 363 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 364 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32); 365 366 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 367 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32); 368 369 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 370 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32); 371 372 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 373 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32); 374 } 375 376 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 377 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 378 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 379 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 380 381 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 382 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 383 384 // Avoid stack access for these. 385 // TODO: Generalize to more vector types. 386 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 387 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 388 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 389 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 390 391 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 392 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 393 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 394 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 395 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 396 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 397 398 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 399 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 400 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 401 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 402 403 // Deal with vec3 vector operations when widened to vec4. 404 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 405 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 406 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 407 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 408 409 // Deal with vec5/6/7 vector operations when widened to vec8. 410 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 411 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 412 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6i32, Custom); 413 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6f32, Custom); 414 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7i32, Custom); 415 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7f32, Custom); 416 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 417 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 418 419 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 420 // and output demarshalling 421 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 422 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 423 424 // We can't return success/failure, only the old value, 425 // let LLVM add the comparison 426 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 427 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 428 429 if (Subtarget->hasFlatAddressSpace()) { 430 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 431 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 432 } 433 434 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 435 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 436 437 // FIXME: This should be narrowed to i32, but that only happens if i64 is 438 // illegal. 439 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 440 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 441 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 442 443 // On SI this is s_memtime and s_memrealtime on VI. 444 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 445 setOperationAction(ISD::TRAP, MVT::Other, Custom); 446 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 447 448 if (Subtarget->has16BitInsts()) { 449 setOperationAction(ISD::FPOW, MVT::f16, Promote); 450 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 451 setOperationAction(ISD::FLOG, MVT::f16, Custom); 452 setOperationAction(ISD::FEXP, MVT::f16, Custom); 453 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 454 } 455 456 if (Subtarget->hasMadMacF32Insts()) 457 setOperationAction(ISD::FMAD, MVT::f32, Legal); 458 459 if (!Subtarget->hasBFI()) { 460 // fcopysign can be done in a single instruction with BFI. 461 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 462 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 463 } 464 465 if (!Subtarget->hasBCNT(32)) 466 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 467 468 if (!Subtarget->hasBCNT(64)) 469 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 470 471 if (Subtarget->hasFFBH()) { 472 setOperationAction(ISD::CTLZ, MVT::i32, Custom); 473 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 474 } 475 476 if (Subtarget->hasFFBL()) { 477 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 478 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 479 } 480 481 // We only really have 32-bit BFE instructions (and 16-bit on VI). 482 // 483 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 484 // effort to match them now. We want this to be false for i64 cases when the 485 // extraction isn't restricted to the upper or lower half. Ideally we would 486 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 487 // span the midpoint are probably relatively rare, so don't worry about them 488 // for now. 489 if (Subtarget->hasBFE()) 490 setHasExtractBitsInsn(true); 491 492 // Clamp modifier on add/sub 493 if (Subtarget->hasIntClamp()) { 494 setOperationAction(ISD::UADDSAT, MVT::i32, Legal); 495 setOperationAction(ISD::USUBSAT, MVT::i32, Legal); 496 } 497 498 if (Subtarget->hasAddNoCarry()) { 499 setOperationAction(ISD::SADDSAT, MVT::i16, Legal); 500 setOperationAction(ISD::SSUBSAT, MVT::i16, Legal); 501 setOperationAction(ISD::SADDSAT, MVT::i32, Legal); 502 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal); 503 } 504 505 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 506 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 507 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 508 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 509 510 511 // These are really only legal for ieee_mode functions. We should be avoiding 512 // them for functions that don't have ieee_mode enabled, so just say they are 513 // legal. 514 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 515 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 516 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 517 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 518 519 520 if (Subtarget->haveRoundOpsF64()) { 521 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 522 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 523 setOperationAction(ISD::FRINT, MVT::f64, Legal); 524 } else { 525 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 526 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 527 setOperationAction(ISD::FRINT, MVT::f64, Custom); 528 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 529 } 530 531 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 532 533 setOperationAction(ISD::FSIN, MVT::f32, Custom); 534 setOperationAction(ISD::FCOS, MVT::f32, Custom); 535 setOperationAction(ISD::FDIV, MVT::f32, Custom); 536 setOperationAction(ISD::FDIV, MVT::f64, Custom); 537 538 if (Subtarget->has16BitInsts()) { 539 setOperationAction(ISD::Constant, MVT::i16, Legal); 540 541 setOperationAction(ISD::SMIN, MVT::i16, Legal); 542 setOperationAction(ISD::SMAX, MVT::i16, Legal); 543 544 setOperationAction(ISD::UMIN, MVT::i16, Legal); 545 setOperationAction(ISD::UMAX, MVT::i16, Legal); 546 547 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 548 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 549 550 setOperationAction(ISD::ROTR, MVT::i16, Expand); 551 setOperationAction(ISD::ROTL, MVT::i16, Expand); 552 553 setOperationAction(ISD::SDIV, MVT::i16, Promote); 554 setOperationAction(ISD::UDIV, MVT::i16, Promote); 555 setOperationAction(ISD::SREM, MVT::i16, Promote); 556 setOperationAction(ISD::UREM, MVT::i16, Promote); 557 setOperationAction(ISD::UADDSAT, MVT::i16, Legal); 558 setOperationAction(ISD::USUBSAT, MVT::i16, Legal); 559 560 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 561 562 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 563 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 564 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 565 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 566 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 567 568 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 569 570 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 571 572 setOperationAction(ISD::LOAD, MVT::i16, Custom); 573 574 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 575 576 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 577 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 578 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 579 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 580 581 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Custom); 582 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Custom); 583 584 // F16 - Constant Actions. 585 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 586 587 // F16 - Load/Store Actions. 588 setOperationAction(ISD::LOAD, MVT::f16, Promote); 589 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 590 setOperationAction(ISD::STORE, MVT::f16, Promote); 591 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 592 593 // F16 - VOP1 Actions. 594 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 595 setOperationAction(ISD::FCOS, MVT::f16, Custom); 596 setOperationAction(ISD::FSIN, MVT::f16, Custom); 597 598 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 599 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 600 601 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 602 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 603 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 604 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 605 setOperationAction(ISD::FROUND, MVT::f16, Custom); 606 607 // F16 - VOP2 Actions. 608 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 609 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 610 611 setOperationAction(ISD::FDIV, MVT::f16, Custom); 612 613 // F16 - VOP3 Actions. 614 setOperationAction(ISD::FMA, MVT::f16, Legal); 615 if (STI.hasMadF16()) 616 setOperationAction(ISD::FMAD, MVT::f16, Legal); 617 618 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 619 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 620 switch (Op) { 621 case ISD::LOAD: 622 case ISD::STORE: 623 case ISD::BUILD_VECTOR: 624 case ISD::BITCAST: 625 case ISD::EXTRACT_VECTOR_ELT: 626 case ISD::INSERT_VECTOR_ELT: 627 case ISD::INSERT_SUBVECTOR: 628 case ISD::EXTRACT_SUBVECTOR: 629 case ISD::SCALAR_TO_VECTOR: 630 break; 631 case ISD::CONCAT_VECTORS: 632 setOperationAction(Op, VT, Custom); 633 break; 634 default: 635 setOperationAction(Op, VT, Expand); 636 break; 637 } 638 } 639 } 640 641 // v_perm_b32 can handle either of these. 642 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 643 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 644 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 645 646 // XXX - Do these do anything? Vector constants turn into build_vector. 647 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 648 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 649 650 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 651 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 652 653 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 654 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 655 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 656 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 657 658 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 659 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 660 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 661 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 662 663 setOperationAction(ISD::AND, MVT::v2i16, Promote); 664 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 665 setOperationAction(ISD::OR, MVT::v2i16, Promote); 666 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 667 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 668 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 669 670 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 671 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 672 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 673 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 674 675 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 676 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 677 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 678 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 679 680 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 681 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 682 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 683 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 684 685 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 686 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 687 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 688 689 if (!Subtarget->hasVOP3PInsts()) { 690 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 691 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 692 } 693 694 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 695 // This isn't really legal, but this avoids the legalizer unrolling it (and 696 // allows matching fneg (fabs x) patterns) 697 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 698 699 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 700 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 701 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 702 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 703 704 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 705 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 706 707 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 708 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 709 } 710 711 if (Subtarget->hasVOP3PInsts()) { 712 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 713 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 714 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 715 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 716 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 717 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 718 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 719 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 720 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 721 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 722 723 setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal); 724 setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal); 725 setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal); 726 setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal); 727 728 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 729 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 730 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 731 732 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 733 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 734 735 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 736 737 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 738 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 739 740 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 741 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 742 743 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 744 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 745 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 746 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 747 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 748 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 749 750 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 751 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 752 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 753 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 754 755 setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom); 756 setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom); 757 setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom); 758 setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom); 759 760 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 761 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 762 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 763 764 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 765 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 766 767 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 768 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 769 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 770 771 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 772 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 773 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 774 775 if (Subtarget->hasPackedFP32Ops()) { 776 setOperationAction(ISD::FADD, MVT::v2f32, Legal); 777 setOperationAction(ISD::FMUL, MVT::v2f32, Legal); 778 setOperationAction(ISD::FMA, MVT::v2f32, Legal); 779 setOperationAction(ISD::FNEG, MVT::v2f32, Legal); 780 781 for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) { 782 setOperationAction(ISD::FADD, VT, Custom); 783 setOperationAction(ISD::FMUL, VT, Custom); 784 setOperationAction(ISD::FMA, VT, Custom); 785 } 786 } 787 } 788 789 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 790 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 791 792 if (Subtarget->has16BitInsts()) { 793 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 794 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 795 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 796 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 797 } else { 798 // Legalization hack. 799 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 800 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 801 802 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 803 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 804 } 805 806 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 807 setOperationAction(ISD::SELECT, VT, Custom); 808 } 809 810 setOperationAction(ISD::SMULO, MVT::i64, Custom); 811 setOperationAction(ISD::UMULO, MVT::i64, Custom); 812 813 if (Subtarget->hasMad64_32()) { 814 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom); 815 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom); 816 } 817 818 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 819 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 820 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 821 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 822 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 823 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 824 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 825 826 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 827 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 828 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom); 829 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom); 830 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 831 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 832 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 833 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 834 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 835 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 836 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 837 838 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 839 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 840 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 841 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom); 842 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom); 843 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 844 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 845 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 846 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 847 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 848 849 setTargetDAGCombine(ISD::ADD); 850 setTargetDAGCombine(ISD::ADDCARRY); 851 setTargetDAGCombine(ISD::SUB); 852 setTargetDAGCombine(ISD::SUBCARRY); 853 setTargetDAGCombine(ISD::FADD); 854 setTargetDAGCombine(ISD::FSUB); 855 setTargetDAGCombine(ISD::FMINNUM); 856 setTargetDAGCombine(ISD::FMAXNUM); 857 setTargetDAGCombine(ISD::FMINNUM_IEEE); 858 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 859 setTargetDAGCombine(ISD::FMA); 860 setTargetDAGCombine(ISD::SMIN); 861 setTargetDAGCombine(ISD::SMAX); 862 setTargetDAGCombine(ISD::UMIN); 863 setTargetDAGCombine(ISD::UMAX); 864 setTargetDAGCombine(ISD::SETCC); 865 setTargetDAGCombine(ISD::AND); 866 setTargetDAGCombine(ISD::OR); 867 setTargetDAGCombine(ISD::XOR); 868 setTargetDAGCombine(ISD::SINT_TO_FP); 869 setTargetDAGCombine(ISD::UINT_TO_FP); 870 setTargetDAGCombine(ISD::FCANONICALIZE); 871 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 872 setTargetDAGCombine(ISD::ZERO_EXTEND); 873 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 874 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 875 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 876 877 // All memory operations. Some folding on the pointer operand is done to help 878 // matching the constant offsets in the addressing modes. 879 setTargetDAGCombine(ISD::LOAD); 880 setTargetDAGCombine(ISD::STORE); 881 setTargetDAGCombine(ISD::ATOMIC_LOAD); 882 setTargetDAGCombine(ISD::ATOMIC_STORE); 883 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 884 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 885 setTargetDAGCombine(ISD::ATOMIC_SWAP); 886 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 887 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 888 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 889 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 890 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 891 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 892 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 893 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 894 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 895 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 896 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 897 setTargetDAGCombine(ISD::INTRINSIC_VOID); 898 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 899 900 // FIXME: In other contexts we pretend this is a per-function property. 901 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 902 903 setSchedulingPreference(Sched::RegPressure); 904 } 905 906 const GCNSubtarget *SITargetLowering::getSubtarget() const { 907 return Subtarget; 908 } 909 910 //===----------------------------------------------------------------------===// 911 // TargetLowering queries 912 //===----------------------------------------------------------------------===// 913 914 // v_mad_mix* support a conversion from f16 to f32. 915 // 916 // There is only one special case when denormals are enabled we don't currently, 917 // where this is OK to use. 918 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 919 EVT DestVT, EVT SrcVT) const { 920 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 921 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 922 DestVT.getScalarType() == MVT::f32 && 923 SrcVT.getScalarType() == MVT::f16 && 924 // TODO: This probably only requires no input flushing? 925 !hasFP32Denormals(DAG.getMachineFunction()); 926 } 927 928 bool SITargetLowering::isFPExtFoldable(const MachineInstr &MI, unsigned Opcode, 929 LLT DestTy, LLT SrcTy) const { 930 return ((Opcode == TargetOpcode::G_FMAD && Subtarget->hasMadMixInsts()) || 931 (Opcode == TargetOpcode::G_FMA && Subtarget->hasFmaMixInsts())) && 932 DestTy.getScalarSizeInBits() == 32 && 933 SrcTy.getScalarSizeInBits() == 16 && 934 // TODO: This probably only requires no input flushing? 935 !hasFP32Denormals(*MI.getMF()); 936 } 937 938 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 939 // SI has some legal vector types, but no legal vector operations. Say no 940 // shuffles are legal in order to prefer scalarizing some vector operations. 941 return false; 942 } 943 944 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 945 CallingConv::ID CC, 946 EVT VT) const { 947 if (CC == CallingConv::AMDGPU_KERNEL) 948 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 949 950 if (VT.isVector()) { 951 EVT ScalarVT = VT.getScalarType(); 952 unsigned Size = ScalarVT.getSizeInBits(); 953 if (Size == 16) { 954 if (Subtarget->has16BitInsts()) 955 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 956 return VT.isInteger() ? MVT::i32 : MVT::f32; 957 } 958 959 if (Size < 16) 960 return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32; 961 return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32; 962 } 963 964 if (VT.getSizeInBits() > 32) 965 return MVT::i32; 966 967 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 968 } 969 970 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 971 CallingConv::ID CC, 972 EVT VT) const { 973 if (CC == CallingConv::AMDGPU_KERNEL) 974 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 975 976 if (VT.isVector()) { 977 unsigned NumElts = VT.getVectorNumElements(); 978 EVT ScalarVT = VT.getScalarType(); 979 unsigned Size = ScalarVT.getSizeInBits(); 980 981 // FIXME: Should probably promote 8-bit vectors to i16. 982 if (Size == 16 && Subtarget->has16BitInsts()) 983 return (NumElts + 1) / 2; 984 985 if (Size <= 32) 986 return NumElts; 987 988 if (Size > 32) 989 return NumElts * ((Size + 31) / 32); 990 } else if (VT.getSizeInBits() > 32) 991 return (VT.getSizeInBits() + 31) / 32; 992 993 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 994 } 995 996 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 997 LLVMContext &Context, CallingConv::ID CC, 998 EVT VT, EVT &IntermediateVT, 999 unsigned &NumIntermediates, MVT &RegisterVT) const { 1000 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 1001 unsigned NumElts = VT.getVectorNumElements(); 1002 EVT ScalarVT = VT.getScalarType(); 1003 unsigned Size = ScalarVT.getSizeInBits(); 1004 // FIXME: We should fix the ABI to be the same on targets without 16-bit 1005 // support, but unless we can properly handle 3-vectors, it will be still be 1006 // inconsistent. 1007 if (Size == 16 && Subtarget->has16BitInsts()) { 1008 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 1009 IntermediateVT = RegisterVT; 1010 NumIntermediates = (NumElts + 1) / 2; 1011 return NumIntermediates; 1012 } 1013 1014 if (Size == 32) { 1015 RegisterVT = ScalarVT.getSimpleVT(); 1016 IntermediateVT = RegisterVT; 1017 NumIntermediates = NumElts; 1018 return NumIntermediates; 1019 } 1020 1021 if (Size < 16 && Subtarget->has16BitInsts()) { 1022 // FIXME: Should probably form v2i16 pieces 1023 RegisterVT = MVT::i16; 1024 IntermediateVT = ScalarVT; 1025 NumIntermediates = NumElts; 1026 return NumIntermediates; 1027 } 1028 1029 1030 if (Size != 16 && Size <= 32) { 1031 RegisterVT = MVT::i32; 1032 IntermediateVT = ScalarVT; 1033 NumIntermediates = NumElts; 1034 return NumIntermediates; 1035 } 1036 1037 if (Size > 32) { 1038 RegisterVT = MVT::i32; 1039 IntermediateVT = RegisterVT; 1040 NumIntermediates = NumElts * ((Size + 31) / 32); 1041 return NumIntermediates; 1042 } 1043 } 1044 1045 return TargetLowering::getVectorTypeBreakdownForCallingConv( 1046 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 1047 } 1048 1049 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 1050 assert(DMaskLanes != 0); 1051 1052 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 1053 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 1054 return EVT::getVectorVT(Ty->getContext(), 1055 EVT::getEVT(VT->getElementType()), 1056 NumElts); 1057 } 1058 1059 return EVT::getEVT(Ty); 1060 } 1061 1062 // Peek through TFE struct returns to only use the data size. 1063 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 1064 auto *ST = dyn_cast<StructType>(Ty); 1065 if (!ST) 1066 return memVTFromImageData(Ty, DMaskLanes); 1067 1068 // Some intrinsics return an aggregate type - special case to work out the 1069 // correct memVT. 1070 // 1071 // Only limited forms of aggregate type currently expected. 1072 if (ST->getNumContainedTypes() != 2 || 1073 !ST->getContainedType(1)->isIntegerTy(32)) 1074 return EVT(); 1075 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 1076 } 1077 1078 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1079 const CallInst &CI, 1080 MachineFunction &MF, 1081 unsigned IntrID) const { 1082 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 1083 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 1084 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 1085 (Intrinsic::ID)IntrID); 1086 if (Attr.hasFnAttr(Attribute::ReadNone)) 1087 return false; 1088 1089 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1090 1091 if (RsrcIntr->IsImage) { 1092 Info.ptrVal = 1093 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1094 Info.align.reset(); 1095 } else { 1096 Info.ptrVal = 1097 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1098 } 1099 1100 Info.flags = MachineMemOperand::MODereferenceable; 1101 if (Attr.hasFnAttr(Attribute::ReadOnly)) { 1102 unsigned DMaskLanes = 4; 1103 1104 if (RsrcIntr->IsImage) { 1105 const AMDGPU::ImageDimIntrinsicInfo *Intr 1106 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 1107 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1108 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1109 1110 if (!BaseOpcode->Gather4) { 1111 // If this isn't a gather, we may have excess loaded elements in the 1112 // IR type. Check the dmask for the real number of elements loaded. 1113 unsigned DMask 1114 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1115 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1116 } 1117 1118 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1119 } else 1120 Info.memVT = EVT::getEVT(CI.getType()); 1121 1122 // FIXME: What does alignment mean for an image? 1123 Info.opc = ISD::INTRINSIC_W_CHAIN; 1124 Info.flags |= MachineMemOperand::MOLoad; 1125 } else if (Attr.hasFnAttr(Attribute::WriteOnly)) { 1126 Info.opc = ISD::INTRINSIC_VOID; 1127 1128 Type *DataTy = CI.getArgOperand(0)->getType(); 1129 if (RsrcIntr->IsImage) { 1130 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1131 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1132 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1133 } else 1134 Info.memVT = EVT::getEVT(DataTy); 1135 1136 Info.flags |= MachineMemOperand::MOStore; 1137 } else { 1138 // Atomic 1139 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID : 1140 ISD::INTRINSIC_W_CHAIN; 1141 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 1142 Info.flags = MachineMemOperand::MOLoad | 1143 MachineMemOperand::MOStore | 1144 MachineMemOperand::MODereferenceable; 1145 1146 // XXX - Should this be volatile without known ordering? 1147 Info.flags |= MachineMemOperand::MOVolatile; 1148 } 1149 return true; 1150 } 1151 1152 switch (IntrID) { 1153 case Intrinsic::amdgcn_atomic_inc: 1154 case Intrinsic::amdgcn_atomic_dec: 1155 case Intrinsic::amdgcn_ds_ordered_add: 1156 case Intrinsic::amdgcn_ds_ordered_swap: 1157 case Intrinsic::amdgcn_ds_fadd: 1158 case Intrinsic::amdgcn_ds_fmin: 1159 case Intrinsic::amdgcn_ds_fmax: { 1160 Info.opc = ISD::INTRINSIC_W_CHAIN; 1161 Info.memVT = MVT::getVT(CI.getType()); 1162 Info.ptrVal = CI.getOperand(0); 1163 Info.align.reset(); 1164 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1165 1166 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1167 if (!Vol->isZero()) 1168 Info.flags |= MachineMemOperand::MOVolatile; 1169 1170 return true; 1171 } 1172 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1173 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1174 1175 Info.opc = ISD::INTRINSIC_W_CHAIN; 1176 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1177 Info.ptrVal = 1178 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1179 Info.align.reset(); 1180 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1181 1182 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1183 if (!Vol || !Vol->isZero()) 1184 Info.flags |= MachineMemOperand::MOVolatile; 1185 1186 return true; 1187 } 1188 case Intrinsic::amdgcn_ds_append: 1189 case Intrinsic::amdgcn_ds_consume: { 1190 Info.opc = ISD::INTRINSIC_W_CHAIN; 1191 Info.memVT = MVT::getVT(CI.getType()); 1192 Info.ptrVal = CI.getOperand(0); 1193 Info.align.reset(); 1194 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1195 1196 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1197 if (!Vol->isZero()) 1198 Info.flags |= MachineMemOperand::MOVolatile; 1199 1200 return true; 1201 } 1202 case Intrinsic::amdgcn_global_atomic_csub: { 1203 Info.opc = ISD::INTRINSIC_W_CHAIN; 1204 Info.memVT = MVT::getVT(CI.getType()); 1205 Info.ptrVal = CI.getOperand(0); 1206 Info.align.reset(); 1207 Info.flags = MachineMemOperand::MOLoad | 1208 MachineMemOperand::MOStore | 1209 MachineMemOperand::MOVolatile; 1210 return true; 1211 } 1212 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 1213 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1214 Info.opc = ISD::INTRINSIC_W_CHAIN; 1215 Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT? 1216 Info.ptrVal = 1217 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1218 Info.align.reset(); 1219 Info.flags = MachineMemOperand::MOLoad | 1220 MachineMemOperand::MODereferenceable; 1221 return true; 1222 } 1223 case Intrinsic::amdgcn_global_atomic_fadd: 1224 case Intrinsic::amdgcn_global_atomic_fmin: 1225 case Intrinsic::amdgcn_global_atomic_fmax: 1226 case Intrinsic::amdgcn_flat_atomic_fadd: 1227 case Intrinsic::amdgcn_flat_atomic_fmin: 1228 case Intrinsic::amdgcn_flat_atomic_fmax: { 1229 Info.opc = ISD::INTRINSIC_W_CHAIN; 1230 Info.memVT = MVT::getVT(CI.getType()); 1231 Info.ptrVal = CI.getOperand(0); 1232 Info.align.reset(); 1233 Info.flags = MachineMemOperand::MOLoad | 1234 MachineMemOperand::MOStore | 1235 MachineMemOperand::MODereferenceable | 1236 MachineMemOperand::MOVolatile; 1237 return true; 1238 } 1239 case Intrinsic::amdgcn_ds_gws_init: 1240 case Intrinsic::amdgcn_ds_gws_barrier: 1241 case Intrinsic::amdgcn_ds_gws_sema_v: 1242 case Intrinsic::amdgcn_ds_gws_sema_br: 1243 case Intrinsic::amdgcn_ds_gws_sema_p: 1244 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1245 Info.opc = ISD::INTRINSIC_VOID; 1246 1247 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1248 Info.ptrVal = 1249 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1250 1251 // This is an abstract access, but we need to specify a type and size. 1252 Info.memVT = MVT::i32; 1253 Info.size = 4; 1254 Info.align = Align(4); 1255 1256 Info.flags = MachineMemOperand::MOStore; 1257 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1258 Info.flags = MachineMemOperand::MOLoad; 1259 return true; 1260 } 1261 default: 1262 return false; 1263 } 1264 } 1265 1266 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1267 SmallVectorImpl<Value*> &Ops, 1268 Type *&AccessTy) const { 1269 switch (II->getIntrinsicID()) { 1270 case Intrinsic::amdgcn_atomic_inc: 1271 case Intrinsic::amdgcn_atomic_dec: 1272 case Intrinsic::amdgcn_ds_ordered_add: 1273 case Intrinsic::amdgcn_ds_ordered_swap: 1274 case Intrinsic::amdgcn_ds_append: 1275 case Intrinsic::amdgcn_ds_consume: 1276 case Intrinsic::amdgcn_ds_fadd: 1277 case Intrinsic::amdgcn_ds_fmin: 1278 case Intrinsic::amdgcn_ds_fmax: 1279 case Intrinsic::amdgcn_global_atomic_fadd: 1280 case Intrinsic::amdgcn_flat_atomic_fadd: 1281 case Intrinsic::amdgcn_flat_atomic_fmin: 1282 case Intrinsic::amdgcn_flat_atomic_fmax: 1283 case Intrinsic::amdgcn_global_atomic_csub: { 1284 Value *Ptr = II->getArgOperand(0); 1285 AccessTy = II->getType(); 1286 Ops.push_back(Ptr); 1287 return true; 1288 } 1289 default: 1290 return false; 1291 } 1292 } 1293 1294 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1295 if (!Subtarget->hasFlatInstOffsets()) { 1296 // Flat instructions do not have offsets, and only have the register 1297 // address. 1298 return AM.BaseOffs == 0 && AM.Scale == 0; 1299 } 1300 1301 return AM.Scale == 0 && 1302 (AM.BaseOffs == 0 || 1303 Subtarget->getInstrInfo()->isLegalFLATOffset( 1304 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT)); 1305 } 1306 1307 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1308 if (Subtarget->hasFlatGlobalInsts()) 1309 return AM.Scale == 0 && 1310 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1311 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1312 SIInstrFlags::FlatGlobal)); 1313 1314 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1315 // Assume the we will use FLAT for all global memory accesses 1316 // on VI. 1317 // FIXME: This assumption is currently wrong. On VI we still use 1318 // MUBUF instructions for the r + i addressing mode. As currently 1319 // implemented, the MUBUF instructions only work on buffer < 4GB. 1320 // It may be possible to support > 4GB buffers with MUBUF instructions, 1321 // by setting the stride value in the resource descriptor which would 1322 // increase the size limit to (stride * 4GB). However, this is risky, 1323 // because it has never been validated. 1324 return isLegalFlatAddressingMode(AM); 1325 } 1326 1327 return isLegalMUBUFAddressingMode(AM); 1328 } 1329 1330 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1331 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1332 // additionally can do r + r + i with addr64. 32-bit has more addressing 1333 // mode options. Depending on the resource constant, it can also do 1334 // (i64 r0) + (i32 r1) * (i14 i). 1335 // 1336 // Private arrays end up using a scratch buffer most of the time, so also 1337 // assume those use MUBUF instructions. Scratch loads / stores are currently 1338 // implemented as mubuf instructions with offen bit set, so slightly 1339 // different than the normal addr64. 1340 if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs)) 1341 return false; 1342 1343 // FIXME: Since we can split immediate into soffset and immediate offset, 1344 // would it make sense to allow any immediate? 1345 1346 switch (AM.Scale) { 1347 case 0: // r + i or just i, depending on HasBaseReg. 1348 return true; 1349 case 1: 1350 return true; // We have r + r or r + i. 1351 case 2: 1352 if (AM.HasBaseReg) { 1353 // Reject 2 * r + r. 1354 return false; 1355 } 1356 1357 // Allow 2 * r as r + r 1358 // Or 2 * r + i is allowed as r + r + i. 1359 return true; 1360 default: // Don't allow n * r 1361 return false; 1362 } 1363 } 1364 1365 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1366 const AddrMode &AM, Type *Ty, 1367 unsigned AS, Instruction *I) const { 1368 // No global is ever allowed as a base. 1369 if (AM.BaseGV) 1370 return false; 1371 1372 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1373 return isLegalGlobalAddressingMode(AM); 1374 1375 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1376 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1377 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1378 // If the offset isn't a multiple of 4, it probably isn't going to be 1379 // correctly aligned. 1380 // FIXME: Can we get the real alignment here? 1381 if (AM.BaseOffs % 4 != 0) 1382 return isLegalMUBUFAddressingMode(AM); 1383 1384 // There are no SMRD extloads, so if we have to do a small type access we 1385 // will use a MUBUF load. 1386 // FIXME?: We also need to do this if unaligned, but we don't know the 1387 // alignment here. 1388 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1389 return isLegalGlobalAddressingMode(AM); 1390 1391 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1392 // SMRD instructions have an 8-bit, dword offset on SI. 1393 if (!isUInt<8>(AM.BaseOffs / 4)) 1394 return false; 1395 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1396 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1397 // in 8-bits, it can use a smaller encoding. 1398 if (!isUInt<32>(AM.BaseOffs / 4)) 1399 return false; 1400 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1401 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1402 if (!isUInt<20>(AM.BaseOffs)) 1403 return false; 1404 } else 1405 llvm_unreachable("unhandled generation"); 1406 1407 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1408 return true; 1409 1410 if (AM.Scale == 1 && AM.HasBaseReg) 1411 return true; 1412 1413 return false; 1414 1415 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1416 return isLegalMUBUFAddressingMode(AM); 1417 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1418 AS == AMDGPUAS::REGION_ADDRESS) { 1419 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1420 // field. 1421 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1422 // an 8-bit dword offset but we don't know the alignment here. 1423 if (!isUInt<16>(AM.BaseOffs)) 1424 return false; 1425 1426 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1427 return true; 1428 1429 if (AM.Scale == 1 && AM.HasBaseReg) 1430 return true; 1431 1432 return false; 1433 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1434 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1435 // For an unknown address space, this usually means that this is for some 1436 // reason being used for pure arithmetic, and not based on some addressing 1437 // computation. We don't have instructions that compute pointers with any 1438 // addressing modes, so treat them as having no offset like flat 1439 // instructions. 1440 return isLegalFlatAddressingMode(AM); 1441 } 1442 1443 // Assume a user alias of global for unknown address spaces. 1444 return isLegalGlobalAddressingMode(AM); 1445 } 1446 1447 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1448 const MachineFunction &MF) const { 1449 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1450 return (MemVT.getSizeInBits() <= 4 * 32); 1451 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1452 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1453 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1454 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1455 return (MemVT.getSizeInBits() <= 2 * 32); 1456 } 1457 return true; 1458 } 1459 1460 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1461 unsigned Size, unsigned AddrSpace, Align Alignment, 1462 MachineMemOperand::Flags Flags, bool *IsFast) const { 1463 if (IsFast) 1464 *IsFast = false; 1465 1466 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1467 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1468 // Check if alignment requirements for ds_read/write instructions are 1469 // disabled. 1470 if (Subtarget->hasUnalignedDSAccessEnabled() && 1471 !Subtarget->hasLDSMisalignedBug()) { 1472 if (IsFast) 1473 *IsFast = Alignment != Align(2); 1474 return true; 1475 } 1476 1477 // Either, the alignment requirements are "enabled", or there is an 1478 // unaligned LDS access related hardware bug though alignment requirements 1479 // are "disabled". In either case, we need to check for proper alignment 1480 // requirements. 1481 // 1482 if (Size == 64) { 1483 // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we 1484 // can do a 4 byte aligned, 8 byte access in a single operation using 1485 // ds_read2/write2_b32 with adjacent offsets. 1486 bool AlignedBy4 = Alignment >= Align(4); 1487 if (IsFast) 1488 *IsFast = AlignedBy4; 1489 1490 return AlignedBy4; 1491 } 1492 if (Size == 96) { 1493 // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on 1494 // gfx8 and older. 1495 bool AlignedBy16 = Alignment >= Align(16); 1496 if (IsFast) 1497 *IsFast = AlignedBy16; 1498 1499 return AlignedBy16; 1500 } 1501 if (Size == 128) { 1502 // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on 1503 // gfx8 and older, but we can do a 8 byte aligned, 16 byte access in a 1504 // single operation using ds_read2/write2_b64. 1505 bool AlignedBy8 = Alignment >= Align(8); 1506 if (IsFast) 1507 *IsFast = AlignedBy8; 1508 1509 return AlignedBy8; 1510 } 1511 } 1512 1513 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) { 1514 bool AlignedBy4 = Alignment >= Align(4); 1515 if (IsFast) 1516 *IsFast = AlignedBy4; 1517 1518 return AlignedBy4 || 1519 Subtarget->enableFlatScratch() || 1520 Subtarget->hasUnalignedScratchAccess(); 1521 } 1522 1523 // FIXME: We have to be conservative here and assume that flat operations 1524 // will access scratch. If we had access to the IR function, then we 1525 // could determine if any private memory was used in the function. 1526 if (AddrSpace == AMDGPUAS::FLAT_ADDRESS && 1527 !Subtarget->hasUnalignedScratchAccess()) { 1528 bool AlignedBy4 = Alignment >= Align(4); 1529 if (IsFast) 1530 *IsFast = AlignedBy4; 1531 1532 return AlignedBy4; 1533 } 1534 1535 if (Subtarget->hasUnalignedBufferAccessEnabled() && 1536 !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1537 AddrSpace == AMDGPUAS::REGION_ADDRESS)) { 1538 // If we have an uniform constant load, it still requires using a slow 1539 // buffer instruction if unaligned. 1540 if (IsFast) { 1541 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1542 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1543 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1544 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1545 Alignment >= Align(4) : Alignment != Align(2); 1546 } 1547 1548 return true; 1549 } 1550 1551 // Smaller than dword value must be aligned. 1552 if (Size < 32) 1553 return false; 1554 1555 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1556 // byte-address are ignored, thus forcing Dword alignment. 1557 // This applies to private, global, and constant memory. 1558 if (IsFast) 1559 *IsFast = true; 1560 1561 return Size >= 32 && Alignment >= Align(4); 1562 } 1563 1564 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1565 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 1566 bool *IsFast) const { 1567 if (IsFast) 1568 *IsFast = false; 1569 1570 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1571 // which isn't a simple VT. 1572 // Until MVT is extended to handle this, simply check for the size and 1573 // rely on the condition below: allow accesses if the size is a multiple of 4. 1574 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1575 VT.getStoreSize() > 16)) { 1576 return false; 1577 } 1578 1579 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1580 Alignment, Flags, IsFast); 1581 } 1582 1583 EVT SITargetLowering::getOptimalMemOpType( 1584 const MemOp &Op, const AttributeList &FuncAttributes) const { 1585 // FIXME: Should account for address space here. 1586 1587 // The default fallback uses the private pointer size as a guess for a type to 1588 // use. Make sure we switch these to 64-bit accesses. 1589 1590 if (Op.size() >= 16 && 1591 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1592 return MVT::v4i32; 1593 1594 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1595 return MVT::v2i32; 1596 1597 // Use the default. 1598 return MVT::Other; 1599 } 1600 1601 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1602 const MemSDNode *MemNode = cast<MemSDNode>(N); 1603 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1604 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1605 return I && I->getMetadata("amdgpu.noclobber"); 1606 } 1607 1608 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) { 1609 return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS || 1610 AS == AMDGPUAS::PRIVATE_ADDRESS; 1611 } 1612 1613 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1614 unsigned DestAS) const { 1615 // Flat -> private/local is a simple truncate. 1616 // Flat -> global is no-op 1617 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1618 return true; 1619 1620 const GCNTargetMachine &TM = 1621 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1622 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 1623 } 1624 1625 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1626 const MemSDNode *MemNode = cast<MemSDNode>(N); 1627 1628 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1629 } 1630 1631 TargetLoweringBase::LegalizeTypeAction 1632 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1633 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 && 1634 VT.getScalarType().bitsLE(MVT::i16)) 1635 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1636 return TargetLoweringBase::getPreferredVectorAction(VT); 1637 } 1638 1639 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1640 Type *Ty) const { 1641 // FIXME: Could be smarter if called for vector constants. 1642 return true; 1643 } 1644 1645 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1646 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1647 switch (Op) { 1648 case ISD::LOAD: 1649 case ISD::STORE: 1650 1651 // These operations are done with 32-bit instructions anyway. 1652 case ISD::AND: 1653 case ISD::OR: 1654 case ISD::XOR: 1655 case ISD::SELECT: 1656 // TODO: Extensions? 1657 return true; 1658 default: 1659 return false; 1660 } 1661 } 1662 1663 // SimplifySetCC uses this function to determine whether or not it should 1664 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1665 if (VT == MVT::i1 && Op == ISD::SETCC) 1666 return false; 1667 1668 return TargetLowering::isTypeDesirableForOp(Op, VT); 1669 } 1670 1671 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1672 const SDLoc &SL, 1673 SDValue Chain, 1674 uint64_t Offset) const { 1675 const DataLayout &DL = DAG.getDataLayout(); 1676 MachineFunction &MF = DAG.getMachineFunction(); 1677 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1678 1679 const ArgDescriptor *InputPtrReg; 1680 const TargetRegisterClass *RC; 1681 LLT ArgTy; 1682 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1683 1684 std::tie(InputPtrReg, RC, ArgTy) = 1685 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1686 1687 // We may not have the kernarg segment argument if we have no kernel 1688 // arguments. 1689 if (!InputPtrReg) 1690 return DAG.getConstant(0, SL, PtrVT); 1691 1692 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1693 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1694 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1695 1696 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset)); 1697 } 1698 1699 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1700 const SDLoc &SL) const { 1701 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1702 FIRST_IMPLICIT); 1703 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1704 } 1705 1706 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1707 const SDLoc &SL, SDValue Val, 1708 bool Signed, 1709 const ISD::InputArg *Arg) const { 1710 // First, if it is a widened vector, narrow it. 1711 if (VT.isVector() && 1712 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1713 EVT NarrowedVT = 1714 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1715 VT.getVectorNumElements()); 1716 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1717 DAG.getConstant(0, SL, MVT::i32)); 1718 } 1719 1720 // Then convert the vector elements or scalar value. 1721 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1722 VT.bitsLT(MemVT)) { 1723 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1724 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1725 } 1726 1727 if (MemVT.isFloatingPoint()) 1728 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1729 else if (Signed) 1730 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1731 else 1732 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1733 1734 return Val; 1735 } 1736 1737 SDValue SITargetLowering::lowerKernargMemParameter( 1738 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1739 uint64_t Offset, Align Alignment, bool Signed, 1740 const ISD::InputArg *Arg) const { 1741 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1742 1743 // Try to avoid using an extload by loading earlier than the argument address, 1744 // and extracting the relevant bits. The load should hopefully be merged with 1745 // the previous argument. 1746 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1747 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1748 int64_t AlignDownOffset = alignDown(Offset, 4); 1749 int64_t OffsetDiff = Offset - AlignDownOffset; 1750 1751 EVT IntVT = MemVT.changeTypeToInteger(); 1752 1753 // TODO: If we passed in the base kernel offset we could have a better 1754 // alignment than 4, but we don't really need it. 1755 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1756 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4), 1757 MachineMemOperand::MODereferenceable | 1758 MachineMemOperand::MOInvariant); 1759 1760 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1761 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1762 1763 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1764 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1765 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1766 1767 1768 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1769 } 1770 1771 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1772 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1773 MachineMemOperand::MODereferenceable | 1774 MachineMemOperand::MOInvariant); 1775 1776 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1777 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1778 } 1779 1780 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1781 const SDLoc &SL, SDValue Chain, 1782 const ISD::InputArg &Arg) const { 1783 MachineFunction &MF = DAG.getMachineFunction(); 1784 MachineFrameInfo &MFI = MF.getFrameInfo(); 1785 1786 if (Arg.Flags.isByVal()) { 1787 unsigned Size = Arg.Flags.getByValSize(); 1788 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1789 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1790 } 1791 1792 unsigned ArgOffset = VA.getLocMemOffset(); 1793 unsigned ArgSize = VA.getValVT().getStoreSize(); 1794 1795 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1796 1797 // Create load nodes to retrieve arguments from the stack. 1798 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1799 SDValue ArgValue; 1800 1801 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1802 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1803 MVT MemVT = VA.getValVT(); 1804 1805 switch (VA.getLocInfo()) { 1806 default: 1807 break; 1808 case CCValAssign::BCvt: 1809 MemVT = VA.getLocVT(); 1810 break; 1811 case CCValAssign::SExt: 1812 ExtType = ISD::SEXTLOAD; 1813 break; 1814 case CCValAssign::ZExt: 1815 ExtType = ISD::ZEXTLOAD; 1816 break; 1817 case CCValAssign::AExt: 1818 ExtType = ISD::EXTLOAD; 1819 break; 1820 } 1821 1822 ArgValue = DAG.getExtLoad( 1823 ExtType, SL, VA.getLocVT(), Chain, FIN, 1824 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1825 MemVT); 1826 return ArgValue; 1827 } 1828 1829 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1830 const SIMachineFunctionInfo &MFI, 1831 EVT VT, 1832 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1833 const ArgDescriptor *Reg; 1834 const TargetRegisterClass *RC; 1835 LLT Ty; 1836 1837 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1838 if (!Reg) { 1839 if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) { 1840 // It's possible for a kernarg intrinsic call to appear in a kernel with 1841 // no allocated segment, in which case we do not add the user sgpr 1842 // argument, so just return null. 1843 return DAG.getConstant(0, SDLoc(), VT); 1844 } 1845 1846 // It's undefined behavior if a function marked with the amdgpu-no-* 1847 // attributes uses the corresponding intrinsic. 1848 return DAG.getUNDEF(VT); 1849 } 1850 1851 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1852 } 1853 1854 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1855 CallingConv::ID CallConv, 1856 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped, 1857 FunctionType *FType, 1858 SIMachineFunctionInfo *Info) { 1859 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1860 const ISD::InputArg *Arg = &Ins[I]; 1861 1862 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1863 "vector type argument should have been split"); 1864 1865 // First check if it's a PS input addr. 1866 if (CallConv == CallingConv::AMDGPU_PS && 1867 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1868 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1869 1870 // Inconveniently only the first part of the split is marked as isSplit, 1871 // so skip to the end. We only want to increment PSInputNum once for the 1872 // entire split argument. 1873 if (Arg->Flags.isSplit()) { 1874 while (!Arg->Flags.isSplitEnd()) { 1875 assert((!Arg->VT.isVector() || 1876 Arg->VT.getScalarSizeInBits() == 16) && 1877 "unexpected vector split in ps argument type"); 1878 if (!SkipArg) 1879 Splits.push_back(*Arg); 1880 Arg = &Ins[++I]; 1881 } 1882 } 1883 1884 if (SkipArg) { 1885 // We can safely skip PS inputs. 1886 Skipped.set(Arg->getOrigArgIndex()); 1887 ++PSInputNum; 1888 continue; 1889 } 1890 1891 Info->markPSInputAllocated(PSInputNum); 1892 if (Arg->Used) 1893 Info->markPSInputEnabled(PSInputNum); 1894 1895 ++PSInputNum; 1896 } 1897 1898 Splits.push_back(*Arg); 1899 } 1900 } 1901 1902 // Allocate special inputs passed in VGPRs. 1903 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1904 MachineFunction &MF, 1905 const SIRegisterInfo &TRI, 1906 SIMachineFunctionInfo &Info) const { 1907 const LLT S32 = LLT::scalar(32); 1908 MachineRegisterInfo &MRI = MF.getRegInfo(); 1909 1910 if (Info.hasWorkItemIDX()) { 1911 Register Reg = AMDGPU::VGPR0; 1912 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1913 1914 CCInfo.AllocateReg(Reg); 1915 unsigned Mask = (Subtarget->hasPackedTID() && 1916 Info.hasWorkItemIDY()) ? 0x3ff : ~0u; 1917 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1918 } 1919 1920 if (Info.hasWorkItemIDY()) { 1921 assert(Info.hasWorkItemIDX()); 1922 if (Subtarget->hasPackedTID()) { 1923 Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1924 0x3ff << 10)); 1925 } else { 1926 unsigned Reg = AMDGPU::VGPR1; 1927 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1928 1929 CCInfo.AllocateReg(Reg); 1930 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1931 } 1932 } 1933 1934 if (Info.hasWorkItemIDZ()) { 1935 assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY()); 1936 if (Subtarget->hasPackedTID()) { 1937 Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1938 0x3ff << 20)); 1939 } else { 1940 unsigned Reg = AMDGPU::VGPR2; 1941 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1942 1943 CCInfo.AllocateReg(Reg); 1944 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1945 } 1946 } 1947 } 1948 1949 // Try to allocate a VGPR at the end of the argument list, or if no argument 1950 // VGPRs are left allocating a stack slot. 1951 // If \p Mask is is given it indicates bitfield position in the register. 1952 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1953 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1954 ArgDescriptor Arg = ArgDescriptor()) { 1955 if (Arg.isSet()) 1956 return ArgDescriptor::createArg(Arg, Mask); 1957 1958 ArrayRef<MCPhysReg> ArgVGPRs 1959 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1960 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1961 if (RegIdx == ArgVGPRs.size()) { 1962 // Spill to stack required. 1963 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 1964 1965 return ArgDescriptor::createStack(Offset, Mask); 1966 } 1967 1968 unsigned Reg = ArgVGPRs[RegIdx]; 1969 Reg = CCInfo.AllocateReg(Reg); 1970 assert(Reg != AMDGPU::NoRegister); 1971 1972 MachineFunction &MF = CCInfo.getMachineFunction(); 1973 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1974 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1975 return ArgDescriptor::createRegister(Reg, Mask); 1976 } 1977 1978 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1979 const TargetRegisterClass *RC, 1980 unsigned NumArgRegs) { 1981 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1982 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1983 if (RegIdx == ArgSGPRs.size()) 1984 report_fatal_error("ran out of SGPRs for arguments"); 1985 1986 unsigned Reg = ArgSGPRs[RegIdx]; 1987 Reg = CCInfo.AllocateReg(Reg); 1988 assert(Reg != AMDGPU::NoRegister); 1989 1990 MachineFunction &MF = CCInfo.getMachineFunction(); 1991 MF.addLiveIn(Reg, RC); 1992 return ArgDescriptor::createRegister(Reg); 1993 } 1994 1995 // If this has a fixed position, we still should allocate the register in the 1996 // CCInfo state. Technically we could get away with this for values passed 1997 // outside of the normal argument range. 1998 static void allocateFixedSGPRInputImpl(CCState &CCInfo, 1999 const TargetRegisterClass *RC, 2000 MCRegister Reg) { 2001 Reg = CCInfo.AllocateReg(Reg); 2002 assert(Reg != AMDGPU::NoRegister); 2003 MachineFunction &MF = CCInfo.getMachineFunction(); 2004 MF.addLiveIn(Reg, RC); 2005 } 2006 2007 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) { 2008 if (Arg) { 2009 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 2010 Arg.getRegister()); 2011 } else 2012 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 2013 } 2014 2015 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) { 2016 if (Arg) { 2017 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 2018 Arg.getRegister()); 2019 } else 2020 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 2021 } 2022 2023 /// Allocate implicit function VGPR arguments at the end of allocated user 2024 /// arguments. 2025 void SITargetLowering::allocateSpecialInputVGPRs( 2026 CCState &CCInfo, MachineFunction &MF, 2027 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 2028 const unsigned Mask = 0x3ff; 2029 ArgDescriptor Arg; 2030 2031 if (Info.hasWorkItemIDX()) { 2032 Arg = allocateVGPR32Input(CCInfo, Mask); 2033 Info.setWorkItemIDX(Arg); 2034 } 2035 2036 if (Info.hasWorkItemIDY()) { 2037 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 2038 Info.setWorkItemIDY(Arg); 2039 } 2040 2041 if (Info.hasWorkItemIDZ()) 2042 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 2043 } 2044 2045 /// Allocate implicit function VGPR arguments in fixed registers. 2046 void SITargetLowering::allocateSpecialInputVGPRsFixed( 2047 CCState &CCInfo, MachineFunction &MF, 2048 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 2049 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 2050 if (!Reg) 2051 report_fatal_error("failed to allocated VGPR for implicit arguments"); 2052 2053 const unsigned Mask = 0x3ff; 2054 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 2055 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 2056 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 2057 } 2058 2059 void SITargetLowering::allocateSpecialInputSGPRs( 2060 CCState &CCInfo, 2061 MachineFunction &MF, 2062 const SIRegisterInfo &TRI, 2063 SIMachineFunctionInfo &Info) const { 2064 auto &ArgInfo = Info.getArgInfo(); 2065 2066 // We need to allocate these in place regardless of their use. 2067 const bool IsFixed = AMDGPUTargetMachine::EnableFixedFunctionABI; 2068 2069 // TODO: Unify handling with private memory pointers. 2070 if (IsFixed || Info.hasDispatchPtr()) 2071 allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr); 2072 2073 if (IsFixed || Info.hasQueuePtr()) 2074 allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr); 2075 2076 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 2077 // constant offset from the kernarg segment. 2078 if (IsFixed || Info.hasImplicitArgPtr()) 2079 allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr); 2080 2081 if (IsFixed || Info.hasDispatchID()) 2082 allocateSGPR64Input(CCInfo, ArgInfo.DispatchID); 2083 2084 // flat_scratch_init is not applicable for non-kernel functions. 2085 2086 if (IsFixed || Info.hasWorkGroupIDX()) 2087 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX); 2088 2089 if (IsFixed || Info.hasWorkGroupIDY()) 2090 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY); 2091 2092 if (IsFixed || Info.hasWorkGroupIDZ()) 2093 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ); 2094 } 2095 2096 // Allocate special inputs passed in user SGPRs. 2097 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 2098 MachineFunction &MF, 2099 const SIRegisterInfo &TRI, 2100 SIMachineFunctionInfo &Info) const { 2101 if (Info.hasImplicitBufferPtr()) { 2102 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 2103 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 2104 CCInfo.AllocateReg(ImplicitBufferPtrReg); 2105 } 2106 2107 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 2108 if (Info.hasPrivateSegmentBuffer()) { 2109 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 2110 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 2111 CCInfo.AllocateReg(PrivateSegmentBufferReg); 2112 } 2113 2114 if (Info.hasDispatchPtr()) { 2115 Register DispatchPtrReg = Info.addDispatchPtr(TRI); 2116 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 2117 CCInfo.AllocateReg(DispatchPtrReg); 2118 } 2119 2120 if (Info.hasQueuePtr()) { 2121 Register QueuePtrReg = Info.addQueuePtr(TRI); 2122 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 2123 CCInfo.AllocateReg(QueuePtrReg); 2124 } 2125 2126 if (Info.hasKernargSegmentPtr()) { 2127 MachineRegisterInfo &MRI = MF.getRegInfo(); 2128 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 2129 CCInfo.AllocateReg(InputPtrReg); 2130 2131 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 2132 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 2133 } 2134 2135 if (Info.hasDispatchID()) { 2136 Register DispatchIDReg = Info.addDispatchID(TRI); 2137 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 2138 CCInfo.AllocateReg(DispatchIDReg); 2139 } 2140 2141 if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) { 2142 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI); 2143 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 2144 CCInfo.AllocateReg(FlatScratchInitReg); 2145 } 2146 2147 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 2148 // these from the dispatch pointer. 2149 } 2150 2151 // Allocate special input registers that are initialized per-wave. 2152 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 2153 MachineFunction &MF, 2154 SIMachineFunctionInfo &Info, 2155 CallingConv::ID CallConv, 2156 bool IsShader) const { 2157 if (Info.hasWorkGroupIDX()) { 2158 Register Reg = Info.addWorkGroupIDX(); 2159 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2160 CCInfo.AllocateReg(Reg); 2161 } 2162 2163 if (Info.hasWorkGroupIDY()) { 2164 Register Reg = Info.addWorkGroupIDY(); 2165 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2166 CCInfo.AllocateReg(Reg); 2167 } 2168 2169 if (Info.hasWorkGroupIDZ()) { 2170 Register Reg = Info.addWorkGroupIDZ(); 2171 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2172 CCInfo.AllocateReg(Reg); 2173 } 2174 2175 if (Info.hasWorkGroupInfo()) { 2176 Register Reg = Info.addWorkGroupInfo(); 2177 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2178 CCInfo.AllocateReg(Reg); 2179 } 2180 2181 if (Info.hasPrivateSegmentWaveByteOffset()) { 2182 // Scratch wave offset passed in system SGPR. 2183 unsigned PrivateSegmentWaveByteOffsetReg; 2184 2185 if (IsShader) { 2186 PrivateSegmentWaveByteOffsetReg = 2187 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 2188 2189 // This is true if the scratch wave byte offset doesn't have a fixed 2190 // location. 2191 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 2192 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 2193 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 2194 } 2195 } else 2196 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 2197 2198 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 2199 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 2200 } 2201 } 2202 2203 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2204 MachineFunction &MF, 2205 const SIRegisterInfo &TRI, 2206 SIMachineFunctionInfo &Info) { 2207 // Now that we've figured out where the scratch register inputs are, see if 2208 // should reserve the arguments and use them directly. 2209 MachineFrameInfo &MFI = MF.getFrameInfo(); 2210 bool HasStackObjects = MFI.hasStackObjects(); 2211 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2212 2213 // Record that we know we have non-spill stack objects so we don't need to 2214 // check all stack objects later. 2215 if (HasStackObjects) 2216 Info.setHasNonSpillStackObjects(true); 2217 2218 // Everything live out of a block is spilled with fast regalloc, so it's 2219 // almost certain that spilling will be required. 2220 if (TM.getOptLevel() == CodeGenOpt::None) 2221 HasStackObjects = true; 2222 2223 // For now assume stack access is needed in any callee functions, so we need 2224 // the scratch registers to pass in. 2225 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2226 2227 if (!ST.enableFlatScratch()) { 2228 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2229 // If we have stack objects, we unquestionably need the private buffer 2230 // resource. For the Code Object V2 ABI, this will be the first 4 user 2231 // SGPR inputs. We can reserve those and use them directly. 2232 2233 Register PrivateSegmentBufferReg = 2234 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2235 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2236 } else { 2237 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2238 // We tentatively reserve the last registers (skipping the last registers 2239 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2240 // we'll replace these with the ones immediately after those which were 2241 // really allocated. In the prologue copies will be inserted from the 2242 // argument to these reserved registers. 2243 2244 // Without HSA, relocations are used for the scratch pointer and the 2245 // buffer resource setup is always inserted in the prologue. Scratch wave 2246 // offset is still in an input SGPR. 2247 Info.setScratchRSrcReg(ReservedBufferReg); 2248 } 2249 } 2250 2251 MachineRegisterInfo &MRI = MF.getRegInfo(); 2252 2253 // For entry functions we have to set up the stack pointer if we use it, 2254 // whereas non-entry functions get this "for free". This means there is no 2255 // intrinsic advantage to using S32 over S34 in cases where we do not have 2256 // calls but do need a frame pointer (i.e. if we are requested to have one 2257 // because frame pointer elimination is disabled). To keep things simple we 2258 // only ever use S32 as the call ABI stack pointer, and so using it does not 2259 // imply we need a separate frame pointer. 2260 // 2261 // Try to use s32 as the SP, but move it if it would interfere with input 2262 // arguments. This won't work with calls though. 2263 // 2264 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2265 // registers. 2266 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2267 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2268 } else { 2269 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2270 2271 if (MFI.hasCalls()) 2272 report_fatal_error("call in graphics shader with too many input SGPRs"); 2273 2274 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2275 if (!MRI.isLiveIn(Reg)) { 2276 Info.setStackPtrOffsetReg(Reg); 2277 break; 2278 } 2279 } 2280 2281 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2282 report_fatal_error("failed to find register for SP"); 2283 } 2284 2285 // hasFP should be accurate for entry functions even before the frame is 2286 // finalized, because it does not rely on the known stack size, only 2287 // properties like whether variable sized objects are present. 2288 if (ST.getFrameLowering()->hasFP(MF)) { 2289 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2290 } 2291 } 2292 2293 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2294 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2295 return !Info->isEntryFunction(); 2296 } 2297 2298 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2299 2300 } 2301 2302 void SITargetLowering::insertCopiesSplitCSR( 2303 MachineBasicBlock *Entry, 2304 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2305 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2306 2307 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2308 if (!IStart) 2309 return; 2310 2311 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2312 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2313 MachineBasicBlock::iterator MBBI = Entry->begin(); 2314 for (const MCPhysReg *I = IStart; *I; ++I) { 2315 const TargetRegisterClass *RC = nullptr; 2316 if (AMDGPU::SReg_64RegClass.contains(*I)) 2317 RC = &AMDGPU::SGPR_64RegClass; 2318 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2319 RC = &AMDGPU::SGPR_32RegClass; 2320 else 2321 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2322 2323 Register NewVR = MRI->createVirtualRegister(RC); 2324 // Create copy from CSR to a virtual register. 2325 Entry->addLiveIn(*I); 2326 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2327 .addReg(*I); 2328 2329 // Insert the copy-back instructions right before the terminator. 2330 for (auto *Exit : Exits) 2331 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2332 TII->get(TargetOpcode::COPY), *I) 2333 .addReg(NewVR); 2334 } 2335 } 2336 2337 SDValue SITargetLowering::LowerFormalArguments( 2338 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2339 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2340 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2341 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2342 2343 MachineFunction &MF = DAG.getMachineFunction(); 2344 const Function &Fn = MF.getFunction(); 2345 FunctionType *FType = MF.getFunction().getFunctionType(); 2346 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2347 2348 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) { 2349 DiagnosticInfoUnsupported NoGraphicsHSA( 2350 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2351 DAG.getContext()->diagnose(NoGraphicsHSA); 2352 return DAG.getEntryNode(); 2353 } 2354 2355 Info->allocateModuleLDSGlobal(Fn.getParent()); 2356 2357 SmallVector<ISD::InputArg, 16> Splits; 2358 SmallVector<CCValAssign, 16> ArgLocs; 2359 BitVector Skipped(Ins.size()); 2360 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2361 *DAG.getContext()); 2362 2363 bool IsGraphics = AMDGPU::isGraphics(CallConv); 2364 bool IsKernel = AMDGPU::isKernel(CallConv); 2365 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2366 2367 if (IsGraphics) { 2368 assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && 2369 (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && 2370 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2371 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2372 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2373 !Info->hasWorkItemIDZ()); 2374 } 2375 2376 if (CallConv == CallingConv::AMDGPU_PS) { 2377 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2378 2379 // At least one interpolation mode must be enabled or else the GPU will 2380 // hang. 2381 // 2382 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2383 // set PSInputAddr, the user wants to enable some bits after the compilation 2384 // based on run-time states. Since we can't know what the final PSInputEna 2385 // will look like, so we shouldn't do anything here and the user should take 2386 // responsibility for the correct programming. 2387 // 2388 // Otherwise, the following restrictions apply: 2389 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2390 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2391 // enabled too. 2392 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2393 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) { 2394 CCInfo.AllocateReg(AMDGPU::VGPR0); 2395 CCInfo.AllocateReg(AMDGPU::VGPR1); 2396 Info->markPSInputAllocated(0); 2397 Info->markPSInputEnabled(0); 2398 } 2399 if (Subtarget->isAmdPalOS()) { 2400 // For isAmdPalOS, the user does not enable some bits after compilation 2401 // based on run-time states; the register values being generated here are 2402 // the final ones set in hardware. Therefore we need to apply the 2403 // workaround to PSInputAddr and PSInputEnable together. (The case where 2404 // a bit is set in PSInputAddr but not PSInputEnable is where the 2405 // frontend set up an input arg for a particular interpolation mode, but 2406 // nothing uses that input arg. Really we should have an earlier pass 2407 // that removes such an arg.) 2408 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2409 if ((PsInputBits & 0x7F) == 0 || 2410 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1))) 2411 Info->markPSInputEnabled( 2412 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2413 } 2414 } else if (IsKernel) { 2415 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2416 } else { 2417 Splits.append(Ins.begin(), Ins.end()); 2418 } 2419 2420 if (IsEntryFunc) { 2421 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2422 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2423 } else { 2424 // For the fixed ABI, pass workitem IDs in the last argument register. 2425 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2426 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2427 } 2428 2429 if (IsKernel) { 2430 analyzeFormalArgumentsCompute(CCInfo, Ins); 2431 } else { 2432 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2433 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2434 } 2435 2436 SmallVector<SDValue, 16> Chains; 2437 2438 // FIXME: This is the minimum kernel argument alignment. We should improve 2439 // this to the maximum alignment of the arguments. 2440 // 2441 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2442 // kern arg offset. 2443 const Align KernelArgBaseAlign = Align(16); 2444 2445 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2446 const ISD::InputArg &Arg = Ins[i]; 2447 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2448 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2449 continue; 2450 } 2451 2452 CCValAssign &VA = ArgLocs[ArgIdx++]; 2453 MVT VT = VA.getLocVT(); 2454 2455 if (IsEntryFunc && VA.isMemLoc()) { 2456 VT = Ins[i].VT; 2457 EVT MemVT = VA.getLocVT(); 2458 2459 const uint64_t Offset = VA.getLocMemOffset(); 2460 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2461 2462 if (Arg.Flags.isByRef()) { 2463 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset); 2464 2465 const GCNTargetMachine &TM = 2466 static_cast<const GCNTargetMachine &>(getTargetMachine()); 2467 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS, 2468 Arg.Flags.getPointerAddrSpace())) { 2469 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS, 2470 Arg.Flags.getPointerAddrSpace()); 2471 } 2472 2473 InVals.push_back(Ptr); 2474 continue; 2475 } 2476 2477 SDValue Arg = lowerKernargMemParameter( 2478 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]); 2479 Chains.push_back(Arg.getValue(1)); 2480 2481 auto *ParamTy = 2482 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2483 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2484 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2485 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2486 // On SI local pointers are just offsets into LDS, so they are always 2487 // less than 16-bits. On CI and newer they could potentially be 2488 // real pointers, so we can't guarantee their size. 2489 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2490 DAG.getValueType(MVT::i16)); 2491 } 2492 2493 InVals.push_back(Arg); 2494 continue; 2495 } else if (!IsEntryFunc && VA.isMemLoc()) { 2496 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2497 InVals.push_back(Val); 2498 if (!Arg.Flags.isByVal()) 2499 Chains.push_back(Val.getValue(1)); 2500 continue; 2501 } 2502 2503 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2504 2505 Register Reg = VA.getLocReg(); 2506 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2507 EVT ValVT = VA.getValVT(); 2508 2509 Reg = MF.addLiveIn(Reg, RC); 2510 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2511 2512 if (Arg.Flags.isSRet()) { 2513 // The return object should be reasonably addressable. 2514 2515 // FIXME: This helps when the return is a real sret. If it is a 2516 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2517 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2518 unsigned NumBits 2519 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2520 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2521 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2522 } 2523 2524 // If this is an 8 or 16-bit value, it is really passed promoted 2525 // to 32 bits. Insert an assert[sz]ext to capture this, then 2526 // truncate to the right size. 2527 switch (VA.getLocInfo()) { 2528 case CCValAssign::Full: 2529 break; 2530 case CCValAssign::BCvt: 2531 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2532 break; 2533 case CCValAssign::SExt: 2534 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2535 DAG.getValueType(ValVT)); 2536 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2537 break; 2538 case CCValAssign::ZExt: 2539 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2540 DAG.getValueType(ValVT)); 2541 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2542 break; 2543 case CCValAssign::AExt: 2544 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2545 break; 2546 default: 2547 llvm_unreachable("Unknown loc info!"); 2548 } 2549 2550 InVals.push_back(Val); 2551 } 2552 2553 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2554 // Special inputs come after user arguments. 2555 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2556 } 2557 2558 // Start adding system SGPRs. 2559 if (IsEntryFunc) { 2560 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics); 2561 } else { 2562 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2563 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2564 } 2565 2566 auto &ArgUsageInfo = 2567 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2568 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2569 2570 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2571 Info->setBytesInStackArgArea(StackArgSize); 2572 2573 return Chains.empty() ? Chain : 2574 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2575 } 2576 2577 // TODO: If return values can't fit in registers, we should return as many as 2578 // possible in registers before passing on stack. 2579 bool SITargetLowering::CanLowerReturn( 2580 CallingConv::ID CallConv, 2581 MachineFunction &MF, bool IsVarArg, 2582 const SmallVectorImpl<ISD::OutputArg> &Outs, 2583 LLVMContext &Context) const { 2584 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2585 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2586 // for shaders. Vector types should be explicitly handled by CC. 2587 if (AMDGPU::isEntryFunctionCC(CallConv)) 2588 return true; 2589 2590 SmallVector<CCValAssign, 16> RVLocs; 2591 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2592 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2593 } 2594 2595 SDValue 2596 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2597 bool isVarArg, 2598 const SmallVectorImpl<ISD::OutputArg> &Outs, 2599 const SmallVectorImpl<SDValue> &OutVals, 2600 const SDLoc &DL, SelectionDAG &DAG) const { 2601 MachineFunction &MF = DAG.getMachineFunction(); 2602 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2603 2604 if (AMDGPU::isKernel(CallConv)) { 2605 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2606 OutVals, DL, DAG); 2607 } 2608 2609 bool IsShader = AMDGPU::isShader(CallConv); 2610 2611 Info->setIfReturnsVoid(Outs.empty()); 2612 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2613 2614 // CCValAssign - represent the assignment of the return value to a location. 2615 SmallVector<CCValAssign, 48> RVLocs; 2616 SmallVector<ISD::OutputArg, 48> Splits; 2617 2618 // CCState - Info about the registers and stack slots. 2619 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2620 *DAG.getContext()); 2621 2622 // Analyze outgoing return values. 2623 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2624 2625 SDValue Flag; 2626 SmallVector<SDValue, 48> RetOps; 2627 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2628 2629 // Add return address for callable functions. 2630 if (!Info->isEntryFunction()) { 2631 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2632 SDValue ReturnAddrReg = CreateLiveInRegister( 2633 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2634 2635 SDValue ReturnAddrVirtualReg = 2636 DAG.getRegister(MF.getRegInfo().createVirtualRegister( 2637 CallConv != CallingConv::AMDGPU_Gfx 2638 ? &AMDGPU::CCR_SGPR_64RegClass 2639 : &AMDGPU::Gfx_CCR_SGPR_64RegClass), 2640 MVT::i64); 2641 Chain = 2642 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2643 Flag = Chain.getValue(1); 2644 RetOps.push_back(ReturnAddrVirtualReg); 2645 } 2646 2647 // Copy the result values into the output registers. 2648 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2649 ++I, ++RealRVLocIdx) { 2650 CCValAssign &VA = RVLocs[I]; 2651 assert(VA.isRegLoc() && "Can only return in registers!"); 2652 // TODO: Partially return in registers if return values don't fit. 2653 SDValue Arg = OutVals[RealRVLocIdx]; 2654 2655 // Copied from other backends. 2656 switch (VA.getLocInfo()) { 2657 case CCValAssign::Full: 2658 break; 2659 case CCValAssign::BCvt: 2660 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2661 break; 2662 case CCValAssign::SExt: 2663 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2664 break; 2665 case CCValAssign::ZExt: 2666 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2667 break; 2668 case CCValAssign::AExt: 2669 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2670 break; 2671 default: 2672 llvm_unreachable("Unknown loc info!"); 2673 } 2674 2675 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2676 Flag = Chain.getValue(1); 2677 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2678 } 2679 2680 // FIXME: Does sret work properly? 2681 if (!Info->isEntryFunction()) { 2682 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2683 const MCPhysReg *I = 2684 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2685 if (I) { 2686 for (; *I; ++I) { 2687 if (AMDGPU::SReg_64RegClass.contains(*I)) 2688 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2689 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2690 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2691 else 2692 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2693 } 2694 } 2695 } 2696 2697 // Update chain and glue. 2698 RetOps[0] = Chain; 2699 if (Flag.getNode()) 2700 RetOps.push_back(Flag); 2701 2702 unsigned Opc = AMDGPUISD::ENDPGM; 2703 if (!IsWaveEnd) { 2704 if (IsShader) 2705 Opc = AMDGPUISD::RETURN_TO_EPILOG; 2706 else if (CallConv == CallingConv::AMDGPU_Gfx) 2707 Opc = AMDGPUISD::RET_GFX_FLAG; 2708 else 2709 Opc = AMDGPUISD::RET_FLAG; 2710 } 2711 2712 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2713 } 2714 2715 SDValue SITargetLowering::LowerCallResult( 2716 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2717 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2718 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2719 SDValue ThisVal) const { 2720 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2721 2722 // Assign locations to each value returned by this call. 2723 SmallVector<CCValAssign, 16> RVLocs; 2724 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2725 *DAG.getContext()); 2726 CCInfo.AnalyzeCallResult(Ins, RetCC); 2727 2728 // Copy all of the result registers out of their specified physreg. 2729 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2730 CCValAssign VA = RVLocs[i]; 2731 SDValue Val; 2732 2733 if (VA.isRegLoc()) { 2734 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2735 Chain = Val.getValue(1); 2736 InFlag = Val.getValue(2); 2737 } else if (VA.isMemLoc()) { 2738 report_fatal_error("TODO: return values in memory"); 2739 } else 2740 llvm_unreachable("unknown argument location type"); 2741 2742 switch (VA.getLocInfo()) { 2743 case CCValAssign::Full: 2744 break; 2745 case CCValAssign::BCvt: 2746 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2747 break; 2748 case CCValAssign::ZExt: 2749 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2750 DAG.getValueType(VA.getValVT())); 2751 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2752 break; 2753 case CCValAssign::SExt: 2754 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2755 DAG.getValueType(VA.getValVT())); 2756 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2757 break; 2758 case CCValAssign::AExt: 2759 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2760 break; 2761 default: 2762 llvm_unreachable("Unknown loc info!"); 2763 } 2764 2765 InVals.push_back(Val); 2766 } 2767 2768 return Chain; 2769 } 2770 2771 // Add code to pass special inputs required depending on used features separate 2772 // from the explicit user arguments present in the IR. 2773 void SITargetLowering::passSpecialInputs( 2774 CallLoweringInfo &CLI, 2775 CCState &CCInfo, 2776 const SIMachineFunctionInfo &Info, 2777 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2778 SmallVectorImpl<SDValue> &MemOpChains, 2779 SDValue Chain) const { 2780 // If we don't have a call site, this was a call inserted by 2781 // legalization. These can never use special inputs. 2782 if (!CLI.CB) 2783 return; 2784 2785 SelectionDAG &DAG = CLI.DAG; 2786 const SDLoc &DL = CLI.DL; 2787 2788 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2789 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2790 2791 const AMDGPUFunctionArgInfo *CalleeArgInfo 2792 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2793 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2794 auto &ArgUsageInfo = 2795 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2796 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2797 } 2798 2799 // TODO: Unify with private memory register handling. This is complicated by 2800 // the fact that at least in kernels, the input argument is not necessarily 2801 // in the same location as the input. 2802 static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue, 2803 StringLiteral> ImplicitAttrs[] = { 2804 {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"}, 2805 {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" }, 2806 {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"}, 2807 {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"}, 2808 {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"}, 2809 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"}, 2810 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"} 2811 }; 2812 2813 for (auto Attr : ImplicitAttrs) { 2814 const ArgDescriptor *OutgoingArg; 2815 const TargetRegisterClass *ArgRC; 2816 LLT ArgTy; 2817 2818 AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first; 2819 2820 // If the callee does not use the attribute value, skip copying the value. 2821 if (CLI.CB->hasFnAttr(Attr.second)) 2822 continue; 2823 2824 std::tie(OutgoingArg, ArgRC, ArgTy) = 2825 CalleeArgInfo->getPreloadedValue(InputID); 2826 if (!OutgoingArg) 2827 continue; 2828 2829 const ArgDescriptor *IncomingArg; 2830 const TargetRegisterClass *IncomingArgRC; 2831 LLT Ty; 2832 std::tie(IncomingArg, IncomingArgRC, Ty) = 2833 CallerArgInfo.getPreloadedValue(InputID); 2834 assert(IncomingArgRC == ArgRC); 2835 2836 // All special arguments are ints for now. 2837 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2838 SDValue InputReg; 2839 2840 if (IncomingArg) { 2841 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2842 } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) { 2843 // The implicit arg ptr is special because it doesn't have a corresponding 2844 // input for kernels, and is computed from the kernarg segment pointer. 2845 InputReg = getImplicitArgPtr(DAG, DL); 2846 } else { 2847 // We may have proven the input wasn't needed, although the ABI is 2848 // requiring it. We just need to allocate the register appropriately. 2849 InputReg = DAG.getUNDEF(ArgVT); 2850 } 2851 2852 if (OutgoingArg->isRegister()) { 2853 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2854 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2855 report_fatal_error("failed to allocate implicit input argument"); 2856 } else { 2857 unsigned SpecialArgOffset = 2858 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2859 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2860 SpecialArgOffset); 2861 MemOpChains.push_back(ArgStore); 2862 } 2863 } 2864 2865 // Pack workitem IDs into a single register or pass it as is if already 2866 // packed. 2867 const ArgDescriptor *OutgoingArg; 2868 const TargetRegisterClass *ArgRC; 2869 LLT Ty; 2870 2871 std::tie(OutgoingArg, ArgRC, Ty) = 2872 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2873 if (!OutgoingArg) 2874 std::tie(OutgoingArg, ArgRC, Ty) = 2875 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2876 if (!OutgoingArg) 2877 std::tie(OutgoingArg, ArgRC, Ty) = 2878 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2879 if (!OutgoingArg) 2880 return; 2881 2882 const ArgDescriptor *IncomingArgX = std::get<0>( 2883 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2884 const ArgDescriptor *IncomingArgY = std::get<0>( 2885 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2886 const ArgDescriptor *IncomingArgZ = std::get<0>( 2887 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2888 2889 SDValue InputReg; 2890 SDLoc SL; 2891 2892 const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x"); 2893 const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y"); 2894 const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z"); 2895 2896 // If incoming ids are not packed we need to pack them. 2897 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX && 2898 NeedWorkItemIDX) 2899 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2900 2901 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY && 2902 NeedWorkItemIDY) { 2903 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2904 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2905 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2906 InputReg = InputReg.getNode() ? 2907 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2908 } 2909 2910 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ && 2911 NeedWorkItemIDZ) { 2912 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2913 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2914 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2915 InputReg = InputReg.getNode() ? 2916 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2917 } 2918 2919 if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) { 2920 // Workitem ids are already packed, any of present incoming arguments 2921 // will carry all required fields. 2922 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2923 IncomingArgX ? *IncomingArgX : 2924 IncomingArgY ? *IncomingArgY : 2925 *IncomingArgZ, ~0u); 2926 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2927 } 2928 2929 if (OutgoingArg->isRegister()) { 2930 if (InputReg) 2931 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2932 2933 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2934 } else { 2935 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2936 if (InputReg) { 2937 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2938 SpecialArgOffset); 2939 MemOpChains.push_back(ArgStore); 2940 } 2941 } 2942 } 2943 2944 static bool canGuaranteeTCO(CallingConv::ID CC) { 2945 return CC == CallingConv::Fast; 2946 } 2947 2948 /// Return true if we might ever do TCO for calls with this calling convention. 2949 static bool mayTailCallThisCC(CallingConv::ID CC) { 2950 switch (CC) { 2951 case CallingConv::C: 2952 case CallingConv::AMDGPU_Gfx: 2953 return true; 2954 default: 2955 return canGuaranteeTCO(CC); 2956 } 2957 } 2958 2959 bool SITargetLowering::isEligibleForTailCallOptimization( 2960 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2961 const SmallVectorImpl<ISD::OutputArg> &Outs, 2962 const SmallVectorImpl<SDValue> &OutVals, 2963 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2964 if (!mayTailCallThisCC(CalleeCC)) 2965 return false; 2966 2967 // For a divergent call target, we need to do a waterfall loop over the 2968 // possible callees which precludes us from using a simple jump. 2969 if (Callee->isDivergent()) 2970 return false; 2971 2972 MachineFunction &MF = DAG.getMachineFunction(); 2973 const Function &CallerF = MF.getFunction(); 2974 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2975 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2976 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2977 2978 // Kernels aren't callable, and don't have a live in return address so it 2979 // doesn't make sense to do a tail call with entry functions. 2980 if (!CallerPreserved) 2981 return false; 2982 2983 bool CCMatch = CallerCC == CalleeCC; 2984 2985 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2986 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2987 return true; 2988 return false; 2989 } 2990 2991 // TODO: Can we handle var args? 2992 if (IsVarArg) 2993 return false; 2994 2995 for (const Argument &Arg : CallerF.args()) { 2996 if (Arg.hasByValAttr()) 2997 return false; 2998 } 2999 3000 LLVMContext &Ctx = *DAG.getContext(); 3001 3002 // Check that the call results are passed in the same way. 3003 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 3004 CCAssignFnForCall(CalleeCC, IsVarArg), 3005 CCAssignFnForCall(CallerCC, IsVarArg))) 3006 return false; 3007 3008 // The callee has to preserve all registers the caller needs to preserve. 3009 if (!CCMatch) { 3010 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 3011 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 3012 return false; 3013 } 3014 3015 // Nothing more to check if the callee is taking no arguments. 3016 if (Outs.empty()) 3017 return true; 3018 3019 SmallVector<CCValAssign, 16> ArgLocs; 3020 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 3021 3022 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 3023 3024 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 3025 // If the stack arguments for this call do not fit into our own save area then 3026 // the call cannot be made tail. 3027 // TODO: Is this really necessary? 3028 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 3029 return false; 3030 3031 const MachineRegisterInfo &MRI = MF.getRegInfo(); 3032 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 3033 } 3034 3035 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 3036 if (!CI->isTailCall()) 3037 return false; 3038 3039 const Function *ParentFn = CI->getParent()->getParent(); 3040 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 3041 return false; 3042 return true; 3043 } 3044 3045 // The wave scratch offset register is used as the global base pointer. 3046 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 3047 SmallVectorImpl<SDValue> &InVals) const { 3048 SelectionDAG &DAG = CLI.DAG; 3049 const SDLoc &DL = CLI.DL; 3050 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 3051 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 3052 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 3053 SDValue Chain = CLI.Chain; 3054 SDValue Callee = CLI.Callee; 3055 bool &IsTailCall = CLI.IsTailCall; 3056 CallingConv::ID CallConv = CLI.CallConv; 3057 bool IsVarArg = CLI.IsVarArg; 3058 bool IsSibCall = false; 3059 bool IsThisReturn = false; 3060 MachineFunction &MF = DAG.getMachineFunction(); 3061 3062 if (Callee.isUndef() || isNullConstant(Callee)) { 3063 if (!CLI.IsTailCall) { 3064 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 3065 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 3066 } 3067 3068 return Chain; 3069 } 3070 3071 if (IsVarArg) { 3072 return lowerUnhandledCall(CLI, InVals, 3073 "unsupported call to variadic function "); 3074 } 3075 3076 if (!CLI.CB) 3077 report_fatal_error("unsupported libcall legalization"); 3078 3079 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 3080 return lowerUnhandledCall(CLI, InVals, 3081 "unsupported required tail call to function "); 3082 } 3083 3084 if (AMDGPU::isShader(CallConv)) { 3085 // Note the issue is with the CC of the called function, not of the call 3086 // itself. 3087 return lowerUnhandledCall(CLI, InVals, 3088 "unsupported call to a shader function "); 3089 } 3090 3091 if (AMDGPU::isShader(MF.getFunction().getCallingConv()) && 3092 CallConv != CallingConv::AMDGPU_Gfx) { 3093 // Only allow calls with specific calling conventions. 3094 return lowerUnhandledCall(CLI, InVals, 3095 "unsupported calling convention for call from " 3096 "graphics shader of function "); 3097 } 3098 3099 if (IsTailCall) { 3100 IsTailCall = isEligibleForTailCallOptimization( 3101 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 3102 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 3103 report_fatal_error("failed to perform tail call elimination on a call " 3104 "site marked musttail"); 3105 } 3106 3107 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 3108 3109 // A sibling call is one where we're under the usual C ABI and not planning 3110 // to change that but can still do a tail call: 3111 if (!TailCallOpt && IsTailCall) 3112 IsSibCall = true; 3113 3114 if (IsTailCall) 3115 ++NumTailCalls; 3116 } 3117 3118 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3119 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3120 SmallVector<SDValue, 8> MemOpChains; 3121 3122 // Analyze operands of the call, assigning locations to each operand. 3123 SmallVector<CCValAssign, 16> ArgLocs; 3124 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 3125 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 3126 3127 if (AMDGPUTargetMachine::EnableFixedFunctionABI && 3128 CallConv != CallingConv::AMDGPU_Gfx) { 3129 // With a fixed ABI, allocate fixed registers before user arguments. 3130 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3131 } 3132 3133 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 3134 3135 // Get a count of how many bytes are to be pushed on the stack. 3136 unsigned NumBytes = CCInfo.getNextStackOffset(); 3137 3138 if (IsSibCall) { 3139 // Since we're not changing the ABI to make this a tail call, the memory 3140 // operands are already available in the caller's incoming argument space. 3141 NumBytes = 0; 3142 } 3143 3144 // FPDiff is the byte offset of the call's argument area from the callee's. 3145 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3146 // by this amount for a tail call. In a sibling call it must be 0 because the 3147 // caller will deallocate the entire stack and the callee still expects its 3148 // arguments to begin at SP+0. Completely unused for non-tail calls. 3149 int32_t FPDiff = 0; 3150 MachineFrameInfo &MFI = MF.getFrameInfo(); 3151 3152 // Adjust the stack pointer for the new arguments... 3153 // These operations are automatically eliminated by the prolog/epilog pass 3154 if (!IsSibCall) { 3155 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 3156 3157 if (!Subtarget->enableFlatScratch()) { 3158 SmallVector<SDValue, 4> CopyFromChains; 3159 3160 // In the HSA case, this should be an identity copy. 3161 SDValue ScratchRSrcReg 3162 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 3163 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 3164 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 3165 Chain = DAG.getTokenFactor(DL, CopyFromChains); 3166 } 3167 } 3168 3169 MVT PtrVT = MVT::i32; 3170 3171 // Walk the register/memloc assignments, inserting copies/loads. 3172 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3173 CCValAssign &VA = ArgLocs[i]; 3174 SDValue Arg = OutVals[i]; 3175 3176 // Promote the value if needed. 3177 switch (VA.getLocInfo()) { 3178 case CCValAssign::Full: 3179 break; 3180 case CCValAssign::BCvt: 3181 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3182 break; 3183 case CCValAssign::ZExt: 3184 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3185 break; 3186 case CCValAssign::SExt: 3187 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3188 break; 3189 case CCValAssign::AExt: 3190 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3191 break; 3192 case CCValAssign::FPExt: 3193 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3194 break; 3195 default: 3196 llvm_unreachable("Unknown loc info!"); 3197 } 3198 3199 if (VA.isRegLoc()) { 3200 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3201 } else { 3202 assert(VA.isMemLoc()); 3203 3204 SDValue DstAddr; 3205 MachinePointerInfo DstInfo; 3206 3207 unsigned LocMemOffset = VA.getLocMemOffset(); 3208 int32_t Offset = LocMemOffset; 3209 3210 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3211 MaybeAlign Alignment; 3212 3213 if (IsTailCall) { 3214 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3215 unsigned OpSize = Flags.isByVal() ? 3216 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3217 3218 // FIXME: We can have better than the minimum byval required alignment. 3219 Alignment = 3220 Flags.isByVal() 3221 ? Flags.getNonZeroByValAlign() 3222 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3223 3224 Offset = Offset + FPDiff; 3225 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3226 3227 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3228 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3229 3230 // Make sure any stack arguments overlapping with where we're storing 3231 // are loaded before this eventual operation. Otherwise they'll be 3232 // clobbered. 3233 3234 // FIXME: Why is this really necessary? This seems to just result in a 3235 // lot of code to copy the stack and write them back to the same 3236 // locations, which are supposed to be immutable? 3237 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3238 } else { 3239 // Stores to the argument stack area are relative to the stack pointer. 3240 SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(), 3241 MVT::i32); 3242 DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff); 3243 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3244 Alignment = 3245 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3246 } 3247 3248 if (Outs[i].Flags.isByVal()) { 3249 SDValue SizeNode = 3250 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3251 SDValue Cpy = 3252 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3253 Outs[i].Flags.getNonZeroByValAlign(), 3254 /*isVol = */ false, /*AlwaysInline = */ true, 3255 /*isTailCall = */ false, DstInfo, 3256 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3257 3258 MemOpChains.push_back(Cpy); 3259 } else { 3260 SDValue Store = 3261 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment); 3262 MemOpChains.push_back(Store); 3263 } 3264 } 3265 } 3266 3267 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 3268 CallConv != CallingConv::AMDGPU_Gfx) { 3269 // Copy special input registers after user input arguments. 3270 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3271 } 3272 3273 if (!MemOpChains.empty()) 3274 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3275 3276 // Build a sequence of copy-to-reg nodes chained together with token chain 3277 // and flag operands which copy the outgoing args into the appropriate regs. 3278 SDValue InFlag; 3279 for (auto &RegToPass : RegsToPass) { 3280 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3281 RegToPass.second, InFlag); 3282 InFlag = Chain.getValue(1); 3283 } 3284 3285 3286 SDValue PhysReturnAddrReg; 3287 if (IsTailCall) { 3288 // Since the return is being combined with the call, we need to pass on the 3289 // return address. 3290 3291 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3292 SDValue ReturnAddrReg = CreateLiveInRegister( 3293 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 3294 3295 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3296 MVT::i64); 3297 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3298 InFlag = Chain.getValue(1); 3299 } 3300 3301 // We don't usually want to end the call-sequence here because we would tidy 3302 // the frame up *after* the call, however in the ABI-changing tail-call case 3303 // we've carefully laid out the parameters so that when sp is reset they'll be 3304 // in the correct location. 3305 if (IsTailCall && !IsSibCall) { 3306 Chain = DAG.getCALLSEQ_END(Chain, 3307 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3308 DAG.getTargetConstant(0, DL, MVT::i32), 3309 InFlag, DL); 3310 InFlag = Chain.getValue(1); 3311 } 3312 3313 std::vector<SDValue> Ops; 3314 Ops.push_back(Chain); 3315 Ops.push_back(Callee); 3316 // Add a redundant copy of the callee global which will not be legalized, as 3317 // we need direct access to the callee later. 3318 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3319 const GlobalValue *GV = GSD->getGlobal(); 3320 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3321 } else { 3322 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3323 } 3324 3325 if (IsTailCall) { 3326 // Each tail call may have to adjust the stack by a different amount, so 3327 // this information must travel along with the operation for eventual 3328 // consumption by emitEpilogue. 3329 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3330 3331 Ops.push_back(PhysReturnAddrReg); 3332 } 3333 3334 // Add argument registers to the end of the list so that they are known live 3335 // into the call. 3336 for (auto &RegToPass : RegsToPass) { 3337 Ops.push_back(DAG.getRegister(RegToPass.first, 3338 RegToPass.second.getValueType())); 3339 } 3340 3341 // Add a register mask operand representing the call-preserved registers. 3342 3343 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3344 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3345 assert(Mask && "Missing call preserved mask for calling convention"); 3346 Ops.push_back(DAG.getRegisterMask(Mask)); 3347 3348 if (InFlag.getNode()) 3349 Ops.push_back(InFlag); 3350 3351 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3352 3353 // If we're doing a tall call, use a TC_RETURN here rather than an 3354 // actual call instruction. 3355 if (IsTailCall) { 3356 MFI.setHasTailCall(); 3357 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3358 } 3359 3360 // Returns a chain and a flag for retval copy to use. 3361 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3362 Chain = Call.getValue(0); 3363 InFlag = Call.getValue(1); 3364 3365 uint64_t CalleePopBytes = NumBytes; 3366 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3367 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3368 InFlag, DL); 3369 if (!Ins.empty()) 3370 InFlag = Chain.getValue(1); 3371 3372 // Handle result values, copying them out of physregs into vregs that we 3373 // return. 3374 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3375 InVals, IsThisReturn, 3376 IsThisReturn ? OutVals[0] : SDValue()); 3377 } 3378 3379 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3380 // except for applying the wave size scale to the increment amount. 3381 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3382 SDValue Op, SelectionDAG &DAG) const { 3383 const MachineFunction &MF = DAG.getMachineFunction(); 3384 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3385 3386 SDLoc dl(Op); 3387 EVT VT = Op.getValueType(); 3388 SDValue Tmp1 = Op; 3389 SDValue Tmp2 = Op.getValue(1); 3390 SDValue Tmp3 = Op.getOperand(2); 3391 SDValue Chain = Tmp1.getOperand(0); 3392 3393 Register SPReg = Info->getStackPtrOffsetReg(); 3394 3395 // Chain the dynamic stack allocation so that it doesn't modify the stack 3396 // pointer when other instructions are using the stack. 3397 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3398 3399 SDValue Size = Tmp2.getOperand(1); 3400 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3401 Chain = SP.getValue(1); 3402 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3403 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3404 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3405 unsigned Opc = 3406 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3407 ISD::ADD : ISD::SUB; 3408 3409 SDValue ScaledSize = DAG.getNode( 3410 ISD::SHL, dl, VT, Size, 3411 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3412 3413 Align StackAlign = TFL->getStackAlign(); 3414 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3415 if (Alignment && *Alignment > StackAlign) { 3416 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3417 DAG.getConstant(-(uint64_t)Alignment->value() 3418 << ST.getWavefrontSizeLog2(), 3419 dl, VT)); 3420 } 3421 3422 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3423 Tmp2 = DAG.getCALLSEQ_END( 3424 Chain, DAG.getIntPtrConstant(0, dl, true), 3425 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3426 3427 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3428 } 3429 3430 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3431 SelectionDAG &DAG) const { 3432 // We only handle constant sizes here to allow non-entry block, static sized 3433 // allocas. A truly dynamic value is more difficult to support because we 3434 // don't know if the size value is uniform or not. If the size isn't uniform, 3435 // we would need to do a wave reduction to get the maximum size to know how 3436 // much to increment the uniform stack pointer. 3437 SDValue Size = Op.getOperand(1); 3438 if (isa<ConstantSDNode>(Size)) 3439 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3440 3441 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3442 } 3443 3444 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3445 const MachineFunction &MF) const { 3446 Register Reg = StringSwitch<Register>(RegName) 3447 .Case("m0", AMDGPU::M0) 3448 .Case("exec", AMDGPU::EXEC) 3449 .Case("exec_lo", AMDGPU::EXEC_LO) 3450 .Case("exec_hi", AMDGPU::EXEC_HI) 3451 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3452 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3453 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3454 .Default(Register()); 3455 3456 if (Reg == AMDGPU::NoRegister) { 3457 report_fatal_error(Twine("invalid register name \"" 3458 + StringRef(RegName) + "\".")); 3459 3460 } 3461 3462 if (!Subtarget->hasFlatScrRegister() && 3463 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3464 report_fatal_error(Twine("invalid register \"" 3465 + StringRef(RegName) + "\" for subtarget.")); 3466 } 3467 3468 switch (Reg) { 3469 case AMDGPU::M0: 3470 case AMDGPU::EXEC_LO: 3471 case AMDGPU::EXEC_HI: 3472 case AMDGPU::FLAT_SCR_LO: 3473 case AMDGPU::FLAT_SCR_HI: 3474 if (VT.getSizeInBits() == 32) 3475 return Reg; 3476 break; 3477 case AMDGPU::EXEC: 3478 case AMDGPU::FLAT_SCR: 3479 if (VT.getSizeInBits() == 64) 3480 return Reg; 3481 break; 3482 default: 3483 llvm_unreachable("missing register type checking"); 3484 } 3485 3486 report_fatal_error(Twine("invalid type for register \"" 3487 + StringRef(RegName) + "\".")); 3488 } 3489 3490 // If kill is not the last instruction, split the block so kill is always a 3491 // proper terminator. 3492 MachineBasicBlock * 3493 SITargetLowering::splitKillBlock(MachineInstr &MI, 3494 MachineBasicBlock *BB) const { 3495 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/); 3496 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3497 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3498 return SplitBB; 3499 } 3500 3501 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3502 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3503 // be the first instruction in the remainder block. 3504 // 3505 /// \returns { LoopBody, Remainder } 3506 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3507 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3508 MachineFunction *MF = MBB.getParent(); 3509 MachineBasicBlock::iterator I(&MI); 3510 3511 // To insert the loop we need to split the block. Move everything after this 3512 // point to a new block, and insert a new empty block between the two. 3513 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3514 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3515 MachineFunction::iterator MBBI(MBB); 3516 ++MBBI; 3517 3518 MF->insert(MBBI, LoopBB); 3519 MF->insert(MBBI, RemainderBB); 3520 3521 LoopBB->addSuccessor(LoopBB); 3522 LoopBB->addSuccessor(RemainderBB); 3523 3524 // Move the rest of the block into a new block. 3525 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3526 3527 if (InstInLoop) { 3528 auto Next = std::next(I); 3529 3530 // Move instruction to loop body. 3531 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3532 3533 // Move the rest of the block. 3534 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3535 } else { 3536 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3537 } 3538 3539 MBB.addSuccessor(LoopBB); 3540 3541 return std::make_pair(LoopBB, RemainderBB); 3542 } 3543 3544 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3545 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3546 MachineBasicBlock *MBB = MI.getParent(); 3547 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3548 auto I = MI.getIterator(); 3549 auto E = std::next(I); 3550 3551 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3552 .addImm(0); 3553 3554 MIBundleBuilder Bundler(*MBB, I, E); 3555 finalizeBundle(*MBB, Bundler.begin()); 3556 } 3557 3558 MachineBasicBlock * 3559 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3560 MachineBasicBlock *BB) const { 3561 const DebugLoc &DL = MI.getDebugLoc(); 3562 3563 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3564 3565 MachineBasicBlock *LoopBB; 3566 MachineBasicBlock *RemainderBB; 3567 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3568 3569 // Apparently kill flags are only valid if the def is in the same block? 3570 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3571 Src->setIsKill(false); 3572 3573 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3574 3575 MachineBasicBlock::iterator I = LoopBB->end(); 3576 3577 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3578 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3579 3580 // Clear TRAP_STS.MEM_VIOL 3581 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3582 .addImm(0) 3583 .addImm(EncodedReg); 3584 3585 bundleInstWithWaitcnt(MI); 3586 3587 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3588 3589 // Load and check TRAP_STS.MEM_VIOL 3590 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3591 .addImm(EncodedReg); 3592 3593 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3594 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3595 .addReg(Reg, RegState::Kill) 3596 .addImm(0); 3597 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3598 .addMBB(LoopBB); 3599 3600 return RemainderBB; 3601 } 3602 3603 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3604 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3605 // will only do one iteration. In the worst case, this will loop 64 times. 3606 // 3607 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3608 static MachineBasicBlock::iterator 3609 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI, 3610 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB, 3611 const DebugLoc &DL, const MachineOperand &Idx, 3612 unsigned InitReg, unsigned ResultReg, unsigned PhiReg, 3613 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode, 3614 Register &SGPRIdxReg) { 3615 3616 MachineFunction *MF = OrigBB.getParent(); 3617 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3618 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3619 MachineBasicBlock::iterator I = LoopBB.begin(); 3620 3621 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3622 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3623 Register NewExec = MRI.createVirtualRegister(BoolRC); 3624 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3625 Register CondReg = MRI.createVirtualRegister(BoolRC); 3626 3627 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3628 .addReg(InitReg) 3629 .addMBB(&OrigBB) 3630 .addReg(ResultReg) 3631 .addMBB(&LoopBB); 3632 3633 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3634 .addReg(InitSaveExecReg) 3635 .addMBB(&OrigBB) 3636 .addReg(NewExec) 3637 .addMBB(&LoopBB); 3638 3639 // Read the next variant <- also loop target. 3640 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3641 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef())); 3642 3643 // Compare the just read M0 value to all possible Idx values. 3644 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3645 .addReg(CurrentIdxReg) 3646 .addReg(Idx.getReg(), 0, Idx.getSubReg()); 3647 3648 // Update EXEC, save the original EXEC value to VCC. 3649 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3650 : AMDGPU::S_AND_SAVEEXEC_B64), 3651 NewExec) 3652 .addReg(CondReg, RegState::Kill); 3653 3654 MRI.setSimpleHint(NewExec, CondReg); 3655 3656 if (UseGPRIdxMode) { 3657 if (Offset == 0) { 3658 SGPRIdxReg = CurrentIdxReg; 3659 } else { 3660 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3661 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg) 3662 .addReg(CurrentIdxReg, RegState::Kill) 3663 .addImm(Offset); 3664 } 3665 } else { 3666 // Move index from VCC into M0 3667 if (Offset == 0) { 3668 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3669 .addReg(CurrentIdxReg, RegState::Kill); 3670 } else { 3671 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3672 .addReg(CurrentIdxReg, RegState::Kill) 3673 .addImm(Offset); 3674 } 3675 } 3676 3677 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3678 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3679 MachineInstr *InsertPt = 3680 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3681 : AMDGPU::S_XOR_B64_term), Exec) 3682 .addReg(Exec) 3683 .addReg(NewExec); 3684 3685 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3686 // s_cbranch_scc0? 3687 3688 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3689 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3690 .addMBB(&LoopBB); 3691 3692 return InsertPt->getIterator(); 3693 } 3694 3695 // This has slightly sub-optimal regalloc when the source vector is killed by 3696 // the read. The register allocator does not understand that the kill is 3697 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3698 // subregister from it, using 1 more VGPR than necessary. This was saved when 3699 // this was expanded after register allocation. 3700 static MachineBasicBlock::iterator 3701 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI, 3702 unsigned InitResultReg, unsigned PhiReg, int Offset, 3703 bool UseGPRIdxMode, Register &SGPRIdxReg) { 3704 MachineFunction *MF = MBB.getParent(); 3705 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3706 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3707 MachineRegisterInfo &MRI = MF->getRegInfo(); 3708 const DebugLoc &DL = MI.getDebugLoc(); 3709 MachineBasicBlock::iterator I(&MI); 3710 3711 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3712 Register DstReg = MI.getOperand(0).getReg(); 3713 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3714 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3715 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3716 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3717 3718 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3719 3720 // Save the EXEC mask 3721 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3722 .addReg(Exec); 3723 3724 MachineBasicBlock *LoopBB; 3725 MachineBasicBlock *RemainderBB; 3726 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3727 3728 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3729 3730 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3731 InitResultReg, DstReg, PhiReg, TmpExec, 3732 Offset, UseGPRIdxMode, SGPRIdxReg); 3733 3734 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3735 MachineFunction::iterator MBBI(LoopBB); 3736 ++MBBI; 3737 MF->insert(MBBI, LandingPad); 3738 LoopBB->removeSuccessor(RemainderBB); 3739 LandingPad->addSuccessor(RemainderBB); 3740 LoopBB->addSuccessor(LandingPad); 3741 MachineBasicBlock::iterator First = LandingPad->begin(); 3742 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3743 .addReg(SaveExec); 3744 3745 return InsPt; 3746 } 3747 3748 // Returns subreg index, offset 3749 static std::pair<unsigned, int> 3750 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3751 const TargetRegisterClass *SuperRC, 3752 unsigned VecReg, 3753 int Offset) { 3754 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3755 3756 // Skip out of bounds offsets, or else we would end up using an undefined 3757 // register. 3758 if (Offset >= NumElts || Offset < 0) 3759 return std::make_pair(AMDGPU::sub0, Offset); 3760 3761 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3762 } 3763 3764 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3765 MachineRegisterInfo &MRI, MachineInstr &MI, 3766 int Offset) { 3767 MachineBasicBlock *MBB = MI.getParent(); 3768 const DebugLoc &DL = MI.getDebugLoc(); 3769 MachineBasicBlock::iterator I(&MI); 3770 3771 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3772 3773 assert(Idx->getReg() != AMDGPU::NoRegister); 3774 3775 if (Offset == 0) { 3776 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx); 3777 } else { 3778 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3779 .add(*Idx) 3780 .addImm(Offset); 3781 } 3782 } 3783 3784 static Register getIndirectSGPRIdx(const SIInstrInfo *TII, 3785 MachineRegisterInfo &MRI, MachineInstr &MI, 3786 int Offset) { 3787 MachineBasicBlock *MBB = MI.getParent(); 3788 const DebugLoc &DL = MI.getDebugLoc(); 3789 MachineBasicBlock::iterator I(&MI); 3790 3791 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3792 3793 if (Offset == 0) 3794 return Idx->getReg(); 3795 3796 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3797 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3798 .add(*Idx) 3799 .addImm(Offset); 3800 return Tmp; 3801 } 3802 3803 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3804 MachineBasicBlock &MBB, 3805 const GCNSubtarget &ST) { 3806 const SIInstrInfo *TII = ST.getInstrInfo(); 3807 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3808 MachineFunction *MF = MBB.getParent(); 3809 MachineRegisterInfo &MRI = MF->getRegInfo(); 3810 3811 Register Dst = MI.getOperand(0).getReg(); 3812 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3813 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3814 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3815 3816 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3817 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3818 3819 unsigned SubReg; 3820 std::tie(SubReg, Offset) 3821 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3822 3823 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3824 3825 // Check for a SGPR index. 3826 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3827 MachineBasicBlock::iterator I(&MI); 3828 const DebugLoc &DL = MI.getDebugLoc(); 3829 3830 if (UseGPRIdxMode) { 3831 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3832 // to avoid interfering with other uses, so probably requires a new 3833 // optimization pass. 3834 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3835 3836 const MCInstrDesc &GPRIDXDesc = 3837 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3838 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3839 .addReg(SrcReg) 3840 .addReg(Idx) 3841 .addImm(SubReg); 3842 } else { 3843 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3844 3845 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3846 .addReg(SrcReg, 0, SubReg) 3847 .addReg(SrcReg, RegState::Implicit); 3848 } 3849 3850 MI.eraseFromParent(); 3851 3852 return &MBB; 3853 } 3854 3855 // Control flow needs to be inserted if indexing with a VGPR. 3856 const DebugLoc &DL = MI.getDebugLoc(); 3857 MachineBasicBlock::iterator I(&MI); 3858 3859 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3860 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3861 3862 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3863 3864 Register SGPRIdxReg; 3865 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, 3866 UseGPRIdxMode, SGPRIdxReg); 3867 3868 MachineBasicBlock *LoopBB = InsPt->getParent(); 3869 3870 if (UseGPRIdxMode) { 3871 const MCInstrDesc &GPRIDXDesc = 3872 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3873 3874 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3875 .addReg(SrcReg) 3876 .addReg(SGPRIdxReg) 3877 .addImm(SubReg); 3878 } else { 3879 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3880 .addReg(SrcReg, 0, SubReg) 3881 .addReg(SrcReg, RegState::Implicit); 3882 } 3883 3884 MI.eraseFromParent(); 3885 3886 return LoopBB; 3887 } 3888 3889 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3890 MachineBasicBlock &MBB, 3891 const GCNSubtarget &ST) { 3892 const SIInstrInfo *TII = ST.getInstrInfo(); 3893 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3894 MachineFunction *MF = MBB.getParent(); 3895 MachineRegisterInfo &MRI = MF->getRegInfo(); 3896 3897 Register Dst = MI.getOperand(0).getReg(); 3898 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3899 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3900 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3901 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3902 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3903 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3904 3905 // This can be an immediate, but will be folded later. 3906 assert(Val->getReg()); 3907 3908 unsigned SubReg; 3909 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3910 SrcVec->getReg(), 3911 Offset); 3912 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3913 3914 if (Idx->getReg() == AMDGPU::NoRegister) { 3915 MachineBasicBlock::iterator I(&MI); 3916 const DebugLoc &DL = MI.getDebugLoc(); 3917 3918 assert(Offset == 0); 3919 3920 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3921 .add(*SrcVec) 3922 .add(*Val) 3923 .addImm(SubReg); 3924 3925 MI.eraseFromParent(); 3926 return &MBB; 3927 } 3928 3929 // Check for a SGPR index. 3930 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3931 MachineBasicBlock::iterator I(&MI); 3932 const DebugLoc &DL = MI.getDebugLoc(); 3933 3934 if (UseGPRIdxMode) { 3935 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3936 3937 const MCInstrDesc &GPRIDXDesc = 3938 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3939 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3940 .addReg(SrcVec->getReg()) 3941 .add(*Val) 3942 .addReg(Idx) 3943 .addImm(SubReg); 3944 } else { 3945 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3946 3947 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3948 TRI.getRegSizeInBits(*VecRC), 32, false); 3949 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3950 .addReg(SrcVec->getReg()) 3951 .add(*Val) 3952 .addImm(SubReg); 3953 } 3954 MI.eraseFromParent(); 3955 return &MBB; 3956 } 3957 3958 // Control flow needs to be inserted if indexing with a VGPR. 3959 if (Val->isReg()) 3960 MRI.clearKillFlags(Val->getReg()); 3961 3962 const DebugLoc &DL = MI.getDebugLoc(); 3963 3964 Register PhiReg = MRI.createVirtualRegister(VecRC); 3965 3966 Register SGPRIdxReg; 3967 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset, 3968 UseGPRIdxMode, SGPRIdxReg); 3969 MachineBasicBlock *LoopBB = InsPt->getParent(); 3970 3971 if (UseGPRIdxMode) { 3972 const MCInstrDesc &GPRIDXDesc = 3973 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3974 3975 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3976 .addReg(PhiReg) 3977 .add(*Val) 3978 .addReg(SGPRIdxReg) 3979 .addImm(AMDGPU::sub0); 3980 } else { 3981 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3982 TRI.getRegSizeInBits(*VecRC), 32, false); 3983 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3984 .addReg(PhiReg) 3985 .add(*Val) 3986 .addImm(AMDGPU::sub0); 3987 } 3988 3989 MI.eraseFromParent(); 3990 return LoopBB; 3991 } 3992 3993 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3994 MachineInstr &MI, MachineBasicBlock *BB) const { 3995 3996 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3997 MachineFunction *MF = BB->getParent(); 3998 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3999 4000 switch (MI.getOpcode()) { 4001 case AMDGPU::S_UADDO_PSEUDO: 4002 case AMDGPU::S_USUBO_PSEUDO: { 4003 const DebugLoc &DL = MI.getDebugLoc(); 4004 MachineOperand &Dest0 = MI.getOperand(0); 4005 MachineOperand &Dest1 = MI.getOperand(1); 4006 MachineOperand &Src0 = MI.getOperand(2); 4007 MachineOperand &Src1 = MI.getOperand(3); 4008 4009 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 4010 ? AMDGPU::S_ADD_I32 4011 : AMDGPU::S_SUB_I32; 4012 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 4013 4014 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 4015 .addImm(1) 4016 .addImm(0); 4017 4018 MI.eraseFromParent(); 4019 return BB; 4020 } 4021 case AMDGPU::S_ADD_U64_PSEUDO: 4022 case AMDGPU::S_SUB_U64_PSEUDO: { 4023 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4024 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4025 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4026 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 4027 const DebugLoc &DL = MI.getDebugLoc(); 4028 4029 MachineOperand &Dest = MI.getOperand(0); 4030 MachineOperand &Src0 = MI.getOperand(1); 4031 MachineOperand &Src1 = MI.getOperand(2); 4032 4033 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4034 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4035 4036 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 4037 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 4038 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 4039 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 4040 4041 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 4042 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 4043 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 4044 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 4045 4046 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 4047 4048 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 4049 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 4050 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 4051 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 4052 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 4053 .addReg(DestSub0) 4054 .addImm(AMDGPU::sub0) 4055 .addReg(DestSub1) 4056 .addImm(AMDGPU::sub1); 4057 MI.eraseFromParent(); 4058 return BB; 4059 } 4060 case AMDGPU::V_ADD_U64_PSEUDO: 4061 case AMDGPU::V_SUB_U64_PSEUDO: { 4062 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4063 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4064 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4065 const DebugLoc &DL = MI.getDebugLoc(); 4066 4067 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 4068 4069 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4070 4071 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4072 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4073 4074 Register CarryReg = MRI.createVirtualRegister(CarryRC); 4075 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 4076 4077 MachineOperand &Dest = MI.getOperand(0); 4078 MachineOperand &Src0 = MI.getOperand(1); 4079 MachineOperand &Src1 = MI.getOperand(2); 4080 4081 const TargetRegisterClass *Src0RC = Src0.isReg() 4082 ? MRI.getRegClass(Src0.getReg()) 4083 : &AMDGPU::VReg_64RegClass; 4084 const TargetRegisterClass *Src1RC = Src1.isReg() 4085 ? MRI.getRegClass(Src1.getReg()) 4086 : &AMDGPU::VReg_64RegClass; 4087 4088 const TargetRegisterClass *Src0SubRC = 4089 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 4090 const TargetRegisterClass *Src1SubRC = 4091 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 4092 4093 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 4094 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 4095 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 4096 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 4097 4098 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 4099 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 4100 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 4101 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 4102 4103 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 4104 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 4105 .addReg(CarryReg, RegState::Define) 4106 .add(SrcReg0Sub0) 4107 .add(SrcReg1Sub0) 4108 .addImm(0); // clamp bit 4109 4110 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 4111 MachineInstr *HiHalf = 4112 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 4113 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 4114 .add(SrcReg0Sub1) 4115 .add(SrcReg1Sub1) 4116 .addReg(CarryReg, RegState::Kill) 4117 .addImm(0); // clamp bit 4118 4119 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 4120 .addReg(DestSub0) 4121 .addImm(AMDGPU::sub0) 4122 .addReg(DestSub1) 4123 .addImm(AMDGPU::sub1); 4124 TII->legalizeOperands(*LoHalf); 4125 TII->legalizeOperands(*HiHalf); 4126 MI.eraseFromParent(); 4127 return BB; 4128 } 4129 case AMDGPU::S_ADD_CO_PSEUDO: 4130 case AMDGPU::S_SUB_CO_PSEUDO: { 4131 // This pseudo has a chance to be selected 4132 // only from uniform add/subcarry node. All the VGPR operands 4133 // therefore assumed to be splat vectors. 4134 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4135 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4136 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4137 MachineBasicBlock::iterator MII = MI; 4138 const DebugLoc &DL = MI.getDebugLoc(); 4139 MachineOperand &Dest = MI.getOperand(0); 4140 MachineOperand &CarryDest = MI.getOperand(1); 4141 MachineOperand &Src0 = MI.getOperand(2); 4142 MachineOperand &Src1 = MI.getOperand(3); 4143 MachineOperand &Src2 = MI.getOperand(4); 4144 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 4145 ? AMDGPU::S_ADDC_U32 4146 : AMDGPU::S_SUBB_U32; 4147 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 4148 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4149 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 4150 .addReg(Src0.getReg()); 4151 Src0.setReg(RegOp0); 4152 } 4153 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 4154 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4155 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 4156 .addReg(Src1.getReg()); 4157 Src1.setReg(RegOp1); 4158 } 4159 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4160 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 4161 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 4162 .addReg(Src2.getReg()); 4163 Src2.setReg(RegOp2); 4164 } 4165 4166 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg()); 4167 unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC); 4168 assert(WaveSize == 64 || WaveSize == 32); 4169 4170 if (WaveSize == 64) { 4171 if (ST.hasScalarCompareEq64()) { 4172 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 4173 .addReg(Src2.getReg()) 4174 .addImm(0); 4175 } else { 4176 const TargetRegisterClass *SubRC = 4177 TRI->getSubRegClass(Src2RC, AMDGPU::sub0); 4178 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm( 4179 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC); 4180 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm( 4181 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC); 4182 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4183 4184 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32) 4185 .add(Src2Sub0) 4186 .add(Src2Sub1); 4187 4188 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 4189 .addReg(Src2_32, RegState::Kill) 4190 .addImm(0); 4191 } 4192 } else { 4193 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4194 .addReg(Src2.getReg()) 4195 .addImm(0); 4196 } 4197 4198 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4199 4200 unsigned SelOpc = 4201 (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32; 4202 4203 BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg()) 4204 .addImm(-1) 4205 .addImm(0); 4206 4207 MI.eraseFromParent(); 4208 return BB; 4209 } 4210 case AMDGPU::SI_INIT_M0: { 4211 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4212 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4213 .add(MI.getOperand(0)); 4214 MI.eraseFromParent(); 4215 return BB; 4216 } 4217 case AMDGPU::GET_GROUPSTATICSIZE: { 4218 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4219 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4220 DebugLoc DL = MI.getDebugLoc(); 4221 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4222 .add(MI.getOperand(0)) 4223 .addImm(MFI->getLDSSize()); 4224 MI.eraseFromParent(); 4225 return BB; 4226 } 4227 case AMDGPU::SI_INDIRECT_SRC_V1: 4228 case AMDGPU::SI_INDIRECT_SRC_V2: 4229 case AMDGPU::SI_INDIRECT_SRC_V4: 4230 case AMDGPU::SI_INDIRECT_SRC_V8: 4231 case AMDGPU::SI_INDIRECT_SRC_V16: 4232 case AMDGPU::SI_INDIRECT_SRC_V32: 4233 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4234 case AMDGPU::SI_INDIRECT_DST_V1: 4235 case AMDGPU::SI_INDIRECT_DST_V2: 4236 case AMDGPU::SI_INDIRECT_DST_V4: 4237 case AMDGPU::SI_INDIRECT_DST_V8: 4238 case AMDGPU::SI_INDIRECT_DST_V16: 4239 case AMDGPU::SI_INDIRECT_DST_V32: 4240 return emitIndirectDst(MI, *BB, *getSubtarget()); 4241 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4242 case AMDGPU::SI_KILL_I1_PSEUDO: 4243 return splitKillBlock(MI, BB); 4244 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4245 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4246 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4247 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4248 4249 Register Dst = MI.getOperand(0).getReg(); 4250 Register Src0 = MI.getOperand(1).getReg(); 4251 Register Src1 = MI.getOperand(2).getReg(); 4252 const DebugLoc &DL = MI.getDebugLoc(); 4253 Register SrcCond = MI.getOperand(3).getReg(); 4254 4255 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4256 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4257 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4258 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4259 4260 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4261 .addReg(SrcCond); 4262 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4263 .addImm(0) 4264 .addReg(Src0, 0, AMDGPU::sub0) 4265 .addImm(0) 4266 .addReg(Src1, 0, AMDGPU::sub0) 4267 .addReg(SrcCondCopy); 4268 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4269 .addImm(0) 4270 .addReg(Src0, 0, AMDGPU::sub1) 4271 .addImm(0) 4272 .addReg(Src1, 0, AMDGPU::sub1) 4273 .addReg(SrcCondCopy); 4274 4275 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4276 .addReg(DstLo) 4277 .addImm(AMDGPU::sub0) 4278 .addReg(DstHi) 4279 .addImm(AMDGPU::sub1); 4280 MI.eraseFromParent(); 4281 return BB; 4282 } 4283 case AMDGPU::SI_BR_UNDEF: { 4284 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4285 const DebugLoc &DL = MI.getDebugLoc(); 4286 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4287 .add(MI.getOperand(0)); 4288 Br->getOperand(1).setIsUndef(true); // read undef SCC 4289 MI.eraseFromParent(); 4290 return BB; 4291 } 4292 case AMDGPU::ADJCALLSTACKUP: 4293 case AMDGPU::ADJCALLSTACKDOWN: { 4294 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4295 MachineInstrBuilder MIB(*MF, &MI); 4296 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4297 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 4298 return BB; 4299 } 4300 case AMDGPU::SI_CALL_ISEL: { 4301 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4302 const DebugLoc &DL = MI.getDebugLoc(); 4303 4304 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4305 4306 MachineInstrBuilder MIB; 4307 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4308 4309 for (const MachineOperand &MO : MI.operands()) 4310 MIB.add(MO); 4311 4312 MIB.cloneMemRefs(MI); 4313 MI.eraseFromParent(); 4314 return BB; 4315 } 4316 case AMDGPU::V_ADD_CO_U32_e32: 4317 case AMDGPU::V_SUB_CO_U32_e32: 4318 case AMDGPU::V_SUBREV_CO_U32_e32: { 4319 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4320 const DebugLoc &DL = MI.getDebugLoc(); 4321 unsigned Opc = MI.getOpcode(); 4322 4323 bool NeedClampOperand = false; 4324 if (TII->pseudoToMCOpcode(Opc) == -1) { 4325 Opc = AMDGPU::getVOPe64(Opc); 4326 NeedClampOperand = true; 4327 } 4328 4329 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4330 if (TII->isVOP3(*I)) { 4331 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4332 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4333 I.addReg(TRI->getVCC(), RegState::Define); 4334 } 4335 I.add(MI.getOperand(1)) 4336 .add(MI.getOperand(2)); 4337 if (NeedClampOperand) 4338 I.addImm(0); // clamp bit for e64 encoding 4339 4340 TII->legalizeOperands(*I); 4341 4342 MI.eraseFromParent(); 4343 return BB; 4344 } 4345 case AMDGPU::V_ADDC_U32_e32: 4346 case AMDGPU::V_SUBB_U32_e32: 4347 case AMDGPU::V_SUBBREV_U32_e32: 4348 // These instructions have an implicit use of vcc which counts towards the 4349 // constant bus limit. 4350 TII->legalizeOperands(MI); 4351 return BB; 4352 case AMDGPU::DS_GWS_INIT: 4353 case AMDGPU::DS_GWS_SEMA_BR: 4354 case AMDGPU::DS_GWS_BARRIER: 4355 if (Subtarget->needsAlignedVGPRs()) { 4356 // Add implicit aligned super-reg to force alignment on the data operand. 4357 const DebugLoc &DL = MI.getDebugLoc(); 4358 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4359 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 4360 MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0); 4361 Register DataReg = Op->getReg(); 4362 bool IsAGPR = TRI->isAGPR(MRI, DataReg); 4363 Register Undef = MRI.createVirtualRegister( 4364 IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass); 4365 BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef); 4366 Register NewVR = 4367 MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass 4368 : &AMDGPU::VReg_64_Align2RegClass); 4369 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR) 4370 .addReg(DataReg, 0, Op->getSubReg()) 4371 .addImm(AMDGPU::sub0) 4372 .addReg(Undef) 4373 .addImm(AMDGPU::sub1); 4374 Op->setReg(NewVR); 4375 Op->setSubReg(AMDGPU::sub0); 4376 MI.addOperand(MachineOperand::CreateReg(NewVR, false, true)); 4377 } 4378 LLVM_FALLTHROUGH; 4379 case AMDGPU::DS_GWS_SEMA_V: 4380 case AMDGPU::DS_GWS_SEMA_P: 4381 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4382 // A s_waitcnt 0 is required to be the instruction immediately following. 4383 if (getSubtarget()->hasGWSAutoReplay()) { 4384 bundleInstWithWaitcnt(MI); 4385 return BB; 4386 } 4387 4388 return emitGWSMemViolTestLoop(MI, BB); 4389 case AMDGPU::S_SETREG_B32: { 4390 // Try to optimize cases that only set the denormal mode or rounding mode. 4391 // 4392 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4393 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4394 // instead. 4395 // 4396 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4397 // allow you to have a no side effect instruction in the output of a 4398 // sideeffecting pattern. 4399 unsigned ID, Offset, Width; 4400 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4401 if (ID != AMDGPU::Hwreg::ID_MODE) 4402 return BB; 4403 4404 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4405 const unsigned SetMask = WidthMask << Offset; 4406 4407 if (getSubtarget()->hasDenormModeInst()) { 4408 unsigned SetDenormOp = 0; 4409 unsigned SetRoundOp = 0; 4410 4411 // The dedicated instructions can only set the whole denorm or round mode 4412 // at once, not a subset of bits in either. 4413 if (SetMask == 4414 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4415 // If this fully sets both the round and denorm mode, emit the two 4416 // dedicated instructions for these. 4417 SetRoundOp = AMDGPU::S_ROUND_MODE; 4418 SetDenormOp = AMDGPU::S_DENORM_MODE; 4419 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4420 SetRoundOp = AMDGPU::S_ROUND_MODE; 4421 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4422 SetDenormOp = AMDGPU::S_DENORM_MODE; 4423 } 4424 4425 if (SetRoundOp || SetDenormOp) { 4426 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4427 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4428 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4429 unsigned ImmVal = Def->getOperand(1).getImm(); 4430 if (SetRoundOp) { 4431 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4432 .addImm(ImmVal & 0xf); 4433 4434 // If we also have the denorm mode, get just the denorm mode bits. 4435 ImmVal >>= 4; 4436 } 4437 4438 if (SetDenormOp) { 4439 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4440 .addImm(ImmVal & 0xf); 4441 } 4442 4443 MI.eraseFromParent(); 4444 return BB; 4445 } 4446 } 4447 } 4448 4449 // If only FP bits are touched, used the no side effects pseudo. 4450 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4451 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) 4452 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode)); 4453 4454 return BB; 4455 } 4456 default: 4457 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4458 } 4459 } 4460 4461 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4462 return isTypeLegal(VT.getScalarType()); 4463 } 4464 4465 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4466 // This currently forces unfolding various combinations of fsub into fma with 4467 // free fneg'd operands. As long as we have fast FMA (controlled by 4468 // isFMAFasterThanFMulAndFAdd), we should perform these. 4469 4470 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4471 // most of these combines appear to be cycle neutral but save on instruction 4472 // count / code size. 4473 return true; 4474 } 4475 4476 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; } 4477 4478 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4479 EVT VT) const { 4480 if (!VT.isVector()) { 4481 return MVT::i1; 4482 } 4483 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4484 } 4485 4486 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4487 // TODO: Should i16 be used always if legal? For now it would force VALU 4488 // shifts. 4489 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4490 } 4491 4492 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4493 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4494 ? Ty.changeElementSize(16) 4495 : Ty.changeElementSize(32); 4496 } 4497 4498 // Answering this is somewhat tricky and depends on the specific device which 4499 // have different rates for fma or all f64 operations. 4500 // 4501 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4502 // regardless of which device (although the number of cycles differs between 4503 // devices), so it is always profitable for f64. 4504 // 4505 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4506 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4507 // which we can always do even without fused FP ops since it returns the same 4508 // result as the separate operations and since it is always full 4509 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4510 // however does not support denormals, so we do report fma as faster if we have 4511 // a fast fma device and require denormals. 4512 // 4513 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4514 EVT VT) const { 4515 VT = VT.getScalarType(); 4516 4517 switch (VT.getSimpleVT().SimpleTy) { 4518 case MVT::f32: { 4519 // If mad is not available this depends only on if f32 fma is full rate. 4520 if (!Subtarget->hasMadMacF32Insts()) 4521 return Subtarget->hasFastFMAF32(); 4522 4523 // Otherwise f32 mad is always full rate and returns the same result as 4524 // the separate operations so should be preferred over fma. 4525 // However does not support denomals. 4526 if (hasFP32Denormals(MF)) 4527 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4528 4529 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4530 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4531 } 4532 case MVT::f64: 4533 return true; 4534 case MVT::f16: 4535 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4536 default: 4537 break; 4538 } 4539 4540 return false; 4541 } 4542 4543 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4544 LLT Ty) const { 4545 switch (Ty.getScalarSizeInBits()) { 4546 case 16: 4547 return isFMAFasterThanFMulAndFAdd(MF, MVT::f16); 4548 case 32: 4549 return isFMAFasterThanFMulAndFAdd(MF, MVT::f32); 4550 case 64: 4551 return isFMAFasterThanFMulAndFAdd(MF, MVT::f64); 4552 default: 4553 break; 4554 } 4555 4556 return false; 4557 } 4558 4559 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const { 4560 if (!Ty.isScalar()) 4561 return false; 4562 4563 if (Ty.getScalarSizeInBits() == 16) 4564 return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF()); 4565 if (Ty.getScalarSizeInBits() == 32) 4566 return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF()); 4567 4568 return false; 4569 } 4570 4571 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4572 const SDNode *N) const { 4573 // TODO: Check future ftz flag 4574 // v_mad_f32/v_mac_f32 do not support denormals. 4575 EVT VT = N->getValueType(0); 4576 if (VT == MVT::f32) 4577 return Subtarget->hasMadMacF32Insts() && 4578 !hasFP32Denormals(DAG.getMachineFunction()); 4579 if (VT == MVT::f16) { 4580 return Subtarget->hasMadF16() && 4581 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4582 } 4583 4584 return false; 4585 } 4586 4587 //===----------------------------------------------------------------------===// 4588 // Custom DAG Lowering Operations 4589 //===----------------------------------------------------------------------===// 4590 4591 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4592 // wider vector type is legal. 4593 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4594 SelectionDAG &DAG) const { 4595 unsigned Opc = Op.getOpcode(); 4596 EVT VT = Op.getValueType(); 4597 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4598 4599 SDValue Lo, Hi; 4600 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4601 4602 SDLoc SL(Op); 4603 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4604 Op->getFlags()); 4605 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4606 Op->getFlags()); 4607 4608 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4609 } 4610 4611 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4612 // wider vector type is legal. 4613 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4614 SelectionDAG &DAG) const { 4615 unsigned Opc = Op.getOpcode(); 4616 EVT VT = Op.getValueType(); 4617 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4618 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32); 4619 4620 SDValue Lo0, Hi0; 4621 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4622 SDValue Lo1, Hi1; 4623 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4624 4625 SDLoc SL(Op); 4626 4627 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4628 Op->getFlags()); 4629 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4630 Op->getFlags()); 4631 4632 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4633 } 4634 4635 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4636 SelectionDAG &DAG) const { 4637 unsigned Opc = Op.getOpcode(); 4638 EVT VT = Op.getValueType(); 4639 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4640 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32); 4641 4642 SDValue Lo0, Hi0; 4643 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4644 SDValue Lo1, Hi1; 4645 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4646 SDValue Lo2, Hi2; 4647 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4648 4649 SDLoc SL(Op); 4650 4651 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4652 Op->getFlags()); 4653 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4654 Op->getFlags()); 4655 4656 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4657 } 4658 4659 4660 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4661 switch (Op.getOpcode()) { 4662 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4663 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4664 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4665 case ISD::LOAD: { 4666 SDValue Result = LowerLOAD(Op, DAG); 4667 assert((!Result.getNode() || 4668 Result.getNode()->getNumValues() == 2) && 4669 "Load should return a value and a chain"); 4670 return Result; 4671 } 4672 4673 case ISD::FSIN: 4674 case ISD::FCOS: 4675 return LowerTrig(Op, DAG); 4676 case ISD::SELECT: return LowerSELECT(Op, DAG); 4677 case ISD::FDIV: return LowerFDIV(Op, DAG); 4678 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4679 case ISD::STORE: return LowerSTORE(Op, DAG); 4680 case ISD::GlobalAddress: { 4681 MachineFunction &MF = DAG.getMachineFunction(); 4682 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4683 return LowerGlobalAddress(MFI, Op, DAG); 4684 } 4685 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4686 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4687 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4688 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4689 case ISD::INSERT_SUBVECTOR: 4690 return lowerINSERT_SUBVECTOR(Op, DAG); 4691 case ISD::INSERT_VECTOR_ELT: 4692 return lowerINSERT_VECTOR_ELT(Op, DAG); 4693 case ISD::EXTRACT_VECTOR_ELT: 4694 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4695 case ISD::VECTOR_SHUFFLE: 4696 return lowerVECTOR_SHUFFLE(Op, DAG); 4697 case ISD::BUILD_VECTOR: 4698 return lowerBUILD_VECTOR(Op, DAG); 4699 case ISD::FP_ROUND: 4700 return lowerFP_ROUND(Op, DAG); 4701 case ISD::TRAP: 4702 return lowerTRAP(Op, DAG); 4703 case ISD::DEBUGTRAP: 4704 return lowerDEBUGTRAP(Op, DAG); 4705 case ISD::FABS: 4706 case ISD::FNEG: 4707 case ISD::FCANONICALIZE: 4708 case ISD::BSWAP: 4709 return splitUnaryVectorOp(Op, DAG); 4710 case ISD::FMINNUM: 4711 case ISD::FMAXNUM: 4712 return lowerFMINNUM_FMAXNUM(Op, DAG); 4713 case ISD::FMA: 4714 return splitTernaryVectorOp(Op, DAG); 4715 case ISD::FP_TO_SINT: 4716 case ISD::FP_TO_UINT: 4717 return LowerFP_TO_INT(Op, DAG); 4718 case ISD::SHL: 4719 case ISD::SRA: 4720 case ISD::SRL: 4721 case ISD::ADD: 4722 case ISD::SUB: 4723 case ISD::MUL: 4724 case ISD::SMIN: 4725 case ISD::SMAX: 4726 case ISD::UMIN: 4727 case ISD::UMAX: 4728 case ISD::FADD: 4729 case ISD::FMUL: 4730 case ISD::FMINNUM_IEEE: 4731 case ISD::FMAXNUM_IEEE: 4732 case ISD::UADDSAT: 4733 case ISD::USUBSAT: 4734 case ISD::SADDSAT: 4735 case ISD::SSUBSAT: 4736 return splitBinaryVectorOp(Op, DAG); 4737 case ISD::SMULO: 4738 case ISD::UMULO: 4739 return lowerXMULO(Op, DAG); 4740 case ISD::SMUL_LOHI: 4741 case ISD::UMUL_LOHI: 4742 return lowerXMUL_LOHI(Op, DAG); 4743 case ISD::DYNAMIC_STACKALLOC: 4744 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4745 } 4746 return SDValue(); 4747 } 4748 4749 // Used for D16: Casts the result of an instruction into the right vector, 4750 // packs values if loads return unpacked values. 4751 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4752 const SDLoc &DL, 4753 SelectionDAG &DAG, bool Unpacked) { 4754 if (!LoadVT.isVector()) 4755 return Result; 4756 4757 // Cast back to the original packed type or to a larger type that is a 4758 // multiple of 32 bit for D16. Widening the return type is a required for 4759 // legalization. 4760 EVT FittingLoadVT = LoadVT; 4761 if ((LoadVT.getVectorNumElements() % 2) == 1) { 4762 FittingLoadVT = 4763 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4764 LoadVT.getVectorNumElements() + 1); 4765 } 4766 4767 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4768 // Truncate to v2i16/v4i16. 4769 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger(); 4770 4771 // Workaround legalizer not scalarizing truncate after vector op 4772 // legalization but not creating intermediate vector trunc. 4773 SmallVector<SDValue, 4> Elts; 4774 DAG.ExtractVectorElements(Result, Elts); 4775 for (SDValue &Elt : Elts) 4776 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4777 4778 // Pad illegal v1i16/v3fi6 to v4i16 4779 if ((LoadVT.getVectorNumElements() % 2) == 1) 4780 Elts.push_back(DAG.getUNDEF(MVT::i16)); 4781 4782 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4783 4784 // Bitcast to original type (v2f16/v4f16). 4785 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4786 } 4787 4788 // Cast back to the original packed type. 4789 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4790 } 4791 4792 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4793 MemSDNode *M, 4794 SelectionDAG &DAG, 4795 ArrayRef<SDValue> Ops, 4796 bool IsIntrinsic) const { 4797 SDLoc DL(M); 4798 4799 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4800 EVT LoadVT = M->getValueType(0); 4801 4802 EVT EquivLoadVT = LoadVT; 4803 if (LoadVT.isVector()) { 4804 if (Unpacked) { 4805 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4806 LoadVT.getVectorNumElements()); 4807 } else if ((LoadVT.getVectorNumElements() % 2) == 1) { 4808 // Widen v3f16 to legal type 4809 EquivLoadVT = 4810 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4811 LoadVT.getVectorNumElements() + 1); 4812 } 4813 } 4814 4815 // Change from v4f16/v2f16 to EquivLoadVT. 4816 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4817 4818 SDValue Load 4819 = DAG.getMemIntrinsicNode( 4820 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4821 VTList, Ops, M->getMemoryVT(), 4822 M->getMemOperand()); 4823 4824 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4825 4826 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4827 } 4828 4829 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4830 SelectionDAG &DAG, 4831 ArrayRef<SDValue> Ops) const { 4832 SDLoc DL(M); 4833 EVT LoadVT = M->getValueType(0); 4834 EVT EltType = LoadVT.getScalarType(); 4835 EVT IntVT = LoadVT.changeTypeToInteger(); 4836 4837 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4838 4839 unsigned Opc = 4840 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4841 4842 if (IsD16) { 4843 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4844 } 4845 4846 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4847 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4848 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4849 4850 if (isTypeLegal(LoadVT)) { 4851 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4852 M->getMemOperand(), DAG); 4853 } 4854 4855 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4856 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4857 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4858 M->getMemOperand(), DAG); 4859 return DAG.getMergeValues( 4860 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4861 DL); 4862 } 4863 4864 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4865 SDNode *N, SelectionDAG &DAG) { 4866 EVT VT = N->getValueType(0); 4867 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4868 unsigned CondCode = CD->getZExtValue(); 4869 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4870 return DAG.getUNDEF(VT); 4871 4872 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4873 4874 SDValue LHS = N->getOperand(1); 4875 SDValue RHS = N->getOperand(2); 4876 4877 SDLoc DL(N); 4878 4879 EVT CmpVT = LHS.getValueType(); 4880 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4881 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4882 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4883 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4884 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4885 } 4886 4887 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4888 4889 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4890 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4891 4892 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4893 DAG.getCondCode(CCOpcode)); 4894 if (VT.bitsEq(CCVT)) 4895 return SetCC; 4896 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4897 } 4898 4899 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4900 SDNode *N, SelectionDAG &DAG) { 4901 EVT VT = N->getValueType(0); 4902 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4903 4904 unsigned CondCode = CD->getZExtValue(); 4905 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4906 return DAG.getUNDEF(VT); 4907 4908 SDValue Src0 = N->getOperand(1); 4909 SDValue Src1 = N->getOperand(2); 4910 EVT CmpVT = Src0.getValueType(); 4911 SDLoc SL(N); 4912 4913 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4914 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4915 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4916 } 4917 4918 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4919 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4920 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4921 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4922 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4923 Src1, DAG.getCondCode(CCOpcode)); 4924 if (VT.bitsEq(CCVT)) 4925 return SetCC; 4926 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4927 } 4928 4929 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4930 SelectionDAG &DAG) { 4931 EVT VT = N->getValueType(0); 4932 SDValue Src = N->getOperand(1); 4933 SDLoc SL(N); 4934 4935 if (Src.getOpcode() == ISD::SETCC) { 4936 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4937 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4938 Src.getOperand(1), Src.getOperand(2)); 4939 } 4940 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4941 // (ballot 0) -> 0 4942 if (Arg->isZero()) 4943 return DAG.getConstant(0, SL, VT); 4944 4945 // (ballot 1) -> EXEC/EXEC_LO 4946 if (Arg->isOne()) { 4947 Register Exec; 4948 if (VT.getScalarSizeInBits() == 32) 4949 Exec = AMDGPU::EXEC_LO; 4950 else if (VT.getScalarSizeInBits() == 64) 4951 Exec = AMDGPU::EXEC; 4952 else 4953 return SDValue(); 4954 4955 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4956 } 4957 } 4958 4959 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4960 // ISD::SETNE) 4961 return DAG.getNode( 4962 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4963 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4964 } 4965 4966 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4967 SmallVectorImpl<SDValue> &Results, 4968 SelectionDAG &DAG) const { 4969 switch (N->getOpcode()) { 4970 case ISD::INSERT_VECTOR_ELT: { 4971 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4972 Results.push_back(Res); 4973 return; 4974 } 4975 case ISD::EXTRACT_VECTOR_ELT: { 4976 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4977 Results.push_back(Res); 4978 return; 4979 } 4980 case ISD::INTRINSIC_WO_CHAIN: { 4981 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4982 switch (IID) { 4983 case Intrinsic::amdgcn_cvt_pkrtz: { 4984 SDValue Src0 = N->getOperand(1); 4985 SDValue Src1 = N->getOperand(2); 4986 SDLoc SL(N); 4987 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4988 Src0, Src1); 4989 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4990 return; 4991 } 4992 case Intrinsic::amdgcn_cvt_pknorm_i16: 4993 case Intrinsic::amdgcn_cvt_pknorm_u16: 4994 case Intrinsic::amdgcn_cvt_pk_i16: 4995 case Intrinsic::amdgcn_cvt_pk_u16: { 4996 SDValue Src0 = N->getOperand(1); 4997 SDValue Src1 = N->getOperand(2); 4998 SDLoc SL(N); 4999 unsigned Opcode; 5000 5001 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 5002 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 5003 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 5004 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 5005 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 5006 Opcode = AMDGPUISD::CVT_PK_I16_I32; 5007 else 5008 Opcode = AMDGPUISD::CVT_PK_U16_U32; 5009 5010 EVT VT = N->getValueType(0); 5011 if (isTypeLegal(VT)) 5012 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 5013 else { 5014 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 5015 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 5016 } 5017 return; 5018 } 5019 } 5020 break; 5021 } 5022 case ISD::INTRINSIC_W_CHAIN: { 5023 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 5024 if (Res.getOpcode() == ISD::MERGE_VALUES) { 5025 // FIXME: Hacky 5026 for (unsigned I = 0; I < Res.getNumOperands(); I++) { 5027 Results.push_back(Res.getOperand(I)); 5028 } 5029 } else { 5030 Results.push_back(Res); 5031 Results.push_back(Res.getValue(1)); 5032 } 5033 return; 5034 } 5035 5036 break; 5037 } 5038 case ISD::SELECT: { 5039 SDLoc SL(N); 5040 EVT VT = N->getValueType(0); 5041 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 5042 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 5043 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 5044 5045 EVT SelectVT = NewVT; 5046 if (NewVT.bitsLT(MVT::i32)) { 5047 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 5048 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 5049 SelectVT = MVT::i32; 5050 } 5051 5052 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 5053 N->getOperand(0), LHS, RHS); 5054 5055 if (NewVT != SelectVT) 5056 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 5057 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 5058 return; 5059 } 5060 case ISD::FNEG: { 5061 if (N->getValueType(0) != MVT::v2f16) 5062 break; 5063 5064 SDLoc SL(N); 5065 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 5066 5067 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 5068 BC, 5069 DAG.getConstant(0x80008000, SL, MVT::i32)); 5070 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 5071 return; 5072 } 5073 case ISD::FABS: { 5074 if (N->getValueType(0) != MVT::v2f16) 5075 break; 5076 5077 SDLoc SL(N); 5078 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 5079 5080 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 5081 BC, 5082 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 5083 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 5084 return; 5085 } 5086 default: 5087 break; 5088 } 5089 } 5090 5091 /// Helper function for LowerBRCOND 5092 static SDNode *findUser(SDValue Value, unsigned Opcode) { 5093 5094 SDNode *Parent = Value.getNode(); 5095 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 5096 I != E; ++I) { 5097 5098 if (I.getUse().get() != Value) 5099 continue; 5100 5101 if (I->getOpcode() == Opcode) 5102 return *I; 5103 } 5104 return nullptr; 5105 } 5106 5107 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 5108 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 5109 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 5110 case Intrinsic::amdgcn_if: 5111 return AMDGPUISD::IF; 5112 case Intrinsic::amdgcn_else: 5113 return AMDGPUISD::ELSE; 5114 case Intrinsic::amdgcn_loop: 5115 return AMDGPUISD::LOOP; 5116 case Intrinsic::amdgcn_end_cf: 5117 llvm_unreachable("should not occur"); 5118 default: 5119 return 0; 5120 } 5121 } 5122 5123 // break, if_break, else_break are all only used as inputs to loop, not 5124 // directly as branch conditions. 5125 return 0; 5126 } 5127 5128 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 5129 const Triple &TT = getTargetMachine().getTargetTriple(); 5130 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5131 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5132 AMDGPU::shouldEmitConstantsToTextSection(TT); 5133 } 5134 5135 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 5136 // FIXME: Either avoid relying on address space here or change the default 5137 // address space for functions to avoid the explicit check. 5138 return (GV->getValueType()->isFunctionTy() || 5139 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 5140 !shouldEmitFixup(GV) && 5141 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 5142 } 5143 5144 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 5145 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 5146 } 5147 5148 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 5149 if (!GV->hasExternalLinkage()) 5150 return true; 5151 5152 const auto OS = getTargetMachine().getTargetTriple().getOS(); 5153 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 5154 } 5155 5156 /// This transforms the control flow intrinsics to get the branch destination as 5157 /// last parameter, also switches branch target with BR if the need arise 5158 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 5159 SelectionDAG &DAG) const { 5160 SDLoc DL(BRCOND); 5161 5162 SDNode *Intr = BRCOND.getOperand(1).getNode(); 5163 SDValue Target = BRCOND.getOperand(2); 5164 SDNode *BR = nullptr; 5165 SDNode *SetCC = nullptr; 5166 5167 if (Intr->getOpcode() == ISD::SETCC) { 5168 // As long as we negate the condition everything is fine 5169 SetCC = Intr; 5170 Intr = SetCC->getOperand(0).getNode(); 5171 5172 } else { 5173 // Get the target from BR if we don't negate the condition 5174 BR = findUser(BRCOND, ISD::BR); 5175 assert(BR && "brcond missing unconditional branch user"); 5176 Target = BR->getOperand(1); 5177 } 5178 5179 unsigned CFNode = isCFIntrinsic(Intr); 5180 if (CFNode == 0) { 5181 // This is a uniform branch so we don't need to legalize. 5182 return BRCOND; 5183 } 5184 5185 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 5186 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 5187 5188 assert(!SetCC || 5189 (SetCC->getConstantOperandVal(1) == 1 && 5190 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 5191 ISD::SETNE)); 5192 5193 // operands of the new intrinsic call 5194 SmallVector<SDValue, 4> Ops; 5195 if (HaveChain) 5196 Ops.push_back(BRCOND.getOperand(0)); 5197 5198 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 5199 Ops.push_back(Target); 5200 5201 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 5202 5203 // build the new intrinsic call 5204 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 5205 5206 if (!HaveChain) { 5207 SDValue Ops[] = { 5208 SDValue(Result, 0), 5209 BRCOND.getOperand(0) 5210 }; 5211 5212 Result = DAG.getMergeValues(Ops, DL).getNode(); 5213 } 5214 5215 if (BR) { 5216 // Give the branch instruction our target 5217 SDValue Ops[] = { 5218 BR->getOperand(0), 5219 BRCOND.getOperand(2) 5220 }; 5221 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5222 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5223 } 5224 5225 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5226 5227 // Copy the intrinsic results to registers 5228 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5229 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5230 if (!CopyToReg) 5231 continue; 5232 5233 Chain = DAG.getCopyToReg( 5234 Chain, DL, 5235 CopyToReg->getOperand(1), 5236 SDValue(Result, i - 1), 5237 SDValue()); 5238 5239 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5240 } 5241 5242 // Remove the old intrinsic from the chain 5243 DAG.ReplaceAllUsesOfValueWith( 5244 SDValue(Intr, Intr->getNumValues() - 1), 5245 Intr->getOperand(0)); 5246 5247 return Chain; 5248 } 5249 5250 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5251 SelectionDAG &DAG) const { 5252 MVT VT = Op.getSimpleValueType(); 5253 SDLoc DL(Op); 5254 // Checking the depth 5255 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5256 return DAG.getConstant(0, DL, VT); 5257 5258 MachineFunction &MF = DAG.getMachineFunction(); 5259 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5260 // Check for kernel and shader functions 5261 if (Info->isEntryFunction()) 5262 return DAG.getConstant(0, DL, VT); 5263 5264 MachineFrameInfo &MFI = MF.getFrameInfo(); 5265 // There is a call to @llvm.returnaddress in this function 5266 MFI.setReturnAddressIsTaken(true); 5267 5268 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5269 // Get the return address reg and mark it as an implicit live-in 5270 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5271 5272 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5273 } 5274 5275 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5276 SDValue Op, 5277 const SDLoc &DL, 5278 EVT VT) const { 5279 return Op.getValueType().bitsLE(VT) ? 5280 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5281 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5282 DAG.getTargetConstant(0, DL, MVT::i32)); 5283 } 5284 5285 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5286 assert(Op.getValueType() == MVT::f16 && 5287 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5288 5289 SDValue Src = Op.getOperand(0); 5290 EVT SrcVT = Src.getValueType(); 5291 if (SrcVT != MVT::f64) 5292 return Op; 5293 5294 SDLoc DL(Op); 5295 5296 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5297 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5298 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5299 } 5300 5301 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5302 SelectionDAG &DAG) const { 5303 EVT VT = Op.getValueType(); 5304 const MachineFunction &MF = DAG.getMachineFunction(); 5305 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5306 bool IsIEEEMode = Info->getMode().IEEE; 5307 5308 // FIXME: Assert during selection that this is only selected for 5309 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5310 // mode functions, but this happens to be OK since it's only done in cases 5311 // where there is known no sNaN. 5312 if (IsIEEEMode) 5313 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5314 5315 if (VT == MVT::v4f16) 5316 return splitBinaryVectorOp(Op, DAG); 5317 return Op; 5318 } 5319 5320 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5321 EVT VT = Op.getValueType(); 5322 SDLoc SL(Op); 5323 SDValue LHS = Op.getOperand(0); 5324 SDValue RHS = Op.getOperand(1); 5325 bool isSigned = Op.getOpcode() == ISD::SMULO; 5326 5327 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5328 const APInt &C = RHSC->getAPIntValue(); 5329 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5330 if (C.isPowerOf2()) { 5331 // smulo(x, signed_min) is same as umulo(x, signed_min). 5332 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5333 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5334 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5335 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5336 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5337 SL, VT, Result, ShiftAmt), 5338 LHS, ISD::SETNE); 5339 return DAG.getMergeValues({ Result, Overflow }, SL); 5340 } 5341 } 5342 5343 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5344 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5345 SL, VT, LHS, RHS); 5346 5347 SDValue Sign = isSigned 5348 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5349 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5350 : DAG.getConstant(0, SL, VT); 5351 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5352 5353 return DAG.getMergeValues({ Result, Overflow }, SL); 5354 } 5355 5356 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const { 5357 if (Op->isDivergent()) { 5358 // Select to V_MAD_[IU]64_[IU]32. 5359 return Op; 5360 } 5361 if (Subtarget->hasSMulHi()) { 5362 // Expand to S_MUL_I32 + S_MUL_HI_[IU]32. 5363 return SDValue(); 5364 } 5365 // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to 5366 // calculate the high part, so we might as well do the whole thing with 5367 // V_MAD_[IU]64_[IU]32. 5368 return Op; 5369 } 5370 5371 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5372 if (!Subtarget->isTrapHandlerEnabled() || 5373 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) 5374 return lowerTrapEndpgm(Op, DAG); 5375 5376 if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) { 5377 switch (*HsaAbiVer) { 5378 case ELF::ELFABIVERSION_AMDGPU_HSA_V2: 5379 case ELF::ELFABIVERSION_AMDGPU_HSA_V3: 5380 return lowerTrapHsaQueuePtr(Op, DAG); 5381 case ELF::ELFABIVERSION_AMDGPU_HSA_V4: 5382 return Subtarget->supportsGetDoorbellID() ? 5383 lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG); 5384 } 5385 } 5386 5387 llvm_unreachable("Unknown trap handler"); 5388 } 5389 5390 SDValue SITargetLowering::lowerTrapEndpgm( 5391 SDValue Op, SelectionDAG &DAG) const { 5392 SDLoc SL(Op); 5393 SDValue Chain = Op.getOperand(0); 5394 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5395 } 5396 5397 SDValue SITargetLowering::lowerTrapHsaQueuePtr( 5398 SDValue Op, SelectionDAG &DAG) const { 5399 SDLoc SL(Op); 5400 SDValue Chain = Op.getOperand(0); 5401 5402 MachineFunction &MF = DAG.getMachineFunction(); 5403 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5404 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5405 5406 SDValue QueuePtr; 5407 if (UserSGPR == AMDGPU::NoRegister) { 5408 // We probably are in a function incorrectly marked with 5409 // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the trap, 5410 // so just use a null pointer. 5411 QueuePtr = DAG.getConstant(0, SL, MVT::i64); 5412 } else { 5413 QueuePtr = CreateLiveInRegister( 5414 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5415 } 5416 5417 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5418 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5419 QueuePtr, SDValue()); 5420 5421 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5422 SDValue Ops[] = { 5423 ToReg, 5424 DAG.getTargetConstant(TrapID, SL, MVT::i16), 5425 SGPR01, 5426 ToReg.getValue(1) 5427 }; 5428 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5429 } 5430 5431 SDValue SITargetLowering::lowerTrapHsa( 5432 SDValue Op, SelectionDAG &DAG) const { 5433 SDLoc SL(Op); 5434 SDValue Chain = Op.getOperand(0); 5435 5436 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5437 SDValue Ops[] = { 5438 Chain, 5439 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5440 }; 5441 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5442 } 5443 5444 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5445 SDLoc SL(Op); 5446 SDValue Chain = Op.getOperand(0); 5447 MachineFunction &MF = DAG.getMachineFunction(); 5448 5449 if (!Subtarget->isTrapHandlerEnabled() || 5450 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) { 5451 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5452 "debugtrap handler not supported", 5453 Op.getDebugLoc(), 5454 DS_Warning); 5455 LLVMContext &Ctx = MF.getFunction().getContext(); 5456 Ctx.diagnose(NoTrap); 5457 return Chain; 5458 } 5459 5460 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap); 5461 SDValue Ops[] = { 5462 Chain, 5463 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5464 }; 5465 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5466 } 5467 5468 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5469 SelectionDAG &DAG) const { 5470 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5471 if (Subtarget->hasApertureRegs()) { 5472 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5473 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5474 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5475 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5476 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5477 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5478 unsigned Encoding = 5479 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5480 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5481 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5482 5483 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5484 SDValue ApertureReg = SDValue( 5485 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5486 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5487 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5488 } 5489 5490 MachineFunction &MF = DAG.getMachineFunction(); 5491 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5492 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5493 if (UserSGPR == AMDGPU::NoRegister) { 5494 // We probably are in a function incorrectly marked with 5495 // amdgpu-no-queue-ptr. This is undefined. 5496 return DAG.getUNDEF(MVT::i32); 5497 } 5498 5499 SDValue QueuePtr = CreateLiveInRegister( 5500 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5501 5502 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5503 // private_segment_aperture_base_hi. 5504 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5505 5506 SDValue Ptr = 5507 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5508 5509 // TODO: Use custom target PseudoSourceValue. 5510 // TODO: We should use the value from the IR intrinsic call, but it might not 5511 // be available and how do we get it? 5512 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5513 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5514 commonAlignment(Align(64), StructOffset), 5515 MachineMemOperand::MODereferenceable | 5516 MachineMemOperand::MOInvariant); 5517 } 5518 5519 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5520 SelectionDAG &DAG) const { 5521 SDLoc SL(Op); 5522 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5523 5524 SDValue Src = ASC->getOperand(0); 5525 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5526 5527 const AMDGPUTargetMachine &TM = 5528 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5529 5530 // flat -> local/private 5531 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5532 unsigned DestAS = ASC->getDestAddressSpace(); 5533 5534 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5535 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5536 unsigned NullVal = TM.getNullPointerValue(DestAS); 5537 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5538 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5539 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5540 5541 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 5542 NonNull, Ptr, SegmentNullPtr); 5543 } 5544 } 5545 5546 // local/private -> flat 5547 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5548 unsigned SrcAS = ASC->getSrcAddressSpace(); 5549 5550 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5551 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5552 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5553 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5554 5555 SDValue NonNull 5556 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5557 5558 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5559 SDValue CvtPtr 5560 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5561 5562 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 5563 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 5564 FlatNullPtr); 5565 } 5566 } 5567 5568 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5569 Src.getValueType() == MVT::i64) 5570 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5571 5572 // global <-> flat are no-ops and never emitted. 5573 5574 const MachineFunction &MF = DAG.getMachineFunction(); 5575 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5576 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5577 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5578 5579 return DAG.getUNDEF(ASC->getValueType(0)); 5580 } 5581 5582 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5583 // the small vector and inserting them into the big vector. That is better than 5584 // the default expansion of doing it via a stack slot. Even though the use of 5585 // the stack slot would be optimized away afterwards, the stack slot itself 5586 // remains. 5587 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5588 SelectionDAG &DAG) const { 5589 SDValue Vec = Op.getOperand(0); 5590 SDValue Ins = Op.getOperand(1); 5591 SDValue Idx = Op.getOperand(2); 5592 EVT VecVT = Vec.getValueType(); 5593 EVT InsVT = Ins.getValueType(); 5594 EVT EltVT = VecVT.getVectorElementType(); 5595 unsigned InsNumElts = InsVT.getVectorNumElements(); 5596 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5597 SDLoc SL(Op); 5598 5599 for (unsigned I = 0; I != InsNumElts; ++I) { 5600 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5601 DAG.getConstant(I, SL, MVT::i32)); 5602 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5603 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5604 } 5605 return Vec; 5606 } 5607 5608 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5609 SelectionDAG &DAG) const { 5610 SDValue Vec = Op.getOperand(0); 5611 SDValue InsVal = Op.getOperand(1); 5612 SDValue Idx = Op.getOperand(2); 5613 EVT VecVT = Vec.getValueType(); 5614 EVT EltVT = VecVT.getVectorElementType(); 5615 unsigned VecSize = VecVT.getSizeInBits(); 5616 unsigned EltSize = EltVT.getSizeInBits(); 5617 5618 5619 assert(VecSize <= 64); 5620 5621 unsigned NumElts = VecVT.getVectorNumElements(); 5622 SDLoc SL(Op); 5623 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5624 5625 if (NumElts == 4 && EltSize == 16 && KIdx) { 5626 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5627 5628 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5629 DAG.getConstant(0, SL, MVT::i32)); 5630 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5631 DAG.getConstant(1, SL, MVT::i32)); 5632 5633 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5634 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5635 5636 unsigned Idx = KIdx->getZExtValue(); 5637 bool InsertLo = Idx < 2; 5638 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5639 InsertLo ? LoVec : HiVec, 5640 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5641 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5642 5643 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5644 5645 SDValue Concat = InsertLo ? 5646 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5647 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5648 5649 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5650 } 5651 5652 if (isa<ConstantSDNode>(Idx)) 5653 return SDValue(); 5654 5655 MVT IntVT = MVT::getIntegerVT(VecSize); 5656 5657 // Avoid stack access for dynamic indexing. 5658 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5659 5660 // Create a congruent vector with the target value in each element so that 5661 // the required element can be masked and ORed into the target vector. 5662 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5663 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5664 5665 assert(isPowerOf2_32(EltSize)); 5666 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5667 5668 // Convert vector index to bit-index. 5669 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5670 5671 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5672 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5673 DAG.getConstant(0xffff, SL, IntVT), 5674 ScaledIdx); 5675 5676 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5677 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5678 DAG.getNOT(SL, BFM, IntVT), BCVec); 5679 5680 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5681 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5682 } 5683 5684 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5685 SelectionDAG &DAG) const { 5686 SDLoc SL(Op); 5687 5688 EVT ResultVT = Op.getValueType(); 5689 SDValue Vec = Op.getOperand(0); 5690 SDValue Idx = Op.getOperand(1); 5691 EVT VecVT = Vec.getValueType(); 5692 unsigned VecSize = VecVT.getSizeInBits(); 5693 EVT EltVT = VecVT.getVectorElementType(); 5694 assert(VecSize <= 64); 5695 5696 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5697 5698 // Make sure we do any optimizations that will make it easier to fold 5699 // source modifiers before obscuring it with bit operations. 5700 5701 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5702 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5703 return Combined; 5704 5705 unsigned EltSize = EltVT.getSizeInBits(); 5706 assert(isPowerOf2_32(EltSize)); 5707 5708 MVT IntVT = MVT::getIntegerVT(VecSize); 5709 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5710 5711 // Convert vector index to bit-index (* EltSize) 5712 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5713 5714 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5715 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5716 5717 if (ResultVT == MVT::f16) { 5718 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5719 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5720 } 5721 5722 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5723 } 5724 5725 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5726 assert(Elt % 2 == 0); 5727 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5728 } 5729 5730 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5731 SelectionDAG &DAG) const { 5732 SDLoc SL(Op); 5733 EVT ResultVT = Op.getValueType(); 5734 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5735 5736 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5737 EVT EltVT = PackVT.getVectorElementType(); 5738 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5739 5740 // vector_shuffle <0,1,6,7> lhs, rhs 5741 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5742 // 5743 // vector_shuffle <6,7,2,3> lhs, rhs 5744 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5745 // 5746 // vector_shuffle <6,7,0,1> lhs, rhs 5747 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5748 5749 // Avoid scalarizing when both halves are reading from consecutive elements. 5750 SmallVector<SDValue, 4> Pieces; 5751 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5752 if (elementPairIsContiguous(SVN->getMask(), I)) { 5753 const int Idx = SVN->getMaskElt(I); 5754 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5755 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5756 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5757 PackVT, SVN->getOperand(VecIdx), 5758 DAG.getConstant(EltIdx, SL, MVT::i32)); 5759 Pieces.push_back(SubVec); 5760 } else { 5761 const int Idx0 = SVN->getMaskElt(I); 5762 const int Idx1 = SVN->getMaskElt(I + 1); 5763 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5764 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5765 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5766 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5767 5768 SDValue Vec0 = SVN->getOperand(VecIdx0); 5769 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5770 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5771 5772 SDValue Vec1 = SVN->getOperand(VecIdx1); 5773 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5774 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5775 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5776 } 5777 } 5778 5779 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5780 } 5781 5782 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5783 SelectionDAG &DAG) const { 5784 SDLoc SL(Op); 5785 EVT VT = Op.getValueType(); 5786 5787 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5788 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5789 5790 // Turn into pair of packed build_vectors. 5791 // TODO: Special case for constants that can be materialized with s_mov_b64. 5792 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5793 { Op.getOperand(0), Op.getOperand(1) }); 5794 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5795 { Op.getOperand(2), Op.getOperand(3) }); 5796 5797 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5798 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5799 5800 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5801 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5802 } 5803 5804 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5805 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5806 5807 SDValue Lo = Op.getOperand(0); 5808 SDValue Hi = Op.getOperand(1); 5809 5810 // Avoid adding defined bits with the zero_extend. 5811 if (Hi.isUndef()) { 5812 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5813 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5814 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5815 } 5816 5817 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5818 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5819 5820 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5821 DAG.getConstant(16, SL, MVT::i32)); 5822 if (Lo.isUndef()) 5823 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5824 5825 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5826 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5827 5828 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5829 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5830 } 5831 5832 bool 5833 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5834 // We can fold offsets for anything that doesn't require a GOT relocation. 5835 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5836 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5837 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5838 !shouldEmitGOTReloc(GA->getGlobal()); 5839 } 5840 5841 static SDValue 5842 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5843 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5844 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5845 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5846 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5847 // lowered to the following code sequence: 5848 // 5849 // For constant address space: 5850 // s_getpc_b64 s[0:1] 5851 // s_add_u32 s0, s0, $symbol 5852 // s_addc_u32 s1, s1, 0 5853 // 5854 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5855 // a fixup or relocation is emitted to replace $symbol with a literal 5856 // constant, which is a pc-relative offset from the encoding of the $symbol 5857 // operand to the global variable. 5858 // 5859 // For global address space: 5860 // s_getpc_b64 s[0:1] 5861 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5862 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5863 // 5864 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5865 // fixups or relocations are emitted to replace $symbol@*@lo and 5866 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5867 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5868 // operand to the global variable. 5869 // 5870 // What we want here is an offset from the value returned by s_getpc 5871 // (which is the address of the s_add_u32 instruction) to the global 5872 // variable, but since the encoding of $symbol starts 4 bytes after the start 5873 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5874 // small. This requires us to add 4 to the global variable offset in order to 5875 // compute the correct address. Similarly for the s_addc_u32 instruction, the 5876 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 5877 // instruction. 5878 SDValue PtrLo = 5879 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5880 SDValue PtrHi; 5881 if (GAFlags == SIInstrInfo::MO_NONE) { 5882 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5883 } else { 5884 PtrHi = 5885 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 5886 } 5887 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5888 } 5889 5890 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5891 SDValue Op, 5892 SelectionDAG &DAG) const { 5893 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5894 SDLoc DL(GSD); 5895 EVT PtrVT = Op.getValueType(); 5896 5897 const GlobalValue *GV = GSD->getGlobal(); 5898 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5899 shouldUseLDSConstAddress(GV)) || 5900 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5901 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 5902 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5903 GV->hasExternalLinkage()) { 5904 Type *Ty = GV->getValueType(); 5905 // HIP uses an unsized array `extern __shared__ T s[]` or similar 5906 // zero-sized type in other languages to declare the dynamic shared 5907 // memory which size is not known at the compile time. They will be 5908 // allocated by the runtime and placed directly after the static 5909 // allocated ones. They all share the same offset. 5910 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 5911 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 5912 // Adjust alignment for that dynamic shared memory array. 5913 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 5914 return SDValue( 5915 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 5916 } 5917 } 5918 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5919 } 5920 5921 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5922 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5923 SIInstrInfo::MO_ABS32_LO); 5924 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5925 } 5926 5927 if (shouldEmitFixup(GV)) 5928 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5929 else if (shouldEmitPCReloc(GV)) 5930 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5931 SIInstrInfo::MO_REL32); 5932 5933 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5934 SIInstrInfo::MO_GOTPCREL32); 5935 5936 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5937 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5938 const DataLayout &DataLayout = DAG.getDataLayout(); 5939 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 5940 MachinePointerInfo PtrInfo 5941 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5942 5943 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 5944 MachineMemOperand::MODereferenceable | 5945 MachineMemOperand::MOInvariant); 5946 } 5947 5948 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5949 const SDLoc &DL, SDValue V) const { 5950 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5951 // the destination register. 5952 // 5953 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5954 // so we will end up with redundant moves to m0. 5955 // 5956 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5957 5958 // A Null SDValue creates a glue result. 5959 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5960 V, Chain); 5961 return SDValue(M0, 0); 5962 } 5963 5964 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5965 SDValue Op, 5966 MVT VT, 5967 unsigned Offset) const { 5968 SDLoc SL(Op); 5969 SDValue Param = lowerKernargMemParameter( 5970 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 5971 // The local size values will have the hi 16-bits as zero. 5972 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5973 DAG.getValueType(VT)); 5974 } 5975 5976 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5977 EVT VT) { 5978 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5979 "non-hsa intrinsic with hsa target", 5980 DL.getDebugLoc()); 5981 DAG.getContext()->diagnose(BadIntrin); 5982 return DAG.getUNDEF(VT); 5983 } 5984 5985 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5986 EVT VT) { 5987 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5988 "intrinsic not supported on subtarget", 5989 DL.getDebugLoc()); 5990 DAG.getContext()->diagnose(BadIntrin); 5991 return DAG.getUNDEF(VT); 5992 } 5993 5994 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5995 ArrayRef<SDValue> Elts) { 5996 assert(!Elts.empty()); 5997 MVT Type; 5998 unsigned NumElts = Elts.size(); 5999 6000 if (NumElts <= 8) { 6001 Type = MVT::getVectorVT(MVT::f32, NumElts); 6002 } else { 6003 assert(Elts.size() <= 16); 6004 Type = MVT::v16f32; 6005 NumElts = 16; 6006 } 6007 6008 SmallVector<SDValue, 16> VecElts(NumElts); 6009 for (unsigned i = 0; i < Elts.size(); ++i) { 6010 SDValue Elt = Elts[i]; 6011 if (Elt.getValueType() != MVT::f32) 6012 Elt = DAG.getBitcast(MVT::f32, Elt); 6013 VecElts[i] = Elt; 6014 } 6015 for (unsigned i = Elts.size(); i < NumElts; ++i) 6016 VecElts[i] = DAG.getUNDEF(MVT::f32); 6017 6018 if (NumElts == 1) 6019 return VecElts[0]; 6020 return DAG.getBuildVector(Type, DL, VecElts); 6021 } 6022 6023 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 6024 SDValue Src, int ExtraElts) { 6025 EVT SrcVT = Src.getValueType(); 6026 6027 SmallVector<SDValue, 8> Elts; 6028 6029 if (SrcVT.isVector()) 6030 DAG.ExtractVectorElements(Src, Elts); 6031 else 6032 Elts.push_back(Src); 6033 6034 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 6035 while (ExtraElts--) 6036 Elts.push_back(Undef); 6037 6038 return DAG.getBuildVector(CastVT, DL, Elts); 6039 } 6040 6041 // Re-construct the required return value for a image load intrinsic. 6042 // This is more complicated due to the optional use TexFailCtrl which means the required 6043 // return type is an aggregate 6044 static SDValue constructRetValue(SelectionDAG &DAG, 6045 MachineSDNode *Result, 6046 ArrayRef<EVT> ResultTypes, 6047 bool IsTexFail, bool Unpacked, bool IsD16, 6048 int DMaskPop, int NumVDataDwords, 6049 const SDLoc &DL) { 6050 // Determine the required return type. This is the same regardless of IsTexFail flag 6051 EVT ReqRetVT = ResultTypes[0]; 6052 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 6053 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 6054 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 6055 6056 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 6057 DMaskPop : (DMaskPop + 1) / 2; 6058 6059 MVT DataDwordVT = NumDataDwords == 1 ? 6060 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 6061 6062 MVT MaskPopVT = MaskPopDwords == 1 ? 6063 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 6064 6065 SDValue Data(Result, 0); 6066 SDValue TexFail; 6067 6068 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) { 6069 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 6070 if (MaskPopVT.isVector()) { 6071 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 6072 SDValue(Result, 0), ZeroIdx); 6073 } else { 6074 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 6075 SDValue(Result, 0), ZeroIdx); 6076 } 6077 } 6078 6079 if (DataDwordVT.isVector()) 6080 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 6081 NumDataDwords - MaskPopDwords); 6082 6083 if (IsD16) 6084 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 6085 6086 EVT LegalReqRetVT = ReqRetVT; 6087 if (!ReqRetVT.isVector()) { 6088 if (!Data.getValueType().isInteger()) 6089 Data = DAG.getNode(ISD::BITCAST, DL, 6090 Data.getValueType().changeTypeToInteger(), Data); 6091 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 6092 } else { 6093 // We need to widen the return vector to a legal type 6094 if ((ReqRetVT.getVectorNumElements() % 2) == 1 && 6095 ReqRetVT.getVectorElementType().getSizeInBits() == 16) { 6096 LegalReqRetVT = 6097 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(), 6098 ReqRetVT.getVectorNumElements() + 1); 6099 } 6100 } 6101 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data); 6102 6103 if (IsTexFail) { 6104 TexFail = 6105 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0), 6106 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 6107 6108 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 6109 } 6110 6111 if (Result->getNumValues() == 1) 6112 return Data; 6113 6114 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 6115 } 6116 6117 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 6118 SDValue *LWE, bool &IsTexFail) { 6119 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 6120 6121 uint64_t Value = TexFailCtrlConst->getZExtValue(); 6122 if (Value) { 6123 IsTexFail = true; 6124 } 6125 6126 SDLoc DL(TexFailCtrlConst); 6127 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 6128 Value &= ~(uint64_t)0x1; 6129 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 6130 Value &= ~(uint64_t)0x2; 6131 6132 return Value == 0; 6133 } 6134 6135 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op, 6136 MVT PackVectorVT, 6137 SmallVectorImpl<SDValue> &PackedAddrs, 6138 unsigned DimIdx, unsigned EndIdx, 6139 unsigned NumGradients) { 6140 SDLoc DL(Op); 6141 for (unsigned I = DimIdx; I < EndIdx; I++) { 6142 SDValue Addr = Op.getOperand(I); 6143 6144 // Gradients are packed with undef for each coordinate. 6145 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 6146 // 1D: undef,dx/dh; undef,dx/dv 6147 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 6148 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 6149 if (((I + 1) >= EndIdx) || 6150 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 6151 I == DimIdx + NumGradients - 1))) { 6152 if (Addr.getValueType() != MVT::i16) 6153 Addr = DAG.getBitcast(MVT::i16, Addr); 6154 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 6155 } else { 6156 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 6157 I++; 6158 } 6159 Addr = DAG.getBitcast(MVT::f32, Addr); 6160 PackedAddrs.push_back(Addr); 6161 } 6162 } 6163 6164 SDValue SITargetLowering::lowerImage(SDValue Op, 6165 const AMDGPU::ImageDimIntrinsicInfo *Intr, 6166 SelectionDAG &DAG, bool WithChain) const { 6167 SDLoc DL(Op); 6168 MachineFunction &MF = DAG.getMachineFunction(); 6169 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 6170 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 6171 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 6172 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 6173 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 6174 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 6175 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 6176 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 6177 unsigned IntrOpcode = Intr->BaseOpcode; 6178 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget); 6179 6180 SmallVector<EVT, 3> ResultTypes(Op->values()); 6181 SmallVector<EVT, 3> OrigResultTypes(Op->values()); 6182 bool IsD16 = false; 6183 bool IsG16 = false; 6184 bool IsA16 = false; 6185 SDValue VData; 6186 int NumVDataDwords; 6187 bool AdjustRetType = false; 6188 6189 // Offset of intrinsic arguments 6190 const unsigned ArgOffset = WithChain ? 2 : 1; 6191 6192 unsigned DMask; 6193 unsigned DMaskLanes = 0; 6194 6195 if (BaseOpcode->Atomic) { 6196 VData = Op.getOperand(2); 6197 6198 bool Is64Bit = VData.getValueType() == MVT::i64; 6199 if (BaseOpcode->AtomicX2) { 6200 SDValue VData2 = Op.getOperand(3); 6201 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 6202 {VData, VData2}); 6203 if (Is64Bit) 6204 VData = DAG.getBitcast(MVT::v4i32, VData); 6205 6206 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 6207 DMask = Is64Bit ? 0xf : 0x3; 6208 NumVDataDwords = Is64Bit ? 4 : 2; 6209 } else { 6210 DMask = Is64Bit ? 0x3 : 0x1; 6211 NumVDataDwords = Is64Bit ? 2 : 1; 6212 } 6213 } else { 6214 auto *DMaskConst = 6215 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex)); 6216 DMask = DMaskConst->getZExtValue(); 6217 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 6218 6219 if (BaseOpcode->Store) { 6220 VData = Op.getOperand(2); 6221 6222 MVT StoreVT = VData.getSimpleValueType(); 6223 if (StoreVT.getScalarType() == MVT::f16) { 6224 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6225 return Op; // D16 is unsupported for this instruction 6226 6227 IsD16 = true; 6228 VData = handleD16VData(VData, DAG, true); 6229 } 6230 6231 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 6232 } else { 6233 // Work out the num dwords based on the dmask popcount and underlying type 6234 // and whether packing is supported. 6235 MVT LoadVT = ResultTypes[0].getSimpleVT(); 6236 if (LoadVT.getScalarType() == MVT::f16) { 6237 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6238 return Op; // D16 is unsupported for this instruction 6239 6240 IsD16 = true; 6241 } 6242 6243 // Confirm that the return type is large enough for the dmask specified 6244 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 6245 (!LoadVT.isVector() && DMaskLanes > 1)) 6246 return Op; 6247 6248 // The sq block of gfx8 and gfx9 do not estimate register use correctly 6249 // for d16 image_gather4, image_gather4_l, and image_gather4_lz 6250 // instructions. 6251 if (IsD16 && !Subtarget->hasUnpackedD16VMem() && 6252 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug())) 6253 NumVDataDwords = (DMaskLanes + 1) / 2; 6254 else 6255 NumVDataDwords = DMaskLanes; 6256 6257 AdjustRetType = true; 6258 } 6259 } 6260 6261 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd; 6262 SmallVector<SDValue, 4> VAddrs; 6263 6264 // Optimize _L to _LZ when _L is zero 6265 if (LZMappingInfo) { 6266 if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>( 6267 Op.getOperand(ArgOffset + Intr->LodIndex))) { 6268 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 6269 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 6270 VAddrEnd--; // remove 'lod' 6271 } 6272 } 6273 } 6274 6275 // Optimize _mip away, when 'lod' is zero 6276 if (MIPMappingInfo) { 6277 if (auto *ConstantLod = dyn_cast<ConstantSDNode>( 6278 Op.getOperand(ArgOffset + Intr->MipIndex))) { 6279 if (ConstantLod->isZero()) { 6280 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 6281 VAddrEnd--; // remove 'mip' 6282 } 6283 } 6284 } 6285 6286 // Push back extra arguments. 6287 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) 6288 VAddrs.push_back(Op.getOperand(ArgOffset + I)); 6289 6290 // Check for 16 bit addresses or derivatives and pack if true. 6291 MVT VAddrVT = 6292 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType(); 6293 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6294 MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6295 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6296 6297 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType(); 6298 VAddrScalarVT = VAddrVT.getScalarType(); 6299 MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6300 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6301 6302 if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) { 6303 // 16 bit gradients are supported, but are tied to the A16 control 6304 // so both gradients and addresses must be 16 bit 6305 LLVM_DEBUG( 6306 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6307 "require 16 bit args for both gradients and addresses"); 6308 return Op; 6309 } 6310 6311 if (IsA16) { 6312 if (!ST->hasA16()) { 6313 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6314 "support 16 bit addresses\n"); 6315 return Op; 6316 } 6317 } 6318 6319 // We've dealt with incorrect input so we know that if IsA16, IsG16 6320 // are set then we have to compress/pack operands (either address, 6321 // gradient or both) 6322 // In the case where a16 and gradients are tied (no G16 support) then we 6323 // have already verified that both IsA16 and IsG16 are true 6324 if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) { 6325 // Activate g16 6326 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6327 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6328 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6329 } 6330 6331 // Add gradients (packed or unpacked) 6332 if (IsG16) { 6333 // Pack the gradients 6334 // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart); 6335 packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs, 6336 ArgOffset + Intr->GradientStart, 6337 ArgOffset + Intr->CoordStart, Intr->NumGradients); 6338 } else { 6339 for (unsigned I = ArgOffset + Intr->GradientStart; 6340 I < ArgOffset + Intr->CoordStart; I++) 6341 VAddrs.push_back(Op.getOperand(I)); 6342 } 6343 6344 // Add addresses (packed or unpacked) 6345 if (IsA16) { 6346 packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs, 6347 ArgOffset + Intr->CoordStart, VAddrEnd, 6348 0 /* No gradients */); 6349 } else { 6350 // Add uncompressed address 6351 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++) 6352 VAddrs.push_back(Op.getOperand(I)); 6353 } 6354 6355 // If the register allocator cannot place the address registers contiguously 6356 // without introducing moves, then using the non-sequential address encoding 6357 // is always preferable, since it saves VALU instructions and is usually a 6358 // wash in terms of code size or even better. 6359 // 6360 // However, we currently have no way of hinting to the register allocator that 6361 // MIMG addresses should be placed contiguously when it is possible to do so, 6362 // so force non-NSA for the common 2-address case as a heuristic. 6363 // 6364 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6365 // allocation when possible. 6366 bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) && 6367 VAddrs.size() >= 3 && 6368 VAddrs.size() <= (unsigned)ST->getNSAMaxSize(); 6369 SDValue VAddr; 6370 if (!UseNSA) 6371 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6372 6373 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6374 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6375 SDValue Unorm; 6376 if (!BaseOpcode->Sampler) { 6377 Unorm = True; 6378 } else { 6379 auto UnormConst = 6380 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex)); 6381 6382 Unorm = UnormConst->getZExtValue() ? True : False; 6383 } 6384 6385 SDValue TFE; 6386 SDValue LWE; 6387 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex); 6388 bool IsTexFail = false; 6389 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6390 return Op; 6391 6392 if (IsTexFail) { 6393 if (!DMaskLanes) { 6394 // Expecting to get an error flag since TFC is on - and dmask is 0 6395 // Force dmask to be at least 1 otherwise the instruction will fail 6396 DMask = 0x1; 6397 DMaskLanes = 1; 6398 NumVDataDwords = 1; 6399 } 6400 NumVDataDwords += 1; 6401 AdjustRetType = true; 6402 } 6403 6404 // Has something earlier tagged that the return type needs adjusting 6405 // This happens if the instruction is a load or has set TexFailCtrl flags 6406 if (AdjustRetType) { 6407 // NumVDataDwords reflects the true number of dwords required in the return type 6408 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6409 // This is a no-op load. This can be eliminated 6410 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6411 if (isa<MemSDNode>(Op)) 6412 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6413 return Undef; 6414 } 6415 6416 EVT NewVT = NumVDataDwords > 1 ? 6417 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6418 : MVT::i32; 6419 6420 ResultTypes[0] = NewVT; 6421 if (ResultTypes.size() == 3) { 6422 // Original result was aggregate type used for TexFailCtrl results 6423 // The actual instruction returns as a vector type which has now been 6424 // created. Remove the aggregate result. 6425 ResultTypes.erase(&ResultTypes[1]); 6426 } 6427 } 6428 6429 unsigned CPol = cast<ConstantSDNode>( 6430 Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue(); 6431 if (BaseOpcode->Atomic) 6432 CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization 6433 if (CPol & ~AMDGPU::CPol::ALL) 6434 return Op; 6435 6436 SmallVector<SDValue, 26> Ops; 6437 if (BaseOpcode->Store || BaseOpcode->Atomic) 6438 Ops.push_back(VData); // vdata 6439 if (UseNSA) 6440 append_range(Ops, VAddrs); 6441 else 6442 Ops.push_back(VAddr); 6443 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex)); 6444 if (BaseOpcode->Sampler) 6445 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex)); 6446 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6447 if (IsGFX10Plus) 6448 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6449 Ops.push_back(Unorm); 6450 Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32)); 6451 Ops.push_back(IsA16 && // r128, a16 for gfx9 6452 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6453 if (IsGFX10Plus) 6454 Ops.push_back(IsA16 ? True : False); 6455 if (!Subtarget->hasGFX90AInsts()) { 6456 Ops.push_back(TFE); //tfe 6457 } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) { 6458 report_fatal_error("TFE is not supported on this GPU"); 6459 } 6460 Ops.push_back(LWE); // lwe 6461 if (!IsGFX10Plus) 6462 Ops.push_back(DimInfo->DA ? True : False); 6463 if (BaseOpcode->HasD16) 6464 Ops.push_back(IsD16 ? True : False); 6465 if (isa<MemSDNode>(Op)) 6466 Ops.push_back(Op.getOperand(0)); // chain 6467 6468 int NumVAddrDwords = 6469 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6470 int Opcode = -1; 6471 6472 if (IsGFX10Plus) { 6473 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6474 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6475 : AMDGPU::MIMGEncGfx10Default, 6476 NumVDataDwords, NumVAddrDwords); 6477 } else { 6478 if (Subtarget->hasGFX90AInsts()) { 6479 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a, 6480 NumVDataDwords, NumVAddrDwords); 6481 if (Opcode == -1) 6482 report_fatal_error( 6483 "requested image instruction is not supported on this GPU"); 6484 } 6485 if (Opcode == -1 && 6486 Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6487 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6488 NumVDataDwords, NumVAddrDwords); 6489 if (Opcode == -1) 6490 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6491 NumVDataDwords, NumVAddrDwords); 6492 } 6493 assert(Opcode != -1); 6494 6495 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6496 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6497 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6498 DAG.setNodeMemRefs(NewNode, {MemRef}); 6499 } 6500 6501 if (BaseOpcode->AtomicX2) { 6502 SmallVector<SDValue, 1> Elt; 6503 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6504 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6505 } 6506 if (BaseOpcode->Store) 6507 return SDValue(NewNode, 0); 6508 return constructRetValue(DAG, NewNode, 6509 OrigResultTypes, IsTexFail, 6510 Subtarget->hasUnpackedD16VMem(), IsD16, 6511 DMaskLanes, NumVDataDwords, DL); 6512 } 6513 6514 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6515 SDValue Offset, SDValue CachePolicy, 6516 SelectionDAG &DAG) const { 6517 MachineFunction &MF = DAG.getMachineFunction(); 6518 6519 const DataLayout &DataLayout = DAG.getDataLayout(); 6520 Align Alignment = 6521 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6522 6523 MachineMemOperand *MMO = MF.getMachineMemOperand( 6524 MachinePointerInfo(), 6525 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6526 MachineMemOperand::MOInvariant, 6527 VT.getStoreSize(), Alignment); 6528 6529 if (!Offset->isDivergent()) { 6530 SDValue Ops[] = { 6531 Rsrc, 6532 Offset, // Offset 6533 CachePolicy 6534 }; 6535 6536 // Widen vec3 load to vec4. 6537 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6538 EVT WidenedVT = 6539 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6540 auto WidenedOp = DAG.getMemIntrinsicNode( 6541 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6542 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6543 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6544 DAG.getVectorIdxConstant(0, DL)); 6545 return Subvector; 6546 } 6547 6548 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6549 DAG.getVTList(VT), Ops, VT, MMO); 6550 } 6551 6552 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6553 // assume that the buffer is unswizzled. 6554 SmallVector<SDValue, 4> Loads; 6555 unsigned NumLoads = 1; 6556 MVT LoadVT = VT.getSimpleVT(); 6557 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6558 assert((LoadVT.getScalarType() == MVT::i32 || 6559 LoadVT.getScalarType() == MVT::f32)); 6560 6561 if (NumElts == 8 || NumElts == 16) { 6562 NumLoads = NumElts / 4; 6563 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6564 } 6565 6566 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6567 SDValue Ops[] = { 6568 DAG.getEntryNode(), // Chain 6569 Rsrc, // rsrc 6570 DAG.getConstant(0, DL, MVT::i32), // vindex 6571 {}, // voffset 6572 {}, // soffset 6573 {}, // offset 6574 CachePolicy, // cachepolicy 6575 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6576 }; 6577 6578 // Use the alignment to ensure that the required offsets will fit into the 6579 // immediate offsets. 6580 setBufferOffsets(Offset, DAG, &Ops[3], 6581 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6582 6583 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6584 for (unsigned i = 0; i < NumLoads; ++i) { 6585 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6586 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6587 LoadVT, MMO, DAG)); 6588 } 6589 6590 if (NumElts == 8 || NumElts == 16) 6591 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6592 6593 return Loads[0]; 6594 } 6595 6596 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6597 SelectionDAG &DAG) const { 6598 MachineFunction &MF = DAG.getMachineFunction(); 6599 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6600 6601 EVT VT = Op.getValueType(); 6602 SDLoc DL(Op); 6603 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6604 6605 // TODO: Should this propagate fast-math-flags? 6606 6607 switch (IntrinsicID) { 6608 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6609 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6610 return emitNonHSAIntrinsicError(DAG, DL, VT); 6611 return getPreloadedValue(DAG, *MFI, VT, 6612 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6613 } 6614 case Intrinsic::amdgcn_dispatch_ptr: 6615 case Intrinsic::amdgcn_queue_ptr: { 6616 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6617 DiagnosticInfoUnsupported BadIntrin( 6618 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6619 DL.getDebugLoc()); 6620 DAG.getContext()->diagnose(BadIntrin); 6621 return DAG.getUNDEF(VT); 6622 } 6623 6624 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6625 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6626 return getPreloadedValue(DAG, *MFI, VT, RegID); 6627 } 6628 case Intrinsic::amdgcn_implicitarg_ptr: { 6629 if (MFI->isEntryFunction()) 6630 return getImplicitArgPtr(DAG, DL); 6631 return getPreloadedValue(DAG, *MFI, VT, 6632 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6633 } 6634 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6635 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6636 // This only makes sense to call in a kernel, so just lower to null. 6637 return DAG.getConstant(0, DL, VT); 6638 } 6639 6640 return getPreloadedValue(DAG, *MFI, VT, 6641 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6642 } 6643 case Intrinsic::amdgcn_dispatch_id: { 6644 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6645 } 6646 case Intrinsic::amdgcn_rcp: 6647 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6648 case Intrinsic::amdgcn_rsq: 6649 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6650 case Intrinsic::amdgcn_rsq_legacy: 6651 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6652 return emitRemovedIntrinsicError(DAG, DL, VT); 6653 return SDValue(); 6654 case Intrinsic::amdgcn_rcp_legacy: 6655 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6656 return emitRemovedIntrinsicError(DAG, DL, VT); 6657 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6658 case Intrinsic::amdgcn_rsq_clamp: { 6659 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6660 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6661 6662 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6663 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6664 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6665 6666 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6667 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6668 DAG.getConstantFP(Max, DL, VT)); 6669 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6670 DAG.getConstantFP(Min, DL, VT)); 6671 } 6672 case Intrinsic::r600_read_ngroups_x: 6673 if (Subtarget->isAmdHsaOS()) 6674 return emitNonHSAIntrinsicError(DAG, DL, VT); 6675 6676 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6677 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6678 false); 6679 case Intrinsic::r600_read_ngroups_y: 6680 if (Subtarget->isAmdHsaOS()) 6681 return emitNonHSAIntrinsicError(DAG, DL, VT); 6682 6683 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6684 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6685 false); 6686 case Intrinsic::r600_read_ngroups_z: 6687 if (Subtarget->isAmdHsaOS()) 6688 return emitNonHSAIntrinsicError(DAG, DL, VT); 6689 6690 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6691 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6692 false); 6693 case Intrinsic::r600_read_global_size_x: 6694 if (Subtarget->isAmdHsaOS()) 6695 return emitNonHSAIntrinsicError(DAG, DL, VT); 6696 6697 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6698 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6699 Align(4), false); 6700 case Intrinsic::r600_read_global_size_y: 6701 if (Subtarget->isAmdHsaOS()) 6702 return emitNonHSAIntrinsicError(DAG, DL, VT); 6703 6704 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6705 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6706 Align(4), false); 6707 case Intrinsic::r600_read_global_size_z: 6708 if (Subtarget->isAmdHsaOS()) 6709 return emitNonHSAIntrinsicError(DAG, DL, VT); 6710 6711 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6712 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6713 Align(4), false); 6714 case Intrinsic::r600_read_local_size_x: 6715 if (Subtarget->isAmdHsaOS()) 6716 return emitNonHSAIntrinsicError(DAG, DL, VT); 6717 6718 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6719 SI::KernelInputOffsets::LOCAL_SIZE_X); 6720 case Intrinsic::r600_read_local_size_y: 6721 if (Subtarget->isAmdHsaOS()) 6722 return emitNonHSAIntrinsicError(DAG, DL, VT); 6723 6724 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6725 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6726 case Intrinsic::r600_read_local_size_z: 6727 if (Subtarget->isAmdHsaOS()) 6728 return emitNonHSAIntrinsicError(DAG, DL, VT); 6729 6730 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6731 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6732 case Intrinsic::amdgcn_workgroup_id_x: 6733 return getPreloadedValue(DAG, *MFI, VT, 6734 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6735 case Intrinsic::amdgcn_workgroup_id_y: 6736 return getPreloadedValue(DAG, *MFI, VT, 6737 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6738 case Intrinsic::amdgcn_workgroup_id_z: 6739 return getPreloadedValue(DAG, *MFI, VT, 6740 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6741 case Intrinsic::amdgcn_workitem_id_x: 6742 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6743 SDLoc(DAG.getEntryNode()), 6744 MFI->getArgInfo().WorkItemIDX); 6745 case Intrinsic::amdgcn_workitem_id_y: 6746 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6747 SDLoc(DAG.getEntryNode()), 6748 MFI->getArgInfo().WorkItemIDY); 6749 case Intrinsic::amdgcn_workitem_id_z: 6750 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6751 SDLoc(DAG.getEntryNode()), 6752 MFI->getArgInfo().WorkItemIDZ); 6753 case Intrinsic::amdgcn_wavefrontsize: 6754 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6755 SDLoc(Op), MVT::i32); 6756 case Intrinsic::amdgcn_s_buffer_load: { 6757 unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 6758 if (CPol & ~AMDGPU::CPol::ALL) 6759 return Op; 6760 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6761 DAG); 6762 } 6763 case Intrinsic::amdgcn_fdiv_fast: 6764 return lowerFDIV_FAST(Op, DAG); 6765 case Intrinsic::amdgcn_sin: 6766 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6767 6768 case Intrinsic::amdgcn_cos: 6769 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6770 6771 case Intrinsic::amdgcn_mul_u24: 6772 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6773 case Intrinsic::amdgcn_mul_i24: 6774 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6775 6776 case Intrinsic::amdgcn_log_clamp: { 6777 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6778 return SDValue(); 6779 6780 return emitRemovedIntrinsicError(DAG, DL, VT); 6781 } 6782 case Intrinsic::amdgcn_ldexp: 6783 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6784 Op.getOperand(1), Op.getOperand(2)); 6785 6786 case Intrinsic::amdgcn_fract: 6787 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6788 6789 case Intrinsic::amdgcn_class: 6790 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6791 Op.getOperand(1), Op.getOperand(2)); 6792 case Intrinsic::amdgcn_div_fmas: 6793 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6794 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6795 Op.getOperand(4)); 6796 6797 case Intrinsic::amdgcn_div_fixup: 6798 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6799 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6800 6801 case Intrinsic::amdgcn_div_scale: { 6802 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6803 6804 // Translate to the operands expected by the machine instruction. The 6805 // first parameter must be the same as the first instruction. 6806 SDValue Numerator = Op.getOperand(1); 6807 SDValue Denominator = Op.getOperand(2); 6808 6809 // Note this order is opposite of the machine instruction's operations, 6810 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6811 // intrinsic has the numerator as the first operand to match a normal 6812 // division operation. 6813 6814 SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator; 6815 6816 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6817 Denominator, Numerator); 6818 } 6819 case Intrinsic::amdgcn_icmp: { 6820 // There is a Pat that handles this variant, so return it as-is. 6821 if (Op.getOperand(1).getValueType() == MVT::i1 && 6822 Op.getConstantOperandVal(2) == 0 && 6823 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6824 return Op; 6825 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6826 } 6827 case Intrinsic::amdgcn_fcmp: { 6828 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6829 } 6830 case Intrinsic::amdgcn_ballot: 6831 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6832 case Intrinsic::amdgcn_fmed3: 6833 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6834 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6835 case Intrinsic::amdgcn_fdot2: 6836 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6837 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6838 Op.getOperand(4)); 6839 case Intrinsic::amdgcn_fmul_legacy: 6840 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6841 Op.getOperand(1), Op.getOperand(2)); 6842 case Intrinsic::amdgcn_sffbh: 6843 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6844 case Intrinsic::amdgcn_sbfe: 6845 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6846 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6847 case Intrinsic::amdgcn_ubfe: 6848 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6849 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6850 case Intrinsic::amdgcn_cvt_pkrtz: 6851 case Intrinsic::amdgcn_cvt_pknorm_i16: 6852 case Intrinsic::amdgcn_cvt_pknorm_u16: 6853 case Intrinsic::amdgcn_cvt_pk_i16: 6854 case Intrinsic::amdgcn_cvt_pk_u16: { 6855 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6856 EVT VT = Op.getValueType(); 6857 unsigned Opcode; 6858 6859 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6860 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6861 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6862 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6863 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6864 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6865 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6866 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6867 else 6868 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6869 6870 if (isTypeLegal(VT)) 6871 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6872 6873 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6874 Op.getOperand(1), Op.getOperand(2)); 6875 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6876 } 6877 case Intrinsic::amdgcn_fmad_ftz: 6878 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6879 Op.getOperand(2), Op.getOperand(3)); 6880 6881 case Intrinsic::amdgcn_if_break: 6882 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6883 Op->getOperand(1), Op->getOperand(2)), 0); 6884 6885 case Intrinsic::amdgcn_groupstaticsize: { 6886 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6887 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6888 return Op; 6889 6890 const Module *M = MF.getFunction().getParent(); 6891 const GlobalValue *GV = 6892 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6893 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6894 SIInstrInfo::MO_ABS32_LO); 6895 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6896 } 6897 case Intrinsic::amdgcn_is_shared: 6898 case Intrinsic::amdgcn_is_private: { 6899 SDLoc SL(Op); 6900 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6901 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6902 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6903 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6904 Op.getOperand(1)); 6905 6906 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6907 DAG.getConstant(1, SL, MVT::i32)); 6908 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6909 } 6910 case Intrinsic::amdgcn_alignbit: 6911 return DAG.getNode(ISD::FSHR, DL, VT, 6912 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6913 case Intrinsic::amdgcn_perm: 6914 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1), 6915 Op.getOperand(2), Op.getOperand(3)); 6916 case Intrinsic::amdgcn_reloc_constant: { 6917 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6918 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6919 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6920 auto RelocSymbol = cast<GlobalVariable>( 6921 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6922 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6923 SIInstrInfo::MO_ABS32_LO); 6924 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6925 } 6926 default: 6927 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6928 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6929 return lowerImage(Op, ImageDimIntr, DAG, false); 6930 6931 return Op; 6932 } 6933 } 6934 6935 /// Update \p MMO based on the offset inputs to an intrinsic. 6936 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset, 6937 SDValue SOffset, SDValue Offset, 6938 SDValue VIndex = SDValue()) { 6939 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6940 !isa<ConstantSDNode>(Offset)) { 6941 // The combined offset is not known to be constant, so we cannot represent 6942 // it in the MMO. Give up. 6943 MMO->setValue((Value *)nullptr); 6944 return; 6945 } 6946 6947 if (VIndex && (!isa<ConstantSDNode>(VIndex) || 6948 !cast<ConstantSDNode>(VIndex)->isZero())) { 6949 // The strided index component of the address is not known to be zero, so we 6950 // cannot represent it in the MMO. Give up. 6951 MMO->setValue((Value *)nullptr); 6952 return; 6953 } 6954 6955 MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() + 6956 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6957 cast<ConstantSDNode>(Offset)->getSExtValue()); 6958 } 6959 6960 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 6961 SelectionDAG &DAG, 6962 unsigned NewOpcode) const { 6963 SDLoc DL(Op); 6964 6965 SDValue VData = Op.getOperand(2); 6966 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6967 SDValue Ops[] = { 6968 Op.getOperand(0), // Chain 6969 VData, // vdata 6970 Op.getOperand(3), // rsrc 6971 DAG.getConstant(0, DL, MVT::i32), // vindex 6972 Offsets.first, // voffset 6973 Op.getOperand(5), // soffset 6974 Offsets.second, // offset 6975 Op.getOperand(6), // cachepolicy 6976 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6977 }; 6978 6979 auto *M = cast<MemSDNode>(Op); 6980 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 6981 6982 EVT MemVT = VData.getValueType(); 6983 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6984 M->getMemOperand()); 6985 } 6986 6987 // Return a value to use for the idxen operand by examining the vindex operand. 6988 static unsigned getIdxEn(SDValue VIndex) { 6989 if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex)) 6990 // No need to set idxen if vindex is known to be zero. 6991 return VIndexC->getZExtValue() != 0; 6992 return 1; 6993 } 6994 6995 SDValue 6996 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 6997 unsigned NewOpcode) const { 6998 SDLoc DL(Op); 6999 7000 SDValue VData = Op.getOperand(2); 7001 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7002 SDValue Ops[] = { 7003 Op.getOperand(0), // Chain 7004 VData, // vdata 7005 Op.getOperand(3), // rsrc 7006 Op.getOperand(4), // vindex 7007 Offsets.first, // voffset 7008 Op.getOperand(6), // soffset 7009 Offsets.second, // offset 7010 Op.getOperand(7), // cachepolicy 7011 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7012 }; 7013 7014 auto *M = cast<MemSDNode>(Op); 7015 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7016 7017 EVT MemVT = VData.getValueType(); 7018 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 7019 M->getMemOperand()); 7020 } 7021 7022 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 7023 SelectionDAG &DAG) const { 7024 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7025 SDLoc DL(Op); 7026 7027 switch (IntrID) { 7028 case Intrinsic::amdgcn_ds_ordered_add: 7029 case Intrinsic::amdgcn_ds_ordered_swap: { 7030 MemSDNode *M = cast<MemSDNode>(Op); 7031 SDValue Chain = M->getOperand(0); 7032 SDValue M0 = M->getOperand(2); 7033 SDValue Value = M->getOperand(3); 7034 unsigned IndexOperand = M->getConstantOperandVal(7); 7035 unsigned WaveRelease = M->getConstantOperandVal(8); 7036 unsigned WaveDone = M->getConstantOperandVal(9); 7037 7038 unsigned OrderedCountIndex = IndexOperand & 0x3f; 7039 IndexOperand &= ~0x3f; 7040 unsigned CountDw = 0; 7041 7042 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 7043 CountDw = (IndexOperand >> 24) & 0xf; 7044 IndexOperand &= ~(0xf << 24); 7045 7046 if (CountDw < 1 || CountDw > 4) { 7047 report_fatal_error( 7048 "ds_ordered_count: dword count must be between 1 and 4"); 7049 } 7050 } 7051 7052 if (IndexOperand) 7053 report_fatal_error("ds_ordered_count: bad index operand"); 7054 7055 if (WaveDone && !WaveRelease) 7056 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 7057 7058 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 7059 unsigned ShaderType = 7060 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 7061 unsigned Offset0 = OrderedCountIndex << 2; 7062 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 7063 (Instruction << 4); 7064 7065 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 7066 Offset1 |= (CountDw - 1) << 6; 7067 7068 unsigned Offset = Offset0 | (Offset1 << 8); 7069 7070 SDValue Ops[] = { 7071 Chain, 7072 Value, 7073 DAG.getTargetConstant(Offset, DL, MVT::i16), 7074 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 7075 }; 7076 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 7077 M->getVTList(), Ops, M->getMemoryVT(), 7078 M->getMemOperand()); 7079 } 7080 case Intrinsic::amdgcn_ds_fadd: { 7081 MemSDNode *M = cast<MemSDNode>(Op); 7082 unsigned Opc; 7083 switch (IntrID) { 7084 case Intrinsic::amdgcn_ds_fadd: 7085 Opc = ISD::ATOMIC_LOAD_FADD; 7086 break; 7087 } 7088 7089 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 7090 M->getOperand(0), M->getOperand(2), M->getOperand(3), 7091 M->getMemOperand()); 7092 } 7093 case Intrinsic::amdgcn_atomic_inc: 7094 case Intrinsic::amdgcn_atomic_dec: 7095 case Intrinsic::amdgcn_ds_fmin: 7096 case Intrinsic::amdgcn_ds_fmax: { 7097 MemSDNode *M = cast<MemSDNode>(Op); 7098 unsigned Opc; 7099 switch (IntrID) { 7100 case Intrinsic::amdgcn_atomic_inc: 7101 Opc = AMDGPUISD::ATOMIC_INC; 7102 break; 7103 case Intrinsic::amdgcn_atomic_dec: 7104 Opc = AMDGPUISD::ATOMIC_DEC; 7105 break; 7106 case Intrinsic::amdgcn_ds_fmin: 7107 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 7108 break; 7109 case Intrinsic::amdgcn_ds_fmax: 7110 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 7111 break; 7112 default: 7113 llvm_unreachable("Unknown intrinsic!"); 7114 } 7115 SDValue Ops[] = { 7116 M->getOperand(0), // Chain 7117 M->getOperand(2), // Ptr 7118 M->getOperand(3) // Value 7119 }; 7120 7121 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 7122 M->getMemoryVT(), M->getMemOperand()); 7123 } 7124 case Intrinsic::amdgcn_buffer_load: 7125 case Intrinsic::amdgcn_buffer_load_format: { 7126 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 7127 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7128 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7129 SDValue Ops[] = { 7130 Op.getOperand(0), // Chain 7131 Op.getOperand(2), // rsrc 7132 Op.getOperand(3), // vindex 7133 SDValue(), // voffset -- will be set by setBufferOffsets 7134 SDValue(), // soffset -- will be set by setBufferOffsets 7135 SDValue(), // offset -- will be set by setBufferOffsets 7136 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7137 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7138 }; 7139 setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 7140 7141 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 7142 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 7143 7144 EVT VT = Op.getValueType(); 7145 EVT IntVT = VT.changeTypeToInteger(); 7146 auto *M = cast<MemSDNode>(Op); 7147 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7148 EVT LoadVT = Op.getValueType(); 7149 7150 if (LoadVT.getScalarType() == MVT::f16) 7151 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 7152 M, DAG, Ops); 7153 7154 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 7155 if (LoadVT.getScalarType() == MVT::i8 || 7156 LoadVT.getScalarType() == MVT::i16) 7157 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 7158 7159 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 7160 M->getMemOperand(), DAG); 7161 } 7162 case Intrinsic::amdgcn_raw_buffer_load: 7163 case Intrinsic::amdgcn_raw_buffer_load_format: { 7164 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 7165 7166 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7167 SDValue Ops[] = { 7168 Op.getOperand(0), // Chain 7169 Op.getOperand(2), // rsrc 7170 DAG.getConstant(0, DL, MVT::i32), // vindex 7171 Offsets.first, // voffset 7172 Op.getOperand(4), // soffset 7173 Offsets.second, // offset 7174 Op.getOperand(5), // cachepolicy, swizzled buffer 7175 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7176 }; 7177 7178 auto *M = cast<MemSDNode>(Op); 7179 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]); 7180 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 7181 } 7182 case Intrinsic::amdgcn_struct_buffer_load: 7183 case Intrinsic::amdgcn_struct_buffer_load_format: { 7184 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 7185 7186 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7187 SDValue Ops[] = { 7188 Op.getOperand(0), // Chain 7189 Op.getOperand(2), // rsrc 7190 Op.getOperand(3), // vindex 7191 Offsets.first, // voffset 7192 Op.getOperand(5), // soffset 7193 Offsets.second, // offset 7194 Op.getOperand(6), // cachepolicy, swizzled buffer 7195 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7196 }; 7197 7198 auto *M = cast<MemSDNode>(Op); 7199 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7200 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 7201 } 7202 case Intrinsic::amdgcn_tbuffer_load: { 7203 MemSDNode *M = cast<MemSDNode>(Op); 7204 EVT LoadVT = Op.getValueType(); 7205 7206 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7207 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7208 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7209 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7210 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7211 SDValue Ops[] = { 7212 Op.getOperand(0), // Chain 7213 Op.getOperand(2), // rsrc 7214 Op.getOperand(3), // vindex 7215 Op.getOperand(4), // voffset 7216 Op.getOperand(5), // soffset 7217 Op.getOperand(6), // offset 7218 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7219 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7220 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 7221 }; 7222 7223 if (LoadVT.getScalarType() == MVT::f16) 7224 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7225 M, DAG, Ops); 7226 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7227 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7228 DAG); 7229 } 7230 case Intrinsic::amdgcn_raw_tbuffer_load: { 7231 MemSDNode *M = cast<MemSDNode>(Op); 7232 EVT LoadVT = Op.getValueType(); 7233 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7234 7235 SDValue Ops[] = { 7236 Op.getOperand(0), // Chain 7237 Op.getOperand(2), // rsrc 7238 DAG.getConstant(0, DL, MVT::i32), // vindex 7239 Offsets.first, // voffset 7240 Op.getOperand(4), // soffset 7241 Offsets.second, // offset 7242 Op.getOperand(5), // format 7243 Op.getOperand(6), // cachepolicy, swizzled buffer 7244 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7245 }; 7246 7247 if (LoadVT.getScalarType() == MVT::f16) 7248 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7249 M, DAG, Ops); 7250 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7251 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7252 DAG); 7253 } 7254 case Intrinsic::amdgcn_struct_tbuffer_load: { 7255 MemSDNode *M = cast<MemSDNode>(Op); 7256 EVT LoadVT = Op.getValueType(); 7257 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7258 7259 SDValue Ops[] = { 7260 Op.getOperand(0), // Chain 7261 Op.getOperand(2), // rsrc 7262 Op.getOperand(3), // vindex 7263 Offsets.first, // voffset 7264 Op.getOperand(5), // soffset 7265 Offsets.second, // offset 7266 Op.getOperand(6), // format 7267 Op.getOperand(7), // cachepolicy, swizzled buffer 7268 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7269 }; 7270 7271 if (LoadVT.getScalarType() == MVT::f16) 7272 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7273 M, DAG, Ops); 7274 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7275 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7276 DAG); 7277 } 7278 case Intrinsic::amdgcn_buffer_atomic_swap: 7279 case Intrinsic::amdgcn_buffer_atomic_add: 7280 case Intrinsic::amdgcn_buffer_atomic_sub: 7281 case Intrinsic::amdgcn_buffer_atomic_csub: 7282 case Intrinsic::amdgcn_buffer_atomic_smin: 7283 case Intrinsic::amdgcn_buffer_atomic_umin: 7284 case Intrinsic::amdgcn_buffer_atomic_smax: 7285 case Intrinsic::amdgcn_buffer_atomic_umax: 7286 case Intrinsic::amdgcn_buffer_atomic_and: 7287 case Intrinsic::amdgcn_buffer_atomic_or: 7288 case Intrinsic::amdgcn_buffer_atomic_xor: 7289 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7290 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7291 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7292 SDValue Ops[] = { 7293 Op.getOperand(0), // Chain 7294 Op.getOperand(2), // vdata 7295 Op.getOperand(3), // rsrc 7296 Op.getOperand(4), // vindex 7297 SDValue(), // voffset -- will be set by setBufferOffsets 7298 SDValue(), // soffset -- will be set by setBufferOffsets 7299 SDValue(), // offset -- will be set by setBufferOffsets 7300 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7301 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7302 }; 7303 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7304 7305 EVT VT = Op.getValueType(); 7306 7307 auto *M = cast<MemSDNode>(Op); 7308 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7309 unsigned Opcode = 0; 7310 7311 switch (IntrID) { 7312 case Intrinsic::amdgcn_buffer_atomic_swap: 7313 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7314 break; 7315 case Intrinsic::amdgcn_buffer_atomic_add: 7316 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7317 break; 7318 case Intrinsic::amdgcn_buffer_atomic_sub: 7319 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7320 break; 7321 case Intrinsic::amdgcn_buffer_atomic_csub: 7322 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7323 break; 7324 case Intrinsic::amdgcn_buffer_atomic_smin: 7325 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7326 break; 7327 case Intrinsic::amdgcn_buffer_atomic_umin: 7328 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7329 break; 7330 case Intrinsic::amdgcn_buffer_atomic_smax: 7331 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7332 break; 7333 case Intrinsic::amdgcn_buffer_atomic_umax: 7334 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7335 break; 7336 case Intrinsic::amdgcn_buffer_atomic_and: 7337 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7338 break; 7339 case Intrinsic::amdgcn_buffer_atomic_or: 7340 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7341 break; 7342 case Intrinsic::amdgcn_buffer_atomic_xor: 7343 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7344 break; 7345 case Intrinsic::amdgcn_buffer_atomic_fadd: 7346 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7347 DiagnosticInfoUnsupported 7348 NoFpRet(DAG.getMachineFunction().getFunction(), 7349 "return versions of fp atomics not supported", 7350 DL.getDebugLoc(), DS_Error); 7351 DAG.getContext()->diagnose(NoFpRet); 7352 return SDValue(); 7353 } 7354 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7355 break; 7356 default: 7357 llvm_unreachable("unhandled atomic opcode"); 7358 } 7359 7360 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7361 M->getMemOperand()); 7362 } 7363 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7364 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7365 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7366 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7367 case Intrinsic::amdgcn_raw_buffer_atomic_fmin: 7368 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7369 case Intrinsic::amdgcn_struct_buffer_atomic_fmin: 7370 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7371 case Intrinsic::amdgcn_raw_buffer_atomic_fmax: 7372 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7373 case Intrinsic::amdgcn_struct_buffer_atomic_fmax: 7374 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7375 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7376 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7377 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7378 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7379 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7380 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7381 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7382 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7383 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7384 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7385 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7386 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7387 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7388 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7389 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7390 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7391 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7392 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7393 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7394 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7395 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7396 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7397 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7398 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7399 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7400 return lowerStructBufferAtomicIntrin(Op, DAG, 7401 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7402 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7403 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7404 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7405 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7406 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7407 return lowerStructBufferAtomicIntrin(Op, DAG, 7408 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7409 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7410 return lowerStructBufferAtomicIntrin(Op, DAG, 7411 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7412 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7413 return lowerStructBufferAtomicIntrin(Op, DAG, 7414 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7415 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7416 return lowerStructBufferAtomicIntrin(Op, DAG, 7417 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7418 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7419 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7420 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7421 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7422 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7423 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7424 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7425 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7426 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7427 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7428 7429 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7430 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7431 unsigned IdxEn = getIdxEn(Op.getOperand(5)); 7432 SDValue Ops[] = { 7433 Op.getOperand(0), // Chain 7434 Op.getOperand(2), // src 7435 Op.getOperand(3), // cmp 7436 Op.getOperand(4), // rsrc 7437 Op.getOperand(5), // vindex 7438 SDValue(), // voffset -- will be set by setBufferOffsets 7439 SDValue(), // soffset -- will be set by setBufferOffsets 7440 SDValue(), // offset -- will be set by setBufferOffsets 7441 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7442 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7443 }; 7444 setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7445 7446 EVT VT = Op.getValueType(); 7447 auto *M = cast<MemSDNode>(Op); 7448 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7449 7450 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7451 Op->getVTList(), Ops, VT, M->getMemOperand()); 7452 } 7453 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7454 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7455 SDValue Ops[] = { 7456 Op.getOperand(0), // Chain 7457 Op.getOperand(2), // src 7458 Op.getOperand(3), // cmp 7459 Op.getOperand(4), // rsrc 7460 DAG.getConstant(0, DL, MVT::i32), // vindex 7461 Offsets.first, // voffset 7462 Op.getOperand(6), // soffset 7463 Offsets.second, // offset 7464 Op.getOperand(7), // cachepolicy 7465 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7466 }; 7467 EVT VT = Op.getValueType(); 7468 auto *M = cast<MemSDNode>(Op); 7469 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]); 7470 7471 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7472 Op->getVTList(), Ops, VT, M->getMemOperand()); 7473 } 7474 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7475 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7476 SDValue Ops[] = { 7477 Op.getOperand(0), // Chain 7478 Op.getOperand(2), // src 7479 Op.getOperand(3), // cmp 7480 Op.getOperand(4), // rsrc 7481 Op.getOperand(5), // vindex 7482 Offsets.first, // voffset 7483 Op.getOperand(7), // soffset 7484 Offsets.second, // offset 7485 Op.getOperand(8), // cachepolicy 7486 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7487 }; 7488 EVT VT = Op.getValueType(); 7489 auto *M = cast<MemSDNode>(Op); 7490 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7491 7492 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7493 Op->getVTList(), Ops, VT, M->getMemOperand()); 7494 } 7495 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 7496 MemSDNode *M = cast<MemSDNode>(Op); 7497 SDValue NodePtr = M->getOperand(2); 7498 SDValue RayExtent = M->getOperand(3); 7499 SDValue RayOrigin = M->getOperand(4); 7500 SDValue RayDir = M->getOperand(5); 7501 SDValue RayInvDir = M->getOperand(6); 7502 SDValue TDescr = M->getOperand(7); 7503 7504 assert(NodePtr.getValueType() == MVT::i32 || 7505 NodePtr.getValueType() == MVT::i64); 7506 assert(RayDir.getValueType() == MVT::v3f16 || 7507 RayDir.getValueType() == MVT::v3f32); 7508 7509 if (!Subtarget->hasGFX10_AEncoding()) { 7510 emitRemovedIntrinsicError(DAG, DL, Op.getValueType()); 7511 return SDValue(); 7512 } 7513 7514 const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16; 7515 const bool Is64 = NodePtr.getValueType() == MVT::i64; 7516 const unsigned NumVDataDwords = 4; 7517 const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11); 7518 const bool UseNSA = Subtarget->hasNSAEncoding() && 7519 NumVAddrDwords <= Subtarget->getNSAMaxSize(); 7520 const unsigned BaseOpcodes[2][2] = { 7521 {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16}, 7522 {AMDGPU::IMAGE_BVH64_INTERSECT_RAY, 7523 AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}}; 7524 int Opcode; 7525 if (UseNSA) { 7526 Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16], 7527 AMDGPU::MIMGEncGfx10NSA, NumVDataDwords, 7528 NumVAddrDwords); 7529 } else { 7530 Opcode = AMDGPU::getMIMGOpcode( 7531 BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords, 7532 PowerOf2Ceil(NumVAddrDwords)); 7533 } 7534 assert(Opcode != -1); 7535 7536 SmallVector<SDValue, 16> Ops; 7537 7538 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) { 7539 SmallVector<SDValue, 3> Lanes; 7540 DAG.ExtractVectorElements(Op, Lanes, 0, 3); 7541 if (Lanes[0].getValueSizeInBits() == 32) { 7542 for (unsigned I = 0; I < 3; ++I) 7543 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I])); 7544 } else { 7545 if (IsAligned) { 7546 Ops.push_back( 7547 DAG.getBitcast(MVT::i32, 7548 DAG.getBuildVector(MVT::v2f16, DL, 7549 { Lanes[0], Lanes[1] }))); 7550 Ops.push_back(Lanes[2]); 7551 } else { 7552 SDValue Elt0 = Ops.pop_back_val(); 7553 Ops.push_back( 7554 DAG.getBitcast(MVT::i32, 7555 DAG.getBuildVector(MVT::v2f16, DL, 7556 { Elt0, Lanes[0] }))); 7557 Ops.push_back( 7558 DAG.getBitcast(MVT::i32, 7559 DAG.getBuildVector(MVT::v2f16, DL, 7560 { Lanes[1], Lanes[2] }))); 7561 } 7562 } 7563 }; 7564 7565 if (Is64) 7566 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2); 7567 else 7568 Ops.push_back(NodePtr); 7569 7570 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7571 packLanes(RayOrigin, true); 7572 packLanes(RayDir, true); 7573 packLanes(RayInvDir, false); 7574 7575 if (!UseNSA) { 7576 // Build a single vector containing all the operands so far prepared. 7577 if (NumVAddrDwords > 8) { 7578 SDValue Undef = DAG.getUNDEF(MVT::i32); 7579 Ops.append(16 - Ops.size(), Undef); 7580 } 7581 assert(Ops.size() == 8 || Ops.size() == 16); 7582 SDValue MergedOps = DAG.getBuildVector( 7583 Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops); 7584 Ops.clear(); 7585 Ops.push_back(MergedOps); 7586 } 7587 7588 Ops.push_back(TDescr); 7589 if (IsA16) 7590 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1)); 7591 Ops.push_back(M->getChain()); 7592 7593 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops); 7594 MachineMemOperand *MemRef = M->getMemOperand(); 7595 DAG.setNodeMemRefs(NewNode, {MemRef}); 7596 return SDValue(NewNode, 0); 7597 } 7598 case Intrinsic::amdgcn_global_atomic_fadd: 7599 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7600 DiagnosticInfoUnsupported 7601 NoFpRet(DAG.getMachineFunction().getFunction(), 7602 "return versions of fp atomics not supported", 7603 DL.getDebugLoc(), DS_Error); 7604 DAG.getContext()->diagnose(NoFpRet); 7605 return SDValue(); 7606 } 7607 LLVM_FALLTHROUGH; 7608 case Intrinsic::amdgcn_global_atomic_fmin: 7609 case Intrinsic::amdgcn_global_atomic_fmax: 7610 case Intrinsic::amdgcn_flat_atomic_fadd: 7611 case Intrinsic::amdgcn_flat_atomic_fmin: 7612 case Intrinsic::amdgcn_flat_atomic_fmax: { 7613 MemSDNode *M = cast<MemSDNode>(Op); 7614 SDValue Ops[] = { 7615 M->getOperand(0), // Chain 7616 M->getOperand(2), // Ptr 7617 M->getOperand(3) // Value 7618 }; 7619 unsigned Opcode = 0; 7620 switch (IntrID) { 7621 case Intrinsic::amdgcn_global_atomic_fadd: 7622 case Intrinsic::amdgcn_flat_atomic_fadd: { 7623 EVT VT = Op.getOperand(3).getValueType(); 7624 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7625 DAG.getVTList(VT, MVT::Other), Ops, 7626 M->getMemOperand()); 7627 } 7628 case Intrinsic::amdgcn_global_atomic_fmin: 7629 case Intrinsic::amdgcn_flat_atomic_fmin: { 7630 Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN; 7631 break; 7632 } 7633 case Intrinsic::amdgcn_global_atomic_fmax: 7634 case Intrinsic::amdgcn_flat_atomic_fmax: { 7635 Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX; 7636 break; 7637 } 7638 default: 7639 llvm_unreachable("unhandled atomic opcode"); 7640 } 7641 return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op), 7642 M->getVTList(), Ops, M->getMemoryVT(), 7643 M->getMemOperand()); 7644 } 7645 default: 7646 7647 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7648 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7649 return lowerImage(Op, ImageDimIntr, DAG, true); 7650 7651 return SDValue(); 7652 } 7653 } 7654 7655 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7656 // dwordx4 if on SI. 7657 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7658 SDVTList VTList, 7659 ArrayRef<SDValue> Ops, EVT MemVT, 7660 MachineMemOperand *MMO, 7661 SelectionDAG &DAG) const { 7662 EVT VT = VTList.VTs[0]; 7663 EVT WidenedVT = VT; 7664 EVT WidenedMemVT = MemVT; 7665 if (!Subtarget->hasDwordx3LoadStores() && 7666 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7667 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7668 WidenedVT.getVectorElementType(), 4); 7669 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7670 WidenedMemVT.getVectorElementType(), 4); 7671 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7672 } 7673 7674 assert(VTList.NumVTs == 2); 7675 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7676 7677 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7678 WidenedMemVT, MMO); 7679 if (WidenedVT != VT) { 7680 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7681 DAG.getVectorIdxConstant(0, DL)); 7682 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7683 } 7684 return NewOp; 7685 } 7686 7687 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG, 7688 bool ImageStore) const { 7689 EVT StoreVT = VData.getValueType(); 7690 7691 // No change for f16 and legal vector D16 types. 7692 if (!StoreVT.isVector()) 7693 return VData; 7694 7695 SDLoc DL(VData); 7696 unsigned NumElements = StoreVT.getVectorNumElements(); 7697 7698 if (Subtarget->hasUnpackedD16VMem()) { 7699 // We need to unpack the packed data to store. 7700 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7701 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7702 7703 EVT EquivStoreVT = 7704 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements); 7705 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7706 return DAG.UnrollVectorOp(ZExt.getNode()); 7707 } 7708 7709 // The sq block of gfx8.1 does not estimate register use correctly for d16 7710 // image store instructions. The data operand is computed as if it were not a 7711 // d16 image instruction. 7712 if (ImageStore && Subtarget->hasImageStoreD16Bug()) { 7713 // Bitcast to i16 7714 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7715 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7716 7717 // Decompose into scalars 7718 SmallVector<SDValue, 4> Elts; 7719 DAG.ExtractVectorElements(IntVData, Elts); 7720 7721 // Group pairs of i16 into v2i16 and bitcast to i32 7722 SmallVector<SDValue, 4> PackedElts; 7723 for (unsigned I = 0; I < Elts.size() / 2; I += 1) { 7724 SDValue Pair = 7725 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]}); 7726 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7727 PackedElts.push_back(IntPair); 7728 } 7729 if ((NumElements % 2) == 1) { 7730 // Handle v3i16 7731 unsigned I = Elts.size() / 2; 7732 SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL, 7733 {Elts[I * 2], DAG.getUNDEF(MVT::i16)}); 7734 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7735 PackedElts.push_back(IntPair); 7736 } 7737 7738 // Pad using UNDEF 7739 PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32)); 7740 7741 // Build final vector 7742 EVT VecVT = 7743 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size()); 7744 return DAG.getBuildVector(VecVT, DL, PackedElts); 7745 } 7746 7747 if (NumElements == 3) { 7748 EVT IntStoreVT = 7749 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits()); 7750 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7751 7752 EVT WidenedStoreVT = EVT::getVectorVT( 7753 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1); 7754 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(), 7755 WidenedStoreVT.getStoreSizeInBits()); 7756 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData); 7757 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt); 7758 } 7759 7760 assert(isTypeLegal(StoreVT)); 7761 return VData; 7762 } 7763 7764 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7765 SelectionDAG &DAG) const { 7766 SDLoc DL(Op); 7767 SDValue Chain = Op.getOperand(0); 7768 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7769 MachineFunction &MF = DAG.getMachineFunction(); 7770 7771 switch (IntrinsicID) { 7772 case Intrinsic::amdgcn_exp_compr: { 7773 SDValue Src0 = Op.getOperand(4); 7774 SDValue Src1 = Op.getOperand(5); 7775 // Hack around illegal type on SI by directly selecting it. 7776 if (isTypeLegal(Src0.getValueType())) 7777 return SDValue(); 7778 7779 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7780 SDValue Undef = DAG.getUNDEF(MVT::f32); 7781 const SDValue Ops[] = { 7782 Op.getOperand(2), // tgt 7783 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7784 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7785 Undef, // src2 7786 Undef, // src3 7787 Op.getOperand(7), // vm 7788 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7789 Op.getOperand(3), // en 7790 Op.getOperand(0) // Chain 7791 }; 7792 7793 unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7794 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7795 } 7796 case Intrinsic::amdgcn_s_barrier: { 7797 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7798 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7799 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7800 if (WGSize <= ST.getWavefrontSize()) 7801 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7802 Op.getOperand(0)), 0); 7803 } 7804 return SDValue(); 7805 }; 7806 case Intrinsic::amdgcn_tbuffer_store: { 7807 SDValue VData = Op.getOperand(2); 7808 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7809 if (IsD16) 7810 VData = handleD16VData(VData, DAG); 7811 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7812 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7813 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7814 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7815 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7816 SDValue Ops[] = { 7817 Chain, 7818 VData, // vdata 7819 Op.getOperand(3), // rsrc 7820 Op.getOperand(4), // vindex 7821 Op.getOperand(5), // voffset 7822 Op.getOperand(6), // soffset 7823 Op.getOperand(7), // offset 7824 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7825 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7826 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7827 }; 7828 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7829 AMDGPUISD::TBUFFER_STORE_FORMAT; 7830 MemSDNode *M = cast<MemSDNode>(Op); 7831 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7832 M->getMemoryVT(), M->getMemOperand()); 7833 } 7834 7835 case Intrinsic::amdgcn_struct_tbuffer_store: { 7836 SDValue VData = Op.getOperand(2); 7837 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7838 if (IsD16) 7839 VData = handleD16VData(VData, DAG); 7840 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7841 SDValue Ops[] = { 7842 Chain, 7843 VData, // vdata 7844 Op.getOperand(3), // rsrc 7845 Op.getOperand(4), // vindex 7846 Offsets.first, // voffset 7847 Op.getOperand(6), // soffset 7848 Offsets.second, // offset 7849 Op.getOperand(7), // format 7850 Op.getOperand(8), // cachepolicy, swizzled buffer 7851 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7852 }; 7853 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7854 AMDGPUISD::TBUFFER_STORE_FORMAT; 7855 MemSDNode *M = cast<MemSDNode>(Op); 7856 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7857 M->getMemoryVT(), M->getMemOperand()); 7858 } 7859 7860 case Intrinsic::amdgcn_raw_tbuffer_store: { 7861 SDValue VData = Op.getOperand(2); 7862 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7863 if (IsD16) 7864 VData = handleD16VData(VData, DAG); 7865 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7866 SDValue Ops[] = { 7867 Chain, 7868 VData, // vdata 7869 Op.getOperand(3), // rsrc 7870 DAG.getConstant(0, DL, MVT::i32), // vindex 7871 Offsets.first, // voffset 7872 Op.getOperand(5), // soffset 7873 Offsets.second, // offset 7874 Op.getOperand(6), // format 7875 Op.getOperand(7), // cachepolicy, swizzled buffer 7876 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7877 }; 7878 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7879 AMDGPUISD::TBUFFER_STORE_FORMAT; 7880 MemSDNode *M = cast<MemSDNode>(Op); 7881 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7882 M->getMemoryVT(), M->getMemOperand()); 7883 } 7884 7885 case Intrinsic::amdgcn_buffer_store: 7886 case Intrinsic::amdgcn_buffer_store_format: { 7887 SDValue VData = Op.getOperand(2); 7888 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7889 if (IsD16) 7890 VData = handleD16VData(VData, DAG); 7891 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7892 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7893 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7894 SDValue Ops[] = { 7895 Chain, 7896 VData, 7897 Op.getOperand(3), // rsrc 7898 Op.getOperand(4), // vindex 7899 SDValue(), // voffset -- will be set by setBufferOffsets 7900 SDValue(), // soffset -- will be set by setBufferOffsets 7901 SDValue(), // offset -- will be set by setBufferOffsets 7902 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7903 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7904 }; 7905 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7906 7907 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7908 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7909 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7910 MemSDNode *M = cast<MemSDNode>(Op); 7911 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7912 7913 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7914 EVT VDataType = VData.getValueType().getScalarType(); 7915 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7916 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7917 7918 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7919 M->getMemoryVT(), M->getMemOperand()); 7920 } 7921 7922 case Intrinsic::amdgcn_raw_buffer_store: 7923 case Intrinsic::amdgcn_raw_buffer_store_format: { 7924 const bool IsFormat = 7925 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7926 7927 SDValue VData = Op.getOperand(2); 7928 EVT VDataVT = VData.getValueType(); 7929 EVT EltType = VDataVT.getScalarType(); 7930 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7931 if (IsD16) { 7932 VData = handleD16VData(VData, DAG); 7933 VDataVT = VData.getValueType(); 7934 } 7935 7936 if (!isTypeLegal(VDataVT)) { 7937 VData = 7938 DAG.getNode(ISD::BITCAST, DL, 7939 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7940 } 7941 7942 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7943 SDValue Ops[] = { 7944 Chain, 7945 VData, 7946 Op.getOperand(3), // rsrc 7947 DAG.getConstant(0, DL, MVT::i32), // vindex 7948 Offsets.first, // voffset 7949 Op.getOperand(5), // soffset 7950 Offsets.second, // offset 7951 Op.getOperand(6), // cachepolicy, swizzled buffer 7952 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7953 }; 7954 unsigned Opc = 7955 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7956 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7957 MemSDNode *M = cast<MemSDNode>(Op); 7958 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 7959 7960 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7961 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7962 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7963 7964 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7965 M->getMemoryVT(), M->getMemOperand()); 7966 } 7967 7968 case Intrinsic::amdgcn_struct_buffer_store: 7969 case Intrinsic::amdgcn_struct_buffer_store_format: { 7970 const bool IsFormat = 7971 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7972 7973 SDValue VData = Op.getOperand(2); 7974 EVT VDataVT = VData.getValueType(); 7975 EVT EltType = VDataVT.getScalarType(); 7976 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7977 7978 if (IsD16) { 7979 VData = handleD16VData(VData, DAG); 7980 VDataVT = VData.getValueType(); 7981 } 7982 7983 if (!isTypeLegal(VDataVT)) { 7984 VData = 7985 DAG.getNode(ISD::BITCAST, DL, 7986 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7987 } 7988 7989 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7990 SDValue Ops[] = { 7991 Chain, 7992 VData, 7993 Op.getOperand(3), // rsrc 7994 Op.getOperand(4), // vindex 7995 Offsets.first, // voffset 7996 Op.getOperand(6), // soffset 7997 Offsets.second, // offset 7998 Op.getOperand(7), // cachepolicy, swizzled buffer 7999 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 8000 }; 8001 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 8002 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 8003 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 8004 MemSDNode *M = cast<MemSDNode>(Op); 8005 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 8006 8007 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 8008 EVT VDataType = VData.getValueType().getScalarType(); 8009 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 8010 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 8011 8012 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8013 M->getMemoryVT(), M->getMemOperand()); 8014 } 8015 case Intrinsic::amdgcn_end_cf: 8016 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 8017 Op->getOperand(2), Chain), 0); 8018 8019 default: { 8020 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 8021 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 8022 return lowerImage(Op, ImageDimIntr, DAG, true); 8023 8024 return Op; 8025 } 8026 } 8027 } 8028 8029 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 8030 // offset (the offset that is included in bounds checking and swizzling, to be 8031 // split between the instruction's voffset and immoffset fields) and soffset 8032 // (the offset that is excluded from bounds checking and swizzling, to go in 8033 // the instruction's soffset field). This function takes the first kind of 8034 // offset and figures out how to split it between voffset and immoffset. 8035 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 8036 SDValue Offset, SelectionDAG &DAG) const { 8037 SDLoc DL(Offset); 8038 const unsigned MaxImm = 4095; 8039 SDValue N0 = Offset; 8040 ConstantSDNode *C1 = nullptr; 8041 8042 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 8043 N0 = SDValue(); 8044 else if (DAG.isBaseWithConstantOffset(N0)) { 8045 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 8046 N0 = N0.getOperand(0); 8047 } 8048 8049 if (C1) { 8050 unsigned ImmOffset = C1->getZExtValue(); 8051 // If the immediate value is too big for the immoffset field, put the value 8052 // and -4096 into the immoffset field so that the value that is copied/added 8053 // for the voffset field is a multiple of 4096, and it stands more chance 8054 // of being CSEd with the copy/add for another similar load/store. 8055 // However, do not do that rounding down to a multiple of 4096 if that is a 8056 // negative number, as it appears to be illegal to have a negative offset 8057 // in the vgpr, even if adding the immediate offset makes it positive. 8058 unsigned Overflow = ImmOffset & ~MaxImm; 8059 ImmOffset -= Overflow; 8060 if ((int32_t)Overflow < 0) { 8061 Overflow += ImmOffset; 8062 ImmOffset = 0; 8063 } 8064 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 8065 if (Overflow) { 8066 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 8067 if (!N0) 8068 N0 = OverflowVal; 8069 else { 8070 SDValue Ops[] = { N0, OverflowVal }; 8071 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 8072 } 8073 } 8074 } 8075 if (!N0) 8076 N0 = DAG.getConstant(0, DL, MVT::i32); 8077 if (!C1) 8078 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 8079 return {N0, SDValue(C1, 0)}; 8080 } 8081 8082 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 8083 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 8084 // pointed to by Offsets. 8085 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 8086 SelectionDAG &DAG, SDValue *Offsets, 8087 Align Alignment) const { 8088 SDLoc DL(CombinedOffset); 8089 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 8090 uint32_t Imm = C->getZExtValue(); 8091 uint32_t SOffset, ImmOffset; 8092 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 8093 Alignment)) { 8094 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 8095 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 8096 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 8097 return; 8098 } 8099 } 8100 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 8101 SDValue N0 = CombinedOffset.getOperand(0); 8102 SDValue N1 = CombinedOffset.getOperand(1); 8103 uint32_t SOffset, ImmOffset; 8104 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 8105 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 8106 Subtarget, Alignment)) { 8107 Offsets[0] = N0; 8108 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 8109 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 8110 return; 8111 } 8112 } 8113 Offsets[0] = CombinedOffset; 8114 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 8115 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 8116 } 8117 8118 // Handle 8 bit and 16 bit buffer loads 8119 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 8120 EVT LoadVT, SDLoc DL, 8121 ArrayRef<SDValue> Ops, 8122 MemSDNode *M) const { 8123 EVT IntVT = LoadVT.changeTypeToInteger(); 8124 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 8125 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 8126 8127 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 8128 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 8129 Ops, IntVT, 8130 M->getMemOperand()); 8131 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 8132 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 8133 8134 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 8135 } 8136 8137 // Handle 8 bit and 16 bit buffer stores 8138 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 8139 EVT VDataType, SDLoc DL, 8140 SDValue Ops[], 8141 MemSDNode *M) const { 8142 if (VDataType == MVT::f16) 8143 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 8144 8145 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 8146 Ops[1] = BufferStoreExt; 8147 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 8148 AMDGPUISD::BUFFER_STORE_SHORT; 8149 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 8150 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 8151 M->getMemOperand()); 8152 } 8153 8154 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 8155 ISD::LoadExtType ExtType, SDValue Op, 8156 const SDLoc &SL, EVT VT) { 8157 if (VT.bitsLT(Op.getValueType())) 8158 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 8159 8160 switch (ExtType) { 8161 case ISD::SEXTLOAD: 8162 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 8163 case ISD::ZEXTLOAD: 8164 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 8165 case ISD::EXTLOAD: 8166 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 8167 case ISD::NON_EXTLOAD: 8168 return Op; 8169 } 8170 8171 llvm_unreachable("invalid ext type"); 8172 } 8173 8174 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 8175 SelectionDAG &DAG = DCI.DAG; 8176 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 8177 return SDValue(); 8178 8179 // FIXME: Constant loads should all be marked invariant. 8180 unsigned AS = Ld->getAddressSpace(); 8181 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 8182 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 8183 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 8184 return SDValue(); 8185 8186 // Don't do this early, since it may interfere with adjacent load merging for 8187 // illegal types. We can avoid losing alignment information for exotic types 8188 // pre-legalize. 8189 EVT MemVT = Ld->getMemoryVT(); 8190 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 8191 MemVT.getSizeInBits() >= 32) 8192 return SDValue(); 8193 8194 SDLoc SL(Ld); 8195 8196 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 8197 "unexpected vector extload"); 8198 8199 // TODO: Drop only high part of range. 8200 SDValue Ptr = Ld->getBasePtr(); 8201 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 8202 MVT::i32, SL, Ld->getChain(), Ptr, 8203 Ld->getOffset(), 8204 Ld->getPointerInfo(), MVT::i32, 8205 Ld->getAlignment(), 8206 Ld->getMemOperand()->getFlags(), 8207 Ld->getAAInfo(), 8208 nullptr); // Drop ranges 8209 8210 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 8211 if (MemVT.isFloatingPoint()) { 8212 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 8213 "unexpected fp extload"); 8214 TruncVT = MemVT.changeTypeToInteger(); 8215 } 8216 8217 SDValue Cvt = NewLoad; 8218 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 8219 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 8220 DAG.getValueType(TruncVT)); 8221 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 8222 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 8223 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 8224 } else { 8225 assert(Ld->getExtensionType() == ISD::EXTLOAD); 8226 } 8227 8228 EVT VT = Ld->getValueType(0); 8229 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 8230 8231 DCI.AddToWorklist(Cvt.getNode()); 8232 8233 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 8234 // the appropriate extension from the 32-bit load. 8235 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 8236 DCI.AddToWorklist(Cvt.getNode()); 8237 8238 // Handle conversion back to floating point if necessary. 8239 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 8240 8241 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 8242 } 8243 8244 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 8245 SDLoc DL(Op); 8246 LoadSDNode *Load = cast<LoadSDNode>(Op); 8247 ISD::LoadExtType ExtType = Load->getExtensionType(); 8248 EVT MemVT = Load->getMemoryVT(); 8249 8250 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 8251 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 8252 return SDValue(); 8253 8254 // FIXME: Copied from PPC 8255 // First, load into 32 bits, then truncate to 1 bit. 8256 8257 SDValue Chain = Load->getChain(); 8258 SDValue BasePtr = Load->getBasePtr(); 8259 MachineMemOperand *MMO = Load->getMemOperand(); 8260 8261 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 8262 8263 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 8264 BasePtr, RealMemVT, MMO); 8265 8266 if (!MemVT.isVector()) { 8267 SDValue Ops[] = { 8268 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 8269 NewLD.getValue(1) 8270 }; 8271 8272 return DAG.getMergeValues(Ops, DL); 8273 } 8274 8275 SmallVector<SDValue, 3> Elts; 8276 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 8277 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 8278 DAG.getConstant(I, DL, MVT::i32)); 8279 8280 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 8281 } 8282 8283 SDValue Ops[] = { 8284 DAG.getBuildVector(MemVT, DL, Elts), 8285 NewLD.getValue(1) 8286 }; 8287 8288 return DAG.getMergeValues(Ops, DL); 8289 } 8290 8291 if (!MemVT.isVector()) 8292 return SDValue(); 8293 8294 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 8295 "Custom lowering for non-i32 vectors hasn't been implemented."); 8296 8297 unsigned Alignment = Load->getAlignment(); 8298 unsigned AS = Load->getAddressSpace(); 8299 if (Subtarget->hasLDSMisalignedBug() && 8300 AS == AMDGPUAS::FLAT_ADDRESS && 8301 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 8302 return SplitVectorLoad(Op, DAG); 8303 } 8304 8305 MachineFunction &MF = DAG.getMachineFunction(); 8306 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8307 // If there is a possibilty that flat instruction access scratch memory 8308 // then we need to use the same legalization rules we use for private. 8309 if (AS == AMDGPUAS::FLAT_ADDRESS && 8310 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8311 AS = MFI->hasFlatScratchInit() ? 8312 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8313 8314 unsigned NumElements = MemVT.getVectorNumElements(); 8315 8316 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8317 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 8318 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 8319 if (MemVT.isPow2VectorType()) 8320 return SDValue(); 8321 return WidenOrSplitVectorLoad(Op, DAG); 8322 } 8323 // Non-uniform loads will be selected to MUBUF instructions, so they 8324 // have the same legalization requirements as global and private 8325 // loads. 8326 // 8327 } 8328 8329 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8330 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8331 AS == AMDGPUAS::GLOBAL_ADDRESS) { 8332 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 8333 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 8334 Alignment >= 4 && NumElements < 32) { 8335 if (MemVT.isPow2VectorType()) 8336 return SDValue(); 8337 return WidenOrSplitVectorLoad(Op, DAG); 8338 } 8339 // Non-uniform loads will be selected to MUBUF instructions, so they 8340 // have the same legalization requirements as global and private 8341 // loads. 8342 // 8343 } 8344 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8345 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8346 AS == AMDGPUAS::GLOBAL_ADDRESS || 8347 AS == AMDGPUAS::FLAT_ADDRESS) { 8348 if (NumElements > 4) 8349 return SplitVectorLoad(Op, DAG); 8350 // v3 loads not supported on SI. 8351 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8352 return WidenOrSplitVectorLoad(Op, DAG); 8353 8354 // v3 and v4 loads are supported for private and global memory. 8355 return SDValue(); 8356 } 8357 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8358 // Depending on the setting of the private_element_size field in the 8359 // resource descriptor, we can only make private accesses up to a certain 8360 // size. 8361 switch (Subtarget->getMaxPrivateElementSize()) { 8362 case 4: { 8363 SDValue Ops[2]; 8364 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 8365 return DAG.getMergeValues(Ops, DL); 8366 } 8367 case 8: 8368 if (NumElements > 2) 8369 return SplitVectorLoad(Op, DAG); 8370 return SDValue(); 8371 case 16: 8372 // Same as global/flat 8373 if (NumElements > 4) 8374 return SplitVectorLoad(Op, DAG); 8375 // v3 loads not supported on SI. 8376 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8377 return WidenOrSplitVectorLoad(Op, DAG); 8378 8379 return SDValue(); 8380 default: 8381 llvm_unreachable("unsupported private_element_size"); 8382 } 8383 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8384 // Use ds_read_b128 or ds_read_b96 when possible. 8385 if (Subtarget->hasDS96AndDS128() && 8386 ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) || 8387 MemVT.getStoreSize() == 12) && 8388 allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 8389 Load->getAlign())) 8390 return SDValue(); 8391 8392 if (NumElements > 2) 8393 return SplitVectorLoad(Op, DAG); 8394 8395 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8396 // address is negative, then the instruction is incorrectly treated as 8397 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8398 // loads here to avoid emitting ds_read2_b32. We may re-combine the 8399 // load later in the SILoadStoreOptimizer. 8400 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 8401 NumElements == 2 && MemVT.getStoreSize() == 8 && 8402 Load->getAlignment() < 8) { 8403 return SplitVectorLoad(Op, DAG); 8404 } 8405 } 8406 8407 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8408 MemVT, *Load->getMemOperand())) { 8409 SDValue Ops[2]; 8410 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 8411 return DAG.getMergeValues(Ops, DL); 8412 } 8413 8414 return SDValue(); 8415 } 8416 8417 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8418 EVT VT = Op.getValueType(); 8419 assert(VT.getSizeInBits() == 64); 8420 8421 SDLoc DL(Op); 8422 SDValue Cond = Op.getOperand(0); 8423 8424 if (Subtarget->hasScalarCompareEq64() && Op->getOperand(0)->hasOneUse() && 8425 !Op->isDivergent()) { 8426 if (VT == MVT::i64) 8427 return Op; 8428 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(1)); 8429 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(2)); 8430 return DAG.getNode(ISD::BITCAST, DL, VT, 8431 DAG.getSelect(DL, MVT::i64, Cond, LHS, RHS)); 8432 } 8433 8434 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8435 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8436 8437 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8438 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8439 8440 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8441 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8442 8443 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8444 8445 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8446 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8447 8448 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8449 8450 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8451 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8452 } 8453 8454 // Catch division cases where we can use shortcuts with rcp and rsq 8455 // instructions. 8456 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8457 SelectionDAG &DAG) const { 8458 SDLoc SL(Op); 8459 SDValue LHS = Op.getOperand(0); 8460 SDValue RHS = Op.getOperand(1); 8461 EVT VT = Op.getValueType(); 8462 const SDNodeFlags Flags = Op->getFlags(); 8463 8464 bool AllowInaccurateRcp = Flags.hasApproximateFuncs(); 8465 8466 // Without !fpmath accuracy information, we can't do more because we don't 8467 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8468 if (!AllowInaccurateRcp) 8469 return SDValue(); 8470 8471 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8472 if (CLHS->isExactlyValue(1.0)) { 8473 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8474 // the CI documentation has a worst case error of 1 ulp. 8475 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8476 // use it as long as we aren't trying to use denormals. 8477 // 8478 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8479 8480 // 1.0 / sqrt(x) -> rsq(x) 8481 8482 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8483 // error seems really high at 2^29 ULP. 8484 if (RHS.getOpcode() == ISD::FSQRT) 8485 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8486 8487 // 1.0 / x -> rcp(x) 8488 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8489 } 8490 8491 // Same as for 1.0, but expand the sign out of the constant. 8492 if (CLHS->isExactlyValue(-1.0)) { 8493 // -1.0 / x -> rcp (fneg x) 8494 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8495 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8496 } 8497 } 8498 8499 // Turn into multiply by the reciprocal. 8500 // x / y -> x * (1.0 / y) 8501 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8502 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8503 } 8504 8505 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op, 8506 SelectionDAG &DAG) const { 8507 SDLoc SL(Op); 8508 SDValue X = Op.getOperand(0); 8509 SDValue Y = Op.getOperand(1); 8510 EVT VT = Op.getValueType(); 8511 const SDNodeFlags Flags = Op->getFlags(); 8512 8513 bool AllowInaccurateDiv = Flags.hasApproximateFuncs() || 8514 DAG.getTarget().Options.UnsafeFPMath; 8515 if (!AllowInaccurateDiv) 8516 return SDValue(); 8517 8518 SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y); 8519 SDValue One = DAG.getConstantFP(1.0, SL, VT); 8520 8521 SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y); 8522 SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8523 8524 R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R); 8525 SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8526 R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R); 8527 SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R); 8528 SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X); 8529 return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret); 8530 } 8531 8532 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8533 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8534 SDNodeFlags Flags) { 8535 if (GlueChain->getNumValues() <= 1) { 8536 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8537 } 8538 8539 assert(GlueChain->getNumValues() == 3); 8540 8541 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8542 switch (Opcode) { 8543 default: llvm_unreachable("no chain equivalent for opcode"); 8544 case ISD::FMUL: 8545 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8546 break; 8547 } 8548 8549 return DAG.getNode(Opcode, SL, VTList, 8550 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8551 Flags); 8552 } 8553 8554 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8555 EVT VT, SDValue A, SDValue B, SDValue C, 8556 SDValue GlueChain, SDNodeFlags Flags) { 8557 if (GlueChain->getNumValues() <= 1) { 8558 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8559 } 8560 8561 assert(GlueChain->getNumValues() == 3); 8562 8563 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8564 switch (Opcode) { 8565 default: llvm_unreachable("no chain equivalent for opcode"); 8566 case ISD::FMA: 8567 Opcode = AMDGPUISD::FMA_W_CHAIN; 8568 break; 8569 } 8570 8571 return DAG.getNode(Opcode, SL, VTList, 8572 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8573 Flags); 8574 } 8575 8576 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8577 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8578 return FastLowered; 8579 8580 SDLoc SL(Op); 8581 SDValue Src0 = Op.getOperand(0); 8582 SDValue Src1 = Op.getOperand(1); 8583 8584 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8585 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8586 8587 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8588 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8589 8590 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8591 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8592 8593 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8594 } 8595 8596 // Faster 2.5 ULP division that does not support denormals. 8597 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8598 SDLoc SL(Op); 8599 SDValue LHS = Op.getOperand(1); 8600 SDValue RHS = Op.getOperand(2); 8601 8602 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8603 8604 const APFloat K0Val(BitsToFloat(0x6f800000)); 8605 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8606 8607 const APFloat K1Val(BitsToFloat(0x2f800000)); 8608 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8609 8610 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8611 8612 EVT SetCCVT = 8613 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8614 8615 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8616 8617 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8618 8619 // TODO: Should this propagate fast-math-flags? 8620 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8621 8622 // rcp does not support denormals. 8623 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8624 8625 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8626 8627 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8628 } 8629 8630 // Returns immediate value for setting the F32 denorm mode when using the 8631 // S_DENORM_MODE instruction. 8632 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8633 const SDLoc &SL, const GCNSubtarget *ST) { 8634 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8635 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8636 ? FP_DENORM_FLUSH_NONE 8637 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8638 8639 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8640 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8641 } 8642 8643 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8644 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8645 return FastLowered; 8646 8647 // The selection matcher assumes anything with a chain selecting to a 8648 // mayRaiseFPException machine instruction. Since we're introducing a chain 8649 // here, we need to explicitly report nofpexcept for the regular fdiv 8650 // lowering. 8651 SDNodeFlags Flags = Op->getFlags(); 8652 Flags.setNoFPExcept(true); 8653 8654 SDLoc SL(Op); 8655 SDValue LHS = Op.getOperand(0); 8656 SDValue RHS = Op.getOperand(1); 8657 8658 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8659 8660 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8661 8662 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8663 {RHS, RHS, LHS}, Flags); 8664 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8665 {LHS, RHS, LHS}, Flags); 8666 8667 // Denominator is scaled to not be denormal, so using rcp is ok. 8668 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8669 DenominatorScaled, Flags); 8670 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8671 DenominatorScaled, Flags); 8672 8673 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8674 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8675 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8676 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8677 8678 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8679 8680 if (!HasFP32Denormals) { 8681 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8682 // lowering. The chain dependence is insufficient, and we need glue. We do 8683 // not need the glue variants in a strictfp function. 8684 8685 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8686 8687 SDNode *EnableDenorm; 8688 if (Subtarget->hasDenormModeInst()) { 8689 const SDValue EnableDenormValue = 8690 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8691 8692 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8693 DAG.getEntryNode(), EnableDenormValue).getNode(); 8694 } else { 8695 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8696 SL, MVT::i32); 8697 EnableDenorm = 8698 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8699 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8700 } 8701 8702 SDValue Ops[3] = { 8703 NegDivScale0, 8704 SDValue(EnableDenorm, 0), 8705 SDValue(EnableDenorm, 1) 8706 }; 8707 8708 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8709 } 8710 8711 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8712 ApproxRcp, One, NegDivScale0, Flags); 8713 8714 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8715 ApproxRcp, Fma0, Flags); 8716 8717 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8718 Fma1, Fma1, Flags); 8719 8720 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8721 NumeratorScaled, Mul, Flags); 8722 8723 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8724 Fma2, Fma1, Mul, Fma2, Flags); 8725 8726 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8727 NumeratorScaled, Fma3, Flags); 8728 8729 if (!HasFP32Denormals) { 8730 SDNode *DisableDenorm; 8731 if (Subtarget->hasDenormModeInst()) { 8732 const SDValue DisableDenormValue = 8733 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8734 8735 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8736 Fma4.getValue(1), DisableDenormValue, 8737 Fma4.getValue(2)).getNode(); 8738 } else { 8739 const SDValue DisableDenormValue = 8740 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8741 8742 DisableDenorm = DAG.getMachineNode( 8743 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8744 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8745 } 8746 8747 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8748 SDValue(DisableDenorm, 0), DAG.getRoot()); 8749 DAG.setRoot(OutputChain); 8750 } 8751 8752 SDValue Scale = NumeratorScaled.getValue(1); 8753 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8754 {Fma4, Fma1, Fma3, Scale}, Flags); 8755 8756 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8757 } 8758 8759 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8760 if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG)) 8761 return FastLowered; 8762 8763 SDLoc SL(Op); 8764 SDValue X = Op.getOperand(0); 8765 SDValue Y = Op.getOperand(1); 8766 8767 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8768 8769 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8770 8771 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8772 8773 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8774 8775 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8776 8777 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8778 8779 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8780 8781 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8782 8783 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8784 8785 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8786 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8787 8788 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8789 NegDivScale0, Mul, DivScale1); 8790 8791 SDValue Scale; 8792 8793 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8794 // Workaround a hardware bug on SI where the condition output from div_scale 8795 // is not usable. 8796 8797 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8798 8799 // Figure out if the scale to use for div_fmas. 8800 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8801 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8802 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8803 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8804 8805 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8806 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8807 8808 SDValue Scale0Hi 8809 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8810 SDValue Scale1Hi 8811 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8812 8813 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8814 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8815 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8816 } else { 8817 Scale = DivScale1.getValue(1); 8818 } 8819 8820 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8821 Fma4, Fma3, Mul, Scale); 8822 8823 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8824 } 8825 8826 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8827 EVT VT = Op.getValueType(); 8828 8829 if (VT == MVT::f32) 8830 return LowerFDIV32(Op, DAG); 8831 8832 if (VT == MVT::f64) 8833 return LowerFDIV64(Op, DAG); 8834 8835 if (VT == MVT::f16) 8836 return LowerFDIV16(Op, DAG); 8837 8838 llvm_unreachable("Unexpected type for fdiv"); 8839 } 8840 8841 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8842 SDLoc DL(Op); 8843 StoreSDNode *Store = cast<StoreSDNode>(Op); 8844 EVT VT = Store->getMemoryVT(); 8845 8846 if (VT == MVT::i1) { 8847 return DAG.getTruncStore(Store->getChain(), DL, 8848 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8849 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8850 } 8851 8852 assert(VT.isVector() && 8853 Store->getValue().getValueType().getScalarType() == MVT::i32); 8854 8855 unsigned AS = Store->getAddressSpace(); 8856 if (Subtarget->hasLDSMisalignedBug() && 8857 AS == AMDGPUAS::FLAT_ADDRESS && 8858 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8859 return SplitVectorStore(Op, DAG); 8860 } 8861 8862 MachineFunction &MF = DAG.getMachineFunction(); 8863 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8864 // If there is a possibilty that flat instruction access scratch memory 8865 // then we need to use the same legalization rules we use for private. 8866 if (AS == AMDGPUAS::FLAT_ADDRESS && 8867 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8868 AS = MFI->hasFlatScratchInit() ? 8869 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8870 8871 unsigned NumElements = VT.getVectorNumElements(); 8872 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8873 AS == AMDGPUAS::FLAT_ADDRESS) { 8874 if (NumElements > 4) 8875 return SplitVectorStore(Op, DAG); 8876 // v3 stores not supported on SI. 8877 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8878 return SplitVectorStore(Op, DAG); 8879 8880 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8881 VT, *Store->getMemOperand())) 8882 return expandUnalignedStore(Store, DAG); 8883 8884 return SDValue(); 8885 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8886 switch (Subtarget->getMaxPrivateElementSize()) { 8887 case 4: 8888 return scalarizeVectorStore(Store, DAG); 8889 case 8: 8890 if (NumElements > 2) 8891 return SplitVectorStore(Op, DAG); 8892 return SDValue(); 8893 case 16: 8894 if (NumElements > 4 || 8895 (NumElements == 3 && !Subtarget->enableFlatScratch())) 8896 return SplitVectorStore(Op, DAG); 8897 return SDValue(); 8898 default: 8899 llvm_unreachable("unsupported private_element_size"); 8900 } 8901 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8902 // Use ds_write_b128 or ds_write_b96 when possible. 8903 if (Subtarget->hasDS96AndDS128() && 8904 ((Subtarget->useDS128() && VT.getStoreSize() == 16) || 8905 (VT.getStoreSize() == 12)) && 8906 allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 8907 Store->getAlign())) 8908 return SDValue(); 8909 8910 if (NumElements > 2) 8911 return SplitVectorStore(Op, DAG); 8912 8913 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8914 // address is negative, then the instruction is incorrectly treated as 8915 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8916 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8917 // store later in the SILoadStoreOptimizer. 8918 if (!Subtarget->hasUsableDSOffset() && 8919 NumElements == 2 && VT.getStoreSize() == 8 && 8920 Store->getAlignment() < 8) { 8921 return SplitVectorStore(Op, DAG); 8922 } 8923 8924 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8925 VT, *Store->getMemOperand())) { 8926 if (VT.isVector()) 8927 return SplitVectorStore(Op, DAG); 8928 return expandUnalignedStore(Store, DAG); 8929 } 8930 8931 return SDValue(); 8932 } else { 8933 llvm_unreachable("unhandled address space"); 8934 } 8935 } 8936 8937 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8938 SDLoc DL(Op); 8939 EVT VT = Op.getValueType(); 8940 SDValue Arg = Op.getOperand(0); 8941 SDValue TrigVal; 8942 8943 // Propagate fast-math flags so that the multiply we introduce can be folded 8944 // if Arg is already the result of a multiply by constant. 8945 auto Flags = Op->getFlags(); 8946 8947 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 8948 8949 if (Subtarget->hasTrigReducedRange()) { 8950 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8951 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 8952 } else { 8953 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8954 } 8955 8956 switch (Op.getOpcode()) { 8957 case ISD::FCOS: 8958 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 8959 case ISD::FSIN: 8960 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 8961 default: 8962 llvm_unreachable("Wrong trig opcode"); 8963 } 8964 } 8965 8966 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8967 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8968 assert(AtomicNode->isCompareAndSwap()); 8969 unsigned AS = AtomicNode->getAddressSpace(); 8970 8971 // No custom lowering required for local address space 8972 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 8973 return Op; 8974 8975 // Non-local address space requires custom lowering for atomic compare 8976 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8977 SDLoc DL(Op); 8978 SDValue ChainIn = Op.getOperand(0); 8979 SDValue Addr = Op.getOperand(1); 8980 SDValue Old = Op.getOperand(2); 8981 SDValue New = Op.getOperand(3); 8982 EVT VT = Op.getValueType(); 8983 MVT SimpleVT = VT.getSimpleVT(); 8984 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8985 8986 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8987 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8988 8989 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8990 Ops, VT, AtomicNode->getMemOperand()); 8991 } 8992 8993 //===----------------------------------------------------------------------===// 8994 // Custom DAG optimizations 8995 //===----------------------------------------------------------------------===// 8996 8997 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8998 DAGCombinerInfo &DCI) const { 8999 EVT VT = N->getValueType(0); 9000 EVT ScalarVT = VT.getScalarType(); 9001 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 9002 return SDValue(); 9003 9004 SelectionDAG &DAG = DCI.DAG; 9005 SDLoc DL(N); 9006 9007 SDValue Src = N->getOperand(0); 9008 EVT SrcVT = Src.getValueType(); 9009 9010 // TODO: We could try to match extracting the higher bytes, which would be 9011 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 9012 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 9013 // about in practice. 9014 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 9015 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 9016 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 9017 DCI.AddToWorklist(Cvt.getNode()); 9018 9019 // For the f16 case, fold to a cast to f32 and then cast back to f16. 9020 if (ScalarVT != MVT::f32) { 9021 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 9022 DAG.getTargetConstant(0, DL, MVT::i32)); 9023 } 9024 return Cvt; 9025 } 9026 } 9027 9028 return SDValue(); 9029 } 9030 9031 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 9032 9033 // This is a variant of 9034 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 9035 // 9036 // The normal DAG combiner will do this, but only if the add has one use since 9037 // that would increase the number of instructions. 9038 // 9039 // This prevents us from seeing a constant offset that can be folded into a 9040 // memory instruction's addressing mode. If we know the resulting add offset of 9041 // a pointer can be folded into an addressing offset, we can replace the pointer 9042 // operand with the add of new constant offset. This eliminates one of the uses, 9043 // and may allow the remaining use to also be simplified. 9044 // 9045 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 9046 unsigned AddrSpace, 9047 EVT MemVT, 9048 DAGCombinerInfo &DCI) const { 9049 SDValue N0 = N->getOperand(0); 9050 SDValue N1 = N->getOperand(1); 9051 9052 // We only do this to handle cases where it's profitable when there are 9053 // multiple uses of the add, so defer to the standard combine. 9054 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 9055 N0->hasOneUse()) 9056 return SDValue(); 9057 9058 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 9059 if (!CN1) 9060 return SDValue(); 9061 9062 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 9063 if (!CAdd) 9064 return SDValue(); 9065 9066 // If the resulting offset is too large, we can't fold it into the addressing 9067 // mode offset. 9068 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 9069 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 9070 9071 AddrMode AM; 9072 AM.HasBaseReg = true; 9073 AM.BaseOffs = Offset.getSExtValue(); 9074 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 9075 return SDValue(); 9076 9077 SelectionDAG &DAG = DCI.DAG; 9078 SDLoc SL(N); 9079 EVT VT = N->getValueType(0); 9080 9081 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 9082 SDValue COffset = DAG.getConstant(Offset, SL, VT); 9083 9084 SDNodeFlags Flags; 9085 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 9086 (N0.getOpcode() == ISD::OR || 9087 N0->getFlags().hasNoUnsignedWrap())); 9088 9089 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 9090 } 9091 9092 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 9093 /// by the chain and intrinsic ID. Theoretically we would also need to check the 9094 /// specific intrinsic, but they all place the pointer operand first. 9095 static unsigned getBasePtrIndex(const MemSDNode *N) { 9096 switch (N->getOpcode()) { 9097 case ISD::STORE: 9098 case ISD::INTRINSIC_W_CHAIN: 9099 case ISD::INTRINSIC_VOID: 9100 return 2; 9101 default: 9102 return 1; 9103 } 9104 } 9105 9106 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 9107 DAGCombinerInfo &DCI) const { 9108 SelectionDAG &DAG = DCI.DAG; 9109 SDLoc SL(N); 9110 9111 unsigned PtrIdx = getBasePtrIndex(N); 9112 SDValue Ptr = N->getOperand(PtrIdx); 9113 9114 // TODO: We could also do this for multiplies. 9115 if (Ptr.getOpcode() == ISD::SHL) { 9116 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 9117 N->getMemoryVT(), DCI); 9118 if (NewPtr) { 9119 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 9120 9121 NewOps[PtrIdx] = NewPtr; 9122 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 9123 } 9124 } 9125 9126 return SDValue(); 9127 } 9128 9129 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 9130 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 9131 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 9132 (Opc == ISD::XOR && Val == 0); 9133 } 9134 9135 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 9136 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 9137 // integer combine opportunities since most 64-bit operations are decomposed 9138 // this way. TODO: We won't want this for SALU especially if it is an inline 9139 // immediate. 9140 SDValue SITargetLowering::splitBinaryBitConstantOp( 9141 DAGCombinerInfo &DCI, 9142 const SDLoc &SL, 9143 unsigned Opc, SDValue LHS, 9144 const ConstantSDNode *CRHS) const { 9145 uint64_t Val = CRHS->getZExtValue(); 9146 uint32_t ValLo = Lo_32(Val); 9147 uint32_t ValHi = Hi_32(Val); 9148 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9149 9150 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 9151 bitOpWithConstantIsReducible(Opc, ValHi)) || 9152 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 9153 // If we need to materialize a 64-bit immediate, it will be split up later 9154 // anyway. Avoid creating the harder to understand 64-bit immediate 9155 // materialization. 9156 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 9157 } 9158 9159 return SDValue(); 9160 } 9161 9162 // Returns true if argument is a boolean value which is not serialized into 9163 // memory or argument and does not require v_cndmask_b32 to be deserialized. 9164 static bool isBoolSGPR(SDValue V) { 9165 if (V.getValueType() != MVT::i1) 9166 return false; 9167 switch (V.getOpcode()) { 9168 default: 9169 break; 9170 case ISD::SETCC: 9171 case AMDGPUISD::FP_CLASS: 9172 return true; 9173 case ISD::AND: 9174 case ISD::OR: 9175 case ISD::XOR: 9176 return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1)); 9177 } 9178 return false; 9179 } 9180 9181 // If a constant has all zeroes or all ones within each byte return it. 9182 // Otherwise return 0. 9183 static uint32_t getConstantPermuteMask(uint32_t C) { 9184 // 0xff for any zero byte in the mask 9185 uint32_t ZeroByteMask = 0; 9186 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 9187 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 9188 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 9189 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 9190 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 9191 if ((NonZeroByteMask & C) != NonZeroByteMask) 9192 return 0; // Partial bytes selected. 9193 return C; 9194 } 9195 9196 // Check if a node selects whole bytes from its operand 0 starting at a byte 9197 // boundary while masking the rest. Returns select mask as in the v_perm_b32 9198 // or -1 if not succeeded. 9199 // Note byte select encoding: 9200 // value 0-3 selects corresponding source byte; 9201 // value 0xc selects zero; 9202 // value 0xff selects 0xff. 9203 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 9204 assert(V.getValueSizeInBits() == 32); 9205 9206 if (V.getNumOperands() != 2) 9207 return ~0; 9208 9209 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 9210 if (!N1) 9211 return ~0; 9212 9213 uint32_t C = N1->getZExtValue(); 9214 9215 switch (V.getOpcode()) { 9216 default: 9217 break; 9218 case ISD::AND: 9219 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9220 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 9221 } 9222 break; 9223 9224 case ISD::OR: 9225 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9226 return (0x03020100 & ~ConstMask) | ConstMask; 9227 } 9228 break; 9229 9230 case ISD::SHL: 9231 if (C % 8) 9232 return ~0; 9233 9234 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 9235 9236 case ISD::SRL: 9237 if (C % 8) 9238 return ~0; 9239 9240 return uint32_t(0x0c0c0c0c03020100ull >> C); 9241 } 9242 9243 return ~0; 9244 } 9245 9246 SDValue SITargetLowering::performAndCombine(SDNode *N, 9247 DAGCombinerInfo &DCI) const { 9248 if (DCI.isBeforeLegalize()) 9249 return SDValue(); 9250 9251 SelectionDAG &DAG = DCI.DAG; 9252 EVT VT = N->getValueType(0); 9253 SDValue LHS = N->getOperand(0); 9254 SDValue RHS = N->getOperand(1); 9255 9256 9257 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9258 if (VT == MVT::i64 && CRHS) { 9259 if (SDValue Split 9260 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 9261 return Split; 9262 } 9263 9264 if (CRHS && VT == MVT::i32) { 9265 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 9266 // nb = number of trailing zeroes in mask 9267 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 9268 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 9269 uint64_t Mask = CRHS->getZExtValue(); 9270 unsigned Bits = countPopulation(Mask); 9271 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 9272 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 9273 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 9274 unsigned Shift = CShift->getZExtValue(); 9275 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 9276 unsigned Offset = NB + Shift; 9277 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 9278 SDLoc SL(N); 9279 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 9280 LHS->getOperand(0), 9281 DAG.getConstant(Offset, SL, MVT::i32), 9282 DAG.getConstant(Bits, SL, MVT::i32)); 9283 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9284 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 9285 DAG.getValueType(NarrowVT)); 9286 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 9287 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 9288 return Shl; 9289 } 9290 } 9291 } 9292 9293 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9294 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 9295 isa<ConstantSDNode>(LHS.getOperand(2))) { 9296 uint32_t Sel = getConstantPermuteMask(Mask); 9297 if (!Sel) 9298 return SDValue(); 9299 9300 // Select 0xc for all zero bytes 9301 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 9302 SDLoc DL(N); 9303 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9304 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9305 } 9306 } 9307 9308 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 9309 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 9310 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 9311 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9312 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 9313 9314 SDValue X = LHS.getOperand(0); 9315 SDValue Y = RHS.getOperand(0); 9316 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 9317 return SDValue(); 9318 9319 if (LCC == ISD::SETO) { 9320 if (X != LHS.getOperand(1)) 9321 return SDValue(); 9322 9323 if (RCC == ISD::SETUNE) { 9324 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 9325 if (!C1 || !C1->isInfinity() || C1->isNegative()) 9326 return SDValue(); 9327 9328 const uint32_t Mask = SIInstrFlags::N_NORMAL | 9329 SIInstrFlags::N_SUBNORMAL | 9330 SIInstrFlags::N_ZERO | 9331 SIInstrFlags::P_ZERO | 9332 SIInstrFlags::P_SUBNORMAL | 9333 SIInstrFlags::P_NORMAL; 9334 9335 static_assert(((~(SIInstrFlags::S_NAN | 9336 SIInstrFlags::Q_NAN | 9337 SIInstrFlags::N_INFINITY | 9338 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 9339 "mask not equal"); 9340 9341 SDLoc DL(N); 9342 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9343 X, DAG.getConstant(Mask, DL, MVT::i32)); 9344 } 9345 } 9346 } 9347 9348 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 9349 std::swap(LHS, RHS); 9350 9351 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 9352 RHS.hasOneUse()) { 9353 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9354 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 9355 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 9356 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9357 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 9358 (RHS.getOperand(0) == LHS.getOperand(0) && 9359 LHS.getOperand(0) == LHS.getOperand(1))) { 9360 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 9361 unsigned NewMask = LCC == ISD::SETO ? 9362 Mask->getZExtValue() & ~OrdMask : 9363 Mask->getZExtValue() & OrdMask; 9364 9365 SDLoc DL(N); 9366 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 9367 DAG.getConstant(NewMask, DL, MVT::i32)); 9368 } 9369 } 9370 9371 if (VT == MVT::i32 && 9372 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 9373 // and x, (sext cc from i1) => select cc, x, 0 9374 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 9375 std::swap(LHS, RHS); 9376 if (isBoolSGPR(RHS.getOperand(0))) 9377 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 9378 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 9379 } 9380 9381 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9382 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9383 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9384 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9385 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9386 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9387 if (LHSMask != ~0u && RHSMask != ~0u) { 9388 // Canonicalize the expression in an attempt to have fewer unique masks 9389 // and therefore fewer registers used to hold the masks. 9390 if (LHSMask > RHSMask) { 9391 std::swap(LHSMask, RHSMask); 9392 std::swap(LHS, RHS); 9393 } 9394 9395 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9396 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9397 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9398 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9399 9400 // Check of we need to combine values from two sources within a byte. 9401 if (!(LHSUsedLanes & RHSUsedLanes) && 9402 // If we select high and lower word keep it for SDWA. 9403 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9404 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9405 // Each byte in each mask is either selector mask 0-3, or has higher 9406 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 9407 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 9408 // mask which is not 0xff wins. By anding both masks we have a correct 9409 // result except that 0x0c shall be corrected to give 0x0c only. 9410 uint32_t Mask = LHSMask & RHSMask; 9411 for (unsigned I = 0; I < 32; I += 8) { 9412 uint32_t ByteSel = 0xff << I; 9413 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 9414 Mask &= (0x0c << I) & 0xffffffff; 9415 } 9416 9417 // Add 4 to each active LHS lane. It will not affect any existing 0xff 9418 // or 0x0c. 9419 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 9420 SDLoc DL(N); 9421 9422 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9423 LHS.getOperand(0), RHS.getOperand(0), 9424 DAG.getConstant(Sel, DL, MVT::i32)); 9425 } 9426 } 9427 } 9428 9429 return SDValue(); 9430 } 9431 9432 SDValue SITargetLowering::performOrCombine(SDNode *N, 9433 DAGCombinerInfo &DCI) const { 9434 SelectionDAG &DAG = DCI.DAG; 9435 SDValue LHS = N->getOperand(0); 9436 SDValue RHS = N->getOperand(1); 9437 9438 EVT VT = N->getValueType(0); 9439 if (VT == MVT::i1) { 9440 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 9441 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 9442 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 9443 SDValue Src = LHS.getOperand(0); 9444 if (Src != RHS.getOperand(0)) 9445 return SDValue(); 9446 9447 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9448 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9449 if (!CLHS || !CRHS) 9450 return SDValue(); 9451 9452 // Only 10 bits are used. 9453 static const uint32_t MaxMask = 0x3ff; 9454 9455 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 9456 SDLoc DL(N); 9457 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9458 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 9459 } 9460 9461 return SDValue(); 9462 } 9463 9464 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9465 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 9466 LHS.getOpcode() == AMDGPUISD::PERM && 9467 isa<ConstantSDNode>(LHS.getOperand(2))) { 9468 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 9469 if (!Sel) 9470 return SDValue(); 9471 9472 Sel |= LHS.getConstantOperandVal(2); 9473 SDLoc DL(N); 9474 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9475 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9476 } 9477 9478 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9479 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9480 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9481 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9482 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9483 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9484 if (LHSMask != ~0u && RHSMask != ~0u) { 9485 // Canonicalize the expression in an attempt to have fewer unique masks 9486 // and therefore fewer registers used to hold the masks. 9487 if (LHSMask > RHSMask) { 9488 std::swap(LHSMask, RHSMask); 9489 std::swap(LHS, RHS); 9490 } 9491 9492 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9493 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9494 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9495 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9496 9497 // Check of we need to combine values from two sources within a byte. 9498 if (!(LHSUsedLanes & RHSUsedLanes) && 9499 // If we select high and lower word keep it for SDWA. 9500 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9501 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9502 // Kill zero bytes selected by other mask. Zero value is 0xc. 9503 LHSMask &= ~RHSUsedLanes; 9504 RHSMask &= ~LHSUsedLanes; 9505 // Add 4 to each active LHS lane 9506 LHSMask |= LHSUsedLanes & 0x04040404; 9507 // Combine masks 9508 uint32_t Sel = LHSMask | RHSMask; 9509 SDLoc DL(N); 9510 9511 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9512 LHS.getOperand(0), RHS.getOperand(0), 9513 DAG.getConstant(Sel, DL, MVT::i32)); 9514 } 9515 } 9516 } 9517 9518 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9519 return SDValue(); 9520 9521 // TODO: This could be a generic combine with a predicate for extracting the 9522 // high half of an integer being free. 9523 9524 // (or i64:x, (zero_extend i32:y)) -> 9525 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9526 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9527 RHS.getOpcode() != ISD::ZERO_EXTEND) 9528 std::swap(LHS, RHS); 9529 9530 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9531 SDValue ExtSrc = RHS.getOperand(0); 9532 EVT SrcVT = ExtSrc.getValueType(); 9533 if (SrcVT == MVT::i32) { 9534 SDLoc SL(N); 9535 SDValue LowLHS, HiBits; 9536 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9537 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9538 9539 DCI.AddToWorklist(LowOr.getNode()); 9540 DCI.AddToWorklist(HiBits.getNode()); 9541 9542 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9543 LowOr, HiBits); 9544 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9545 } 9546 } 9547 9548 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9549 if (CRHS) { 9550 if (SDValue Split 9551 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, 9552 N->getOperand(0), CRHS)) 9553 return Split; 9554 } 9555 9556 return SDValue(); 9557 } 9558 9559 SDValue SITargetLowering::performXorCombine(SDNode *N, 9560 DAGCombinerInfo &DCI) const { 9561 EVT VT = N->getValueType(0); 9562 if (VT != MVT::i64) 9563 return SDValue(); 9564 9565 SDValue LHS = N->getOperand(0); 9566 SDValue RHS = N->getOperand(1); 9567 9568 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9569 if (CRHS) { 9570 if (SDValue Split 9571 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9572 return Split; 9573 } 9574 9575 return SDValue(); 9576 } 9577 9578 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9579 DAGCombinerInfo &DCI) const { 9580 if (!Subtarget->has16BitInsts() || 9581 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9582 return SDValue(); 9583 9584 EVT VT = N->getValueType(0); 9585 if (VT != MVT::i32) 9586 return SDValue(); 9587 9588 SDValue Src = N->getOperand(0); 9589 if (Src.getValueType() != MVT::i16) 9590 return SDValue(); 9591 9592 return SDValue(); 9593 } 9594 9595 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9596 DAGCombinerInfo &DCI) 9597 const { 9598 SDValue Src = N->getOperand(0); 9599 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9600 9601 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9602 VTSign->getVT() == MVT::i8) || 9603 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9604 VTSign->getVT() == MVT::i16)) && 9605 Src.hasOneUse()) { 9606 auto *M = cast<MemSDNode>(Src); 9607 SDValue Ops[] = { 9608 Src.getOperand(0), // Chain 9609 Src.getOperand(1), // rsrc 9610 Src.getOperand(2), // vindex 9611 Src.getOperand(3), // voffset 9612 Src.getOperand(4), // soffset 9613 Src.getOperand(5), // offset 9614 Src.getOperand(6), 9615 Src.getOperand(7) 9616 }; 9617 // replace with BUFFER_LOAD_BYTE/SHORT 9618 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9619 Src.getOperand(0).getValueType()); 9620 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9621 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9622 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9623 ResList, 9624 Ops, M->getMemoryVT(), 9625 M->getMemOperand()); 9626 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9627 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9628 } 9629 return SDValue(); 9630 } 9631 9632 SDValue SITargetLowering::performClassCombine(SDNode *N, 9633 DAGCombinerInfo &DCI) const { 9634 SelectionDAG &DAG = DCI.DAG; 9635 SDValue Mask = N->getOperand(1); 9636 9637 // fp_class x, 0 -> false 9638 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9639 if (CMask->isZero()) 9640 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9641 } 9642 9643 if (N->getOperand(0).isUndef()) 9644 return DAG.getUNDEF(MVT::i1); 9645 9646 return SDValue(); 9647 } 9648 9649 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9650 DAGCombinerInfo &DCI) const { 9651 EVT VT = N->getValueType(0); 9652 SDValue N0 = N->getOperand(0); 9653 9654 if (N0.isUndef()) 9655 return N0; 9656 9657 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9658 N0.getOpcode() == ISD::SINT_TO_FP)) { 9659 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9660 N->getFlags()); 9661 } 9662 9663 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9664 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9665 N0.getOperand(0), N->getFlags()); 9666 } 9667 9668 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9669 } 9670 9671 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9672 unsigned MaxDepth) const { 9673 unsigned Opcode = Op.getOpcode(); 9674 if (Opcode == ISD::FCANONICALIZE) 9675 return true; 9676 9677 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9678 auto F = CFP->getValueAPF(); 9679 if (F.isNaN() && F.isSignaling()) 9680 return false; 9681 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9682 } 9683 9684 // If source is a result of another standard FP operation it is already in 9685 // canonical form. 9686 if (MaxDepth == 0) 9687 return false; 9688 9689 switch (Opcode) { 9690 // These will flush denorms if required. 9691 case ISD::FADD: 9692 case ISD::FSUB: 9693 case ISD::FMUL: 9694 case ISD::FCEIL: 9695 case ISD::FFLOOR: 9696 case ISD::FMA: 9697 case ISD::FMAD: 9698 case ISD::FSQRT: 9699 case ISD::FDIV: 9700 case ISD::FREM: 9701 case ISD::FP_ROUND: 9702 case ISD::FP_EXTEND: 9703 case AMDGPUISD::FMUL_LEGACY: 9704 case AMDGPUISD::FMAD_FTZ: 9705 case AMDGPUISD::RCP: 9706 case AMDGPUISD::RSQ: 9707 case AMDGPUISD::RSQ_CLAMP: 9708 case AMDGPUISD::RCP_LEGACY: 9709 case AMDGPUISD::RCP_IFLAG: 9710 case AMDGPUISD::DIV_SCALE: 9711 case AMDGPUISD::DIV_FMAS: 9712 case AMDGPUISD::DIV_FIXUP: 9713 case AMDGPUISD::FRACT: 9714 case AMDGPUISD::LDEXP: 9715 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9716 case AMDGPUISD::CVT_F32_UBYTE0: 9717 case AMDGPUISD::CVT_F32_UBYTE1: 9718 case AMDGPUISD::CVT_F32_UBYTE2: 9719 case AMDGPUISD::CVT_F32_UBYTE3: 9720 return true; 9721 9722 // It can/will be lowered or combined as a bit operation. 9723 // Need to check their input recursively to handle. 9724 case ISD::FNEG: 9725 case ISD::FABS: 9726 case ISD::FCOPYSIGN: 9727 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9728 9729 case ISD::FSIN: 9730 case ISD::FCOS: 9731 case ISD::FSINCOS: 9732 return Op.getValueType().getScalarType() != MVT::f16; 9733 9734 case ISD::FMINNUM: 9735 case ISD::FMAXNUM: 9736 case ISD::FMINNUM_IEEE: 9737 case ISD::FMAXNUM_IEEE: 9738 case AMDGPUISD::CLAMP: 9739 case AMDGPUISD::FMED3: 9740 case AMDGPUISD::FMAX3: 9741 case AMDGPUISD::FMIN3: { 9742 // FIXME: Shouldn't treat the generic operations different based these. 9743 // However, we aren't really required to flush the result from 9744 // minnum/maxnum.. 9745 9746 // snans will be quieted, so we only need to worry about denormals. 9747 if (Subtarget->supportsMinMaxDenormModes() || 9748 denormalsEnabledForType(DAG, Op.getValueType())) 9749 return true; 9750 9751 // Flushing may be required. 9752 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9753 // targets need to check their input recursively. 9754 9755 // FIXME: Does this apply with clamp? It's implemented with max. 9756 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9757 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9758 return false; 9759 } 9760 9761 return true; 9762 } 9763 case ISD::SELECT: { 9764 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9765 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9766 } 9767 case ISD::BUILD_VECTOR: { 9768 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9769 SDValue SrcOp = Op.getOperand(i); 9770 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9771 return false; 9772 } 9773 9774 return true; 9775 } 9776 case ISD::EXTRACT_VECTOR_ELT: 9777 case ISD::EXTRACT_SUBVECTOR: { 9778 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9779 } 9780 case ISD::INSERT_VECTOR_ELT: { 9781 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9782 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9783 } 9784 case ISD::UNDEF: 9785 // Could be anything. 9786 return false; 9787 9788 case ISD::BITCAST: 9789 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9790 case ISD::TRUNCATE: { 9791 // Hack round the mess we make when legalizing extract_vector_elt 9792 if (Op.getValueType() == MVT::i16) { 9793 SDValue TruncSrc = Op.getOperand(0); 9794 if (TruncSrc.getValueType() == MVT::i32 && 9795 TruncSrc.getOpcode() == ISD::BITCAST && 9796 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9797 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9798 } 9799 } 9800 return false; 9801 } 9802 case ISD::INTRINSIC_WO_CHAIN: { 9803 unsigned IntrinsicID 9804 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9805 // TODO: Handle more intrinsics 9806 switch (IntrinsicID) { 9807 case Intrinsic::amdgcn_cvt_pkrtz: 9808 case Intrinsic::amdgcn_cubeid: 9809 case Intrinsic::amdgcn_frexp_mant: 9810 case Intrinsic::amdgcn_fdot2: 9811 case Intrinsic::amdgcn_rcp: 9812 case Intrinsic::amdgcn_rsq: 9813 case Intrinsic::amdgcn_rsq_clamp: 9814 case Intrinsic::amdgcn_rcp_legacy: 9815 case Intrinsic::amdgcn_rsq_legacy: 9816 case Intrinsic::amdgcn_trig_preop: 9817 return true; 9818 default: 9819 break; 9820 } 9821 9822 LLVM_FALLTHROUGH; 9823 } 9824 default: 9825 return denormalsEnabledForType(DAG, Op.getValueType()) && 9826 DAG.isKnownNeverSNaN(Op); 9827 } 9828 9829 llvm_unreachable("invalid operation"); 9830 } 9831 9832 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF, 9833 unsigned MaxDepth) const { 9834 MachineRegisterInfo &MRI = MF.getRegInfo(); 9835 MachineInstr *MI = MRI.getVRegDef(Reg); 9836 unsigned Opcode = MI->getOpcode(); 9837 9838 if (Opcode == AMDGPU::G_FCANONICALIZE) 9839 return true; 9840 9841 Optional<FPValueAndVReg> FCR; 9842 // Constant splat (can be padded with undef) or scalar constant. 9843 if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) { 9844 if (FCR->Value.isSignaling()) 9845 return false; 9846 return !FCR->Value.isDenormal() || 9847 denormalsEnabledForType(MRI.getType(FCR->VReg), MF); 9848 } 9849 9850 if (MaxDepth == 0) 9851 return false; 9852 9853 switch (Opcode) { 9854 case AMDGPU::G_FMINNUM_IEEE: 9855 case AMDGPU::G_FMAXNUM_IEEE: { 9856 if (Subtarget->supportsMinMaxDenormModes() || 9857 denormalsEnabledForType(MRI.getType(Reg), MF)) 9858 return true; 9859 for (const MachineOperand &MO : llvm::drop_begin(MI->operands())) 9860 if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1)) 9861 return false; 9862 return true; 9863 } 9864 default: 9865 return denormalsEnabledForType(MRI.getType(Reg), MF) && 9866 isKnownNeverSNaN(Reg, MRI); 9867 } 9868 9869 llvm_unreachable("invalid operation"); 9870 } 9871 9872 // Constant fold canonicalize. 9873 SDValue SITargetLowering::getCanonicalConstantFP( 9874 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9875 // Flush denormals to 0 if not enabled. 9876 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9877 return DAG.getConstantFP(0.0, SL, VT); 9878 9879 if (C.isNaN()) { 9880 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9881 if (C.isSignaling()) { 9882 // Quiet a signaling NaN. 9883 // FIXME: Is this supposed to preserve payload bits? 9884 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9885 } 9886 9887 // Make sure it is the canonical NaN bitpattern. 9888 // 9889 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9890 // immediate? 9891 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9892 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9893 } 9894 9895 // Already canonical. 9896 return DAG.getConstantFP(C, SL, VT); 9897 } 9898 9899 static bool vectorEltWillFoldAway(SDValue Op) { 9900 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9901 } 9902 9903 SDValue SITargetLowering::performFCanonicalizeCombine( 9904 SDNode *N, 9905 DAGCombinerInfo &DCI) const { 9906 SelectionDAG &DAG = DCI.DAG; 9907 SDValue N0 = N->getOperand(0); 9908 EVT VT = N->getValueType(0); 9909 9910 // fcanonicalize undef -> qnan 9911 if (N0.isUndef()) { 9912 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9913 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9914 } 9915 9916 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9917 EVT VT = N->getValueType(0); 9918 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9919 } 9920 9921 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9922 // (fcanonicalize k) 9923 // 9924 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9925 9926 // TODO: This could be better with wider vectors that will be split to v2f16, 9927 // and to consider uses since there aren't that many packed operations. 9928 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9929 isTypeLegal(MVT::v2f16)) { 9930 SDLoc SL(N); 9931 SDValue NewElts[2]; 9932 SDValue Lo = N0.getOperand(0); 9933 SDValue Hi = N0.getOperand(1); 9934 EVT EltVT = Lo.getValueType(); 9935 9936 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9937 for (unsigned I = 0; I != 2; ++I) { 9938 SDValue Op = N0.getOperand(I); 9939 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9940 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9941 CFP->getValueAPF()); 9942 } else if (Op.isUndef()) { 9943 // Handled below based on what the other operand is. 9944 NewElts[I] = Op; 9945 } else { 9946 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9947 } 9948 } 9949 9950 // If one half is undef, and one is constant, perfer a splat vector rather 9951 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9952 // cheaper to use and may be free with a packed operation. 9953 if (NewElts[0].isUndef()) { 9954 if (isa<ConstantFPSDNode>(NewElts[1])) 9955 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9956 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9957 } 9958 9959 if (NewElts[1].isUndef()) { 9960 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9961 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9962 } 9963 9964 return DAG.getBuildVector(VT, SL, NewElts); 9965 } 9966 } 9967 9968 unsigned SrcOpc = N0.getOpcode(); 9969 9970 // If it's free to do so, push canonicalizes further up the source, which may 9971 // find a canonical source. 9972 // 9973 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9974 // sNaNs. 9975 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9976 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9977 if (CRHS && N0.hasOneUse()) { 9978 SDLoc SL(N); 9979 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9980 N0.getOperand(0)); 9981 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9982 DCI.AddToWorklist(Canon0.getNode()); 9983 9984 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9985 } 9986 } 9987 9988 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9989 } 9990 9991 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9992 switch (Opc) { 9993 case ISD::FMAXNUM: 9994 case ISD::FMAXNUM_IEEE: 9995 return AMDGPUISD::FMAX3; 9996 case ISD::SMAX: 9997 return AMDGPUISD::SMAX3; 9998 case ISD::UMAX: 9999 return AMDGPUISD::UMAX3; 10000 case ISD::FMINNUM: 10001 case ISD::FMINNUM_IEEE: 10002 return AMDGPUISD::FMIN3; 10003 case ISD::SMIN: 10004 return AMDGPUISD::SMIN3; 10005 case ISD::UMIN: 10006 return AMDGPUISD::UMIN3; 10007 default: 10008 llvm_unreachable("Not a min/max opcode"); 10009 } 10010 } 10011 10012 SDValue SITargetLowering::performIntMed3ImmCombine( 10013 SelectionDAG &DAG, const SDLoc &SL, 10014 SDValue Op0, SDValue Op1, bool Signed) const { 10015 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 10016 if (!K1) 10017 return SDValue(); 10018 10019 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 10020 if (!K0) 10021 return SDValue(); 10022 10023 if (Signed) { 10024 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 10025 return SDValue(); 10026 } else { 10027 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 10028 return SDValue(); 10029 } 10030 10031 EVT VT = K0->getValueType(0); 10032 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 10033 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 10034 return DAG.getNode(Med3Opc, SL, VT, 10035 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 10036 } 10037 10038 // If there isn't a 16-bit med3 operation, convert to 32-bit. 10039 if (VT == MVT::i16) { 10040 MVT NVT = MVT::i32; 10041 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 10042 10043 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 10044 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 10045 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 10046 10047 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 10048 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 10049 } 10050 10051 return SDValue(); 10052 } 10053 10054 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 10055 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 10056 return C; 10057 10058 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 10059 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 10060 return C; 10061 } 10062 10063 return nullptr; 10064 } 10065 10066 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 10067 const SDLoc &SL, 10068 SDValue Op0, 10069 SDValue Op1) const { 10070 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 10071 if (!K1) 10072 return SDValue(); 10073 10074 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 10075 if (!K0) 10076 return SDValue(); 10077 10078 // Ordered >= (although NaN inputs should have folded away by now). 10079 if (K0->getValueAPF() > K1->getValueAPF()) 10080 return SDValue(); 10081 10082 const MachineFunction &MF = DAG.getMachineFunction(); 10083 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10084 10085 // TODO: Check IEEE bit enabled? 10086 EVT VT = Op0.getValueType(); 10087 if (Info->getMode().DX10Clamp) { 10088 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 10089 // hardware fmed3 behavior converting to a min. 10090 // FIXME: Should this be allowing -0.0? 10091 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 10092 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 10093 } 10094 10095 // med3 for f16 is only available on gfx9+, and not available for v2f16. 10096 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 10097 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 10098 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 10099 // then give the other result, which is different from med3 with a NaN 10100 // input. 10101 SDValue Var = Op0.getOperand(0); 10102 if (!DAG.isKnownNeverSNaN(Var)) 10103 return SDValue(); 10104 10105 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10106 10107 if ((!K0->hasOneUse() || 10108 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 10109 (!K1->hasOneUse() || 10110 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 10111 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 10112 Var, SDValue(K0, 0), SDValue(K1, 0)); 10113 } 10114 } 10115 10116 return SDValue(); 10117 } 10118 10119 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 10120 DAGCombinerInfo &DCI) const { 10121 SelectionDAG &DAG = DCI.DAG; 10122 10123 EVT VT = N->getValueType(0); 10124 unsigned Opc = N->getOpcode(); 10125 SDValue Op0 = N->getOperand(0); 10126 SDValue Op1 = N->getOperand(1); 10127 10128 // Only do this if the inner op has one use since this will just increases 10129 // register pressure for no benefit. 10130 10131 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 10132 !VT.isVector() && 10133 (VT == MVT::i32 || VT == MVT::f32 || 10134 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 10135 // max(max(a, b), c) -> max3(a, b, c) 10136 // min(min(a, b), c) -> min3(a, b, c) 10137 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 10138 SDLoc DL(N); 10139 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10140 DL, 10141 N->getValueType(0), 10142 Op0.getOperand(0), 10143 Op0.getOperand(1), 10144 Op1); 10145 } 10146 10147 // Try commuted. 10148 // max(a, max(b, c)) -> max3(a, b, c) 10149 // min(a, min(b, c)) -> min3(a, b, c) 10150 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 10151 SDLoc DL(N); 10152 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10153 DL, 10154 N->getValueType(0), 10155 Op0, 10156 Op1.getOperand(0), 10157 Op1.getOperand(1)); 10158 } 10159 } 10160 10161 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 10162 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 10163 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 10164 return Med3; 10165 } 10166 10167 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 10168 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 10169 return Med3; 10170 } 10171 10172 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 10173 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 10174 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 10175 (Opc == AMDGPUISD::FMIN_LEGACY && 10176 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 10177 (VT == MVT::f32 || VT == MVT::f64 || 10178 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 10179 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 10180 Op0.hasOneUse()) { 10181 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 10182 return Res; 10183 } 10184 10185 return SDValue(); 10186 } 10187 10188 static bool isClampZeroToOne(SDValue A, SDValue B) { 10189 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 10190 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 10191 // FIXME: Should this be allowing -0.0? 10192 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 10193 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 10194 } 10195 } 10196 10197 return false; 10198 } 10199 10200 // FIXME: Should only worry about snans for version with chain. 10201 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 10202 DAGCombinerInfo &DCI) const { 10203 EVT VT = N->getValueType(0); 10204 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 10205 // NaNs. With a NaN input, the order of the operands may change the result. 10206 10207 SelectionDAG &DAG = DCI.DAG; 10208 SDLoc SL(N); 10209 10210 SDValue Src0 = N->getOperand(0); 10211 SDValue Src1 = N->getOperand(1); 10212 SDValue Src2 = N->getOperand(2); 10213 10214 if (isClampZeroToOne(Src0, Src1)) { 10215 // const_a, const_b, x -> clamp is safe in all cases including signaling 10216 // nans. 10217 // FIXME: Should this be allowing -0.0? 10218 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 10219 } 10220 10221 const MachineFunction &MF = DAG.getMachineFunction(); 10222 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10223 10224 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 10225 // handling no dx10-clamp? 10226 if (Info->getMode().DX10Clamp) { 10227 // If NaNs is clamped to 0, we are free to reorder the inputs. 10228 10229 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10230 std::swap(Src0, Src1); 10231 10232 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 10233 std::swap(Src1, Src2); 10234 10235 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10236 std::swap(Src0, Src1); 10237 10238 if (isClampZeroToOne(Src1, Src2)) 10239 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 10240 } 10241 10242 return SDValue(); 10243 } 10244 10245 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 10246 DAGCombinerInfo &DCI) const { 10247 SDValue Src0 = N->getOperand(0); 10248 SDValue Src1 = N->getOperand(1); 10249 if (Src0.isUndef() && Src1.isUndef()) 10250 return DCI.DAG.getUNDEF(N->getValueType(0)); 10251 return SDValue(); 10252 } 10253 10254 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 10255 // expanded into a set of cmp/select instructions. 10256 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 10257 unsigned NumElem, 10258 bool IsDivergentIdx) { 10259 if (UseDivergentRegisterIndexing) 10260 return false; 10261 10262 unsigned VecSize = EltSize * NumElem; 10263 10264 // Sub-dword vectors of size 2 dword or less have better implementation. 10265 if (VecSize <= 64 && EltSize < 32) 10266 return false; 10267 10268 // Always expand the rest of sub-dword instructions, otherwise it will be 10269 // lowered via memory. 10270 if (EltSize < 32) 10271 return true; 10272 10273 // Always do this if var-idx is divergent, otherwise it will become a loop. 10274 if (IsDivergentIdx) 10275 return true; 10276 10277 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 10278 unsigned NumInsts = NumElem /* Number of compares */ + 10279 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 10280 return NumInsts <= 16; 10281 } 10282 10283 static bool shouldExpandVectorDynExt(SDNode *N) { 10284 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 10285 if (isa<ConstantSDNode>(Idx)) 10286 return false; 10287 10288 SDValue Vec = N->getOperand(0); 10289 EVT VecVT = Vec.getValueType(); 10290 EVT EltVT = VecVT.getVectorElementType(); 10291 unsigned EltSize = EltVT.getSizeInBits(); 10292 unsigned NumElem = VecVT.getVectorNumElements(); 10293 10294 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 10295 Idx->isDivergent()); 10296 } 10297 10298 SDValue SITargetLowering::performExtractVectorEltCombine( 10299 SDNode *N, DAGCombinerInfo &DCI) const { 10300 SDValue Vec = N->getOperand(0); 10301 SelectionDAG &DAG = DCI.DAG; 10302 10303 EVT VecVT = Vec.getValueType(); 10304 EVT EltVT = VecVT.getVectorElementType(); 10305 10306 if ((Vec.getOpcode() == ISD::FNEG || 10307 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 10308 SDLoc SL(N); 10309 EVT EltVT = N->getValueType(0); 10310 SDValue Idx = N->getOperand(1); 10311 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10312 Vec.getOperand(0), Idx); 10313 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 10314 } 10315 10316 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 10317 // => 10318 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 10319 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 10320 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 10321 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 10322 SDLoc SL(N); 10323 EVT EltVT = N->getValueType(0); 10324 SDValue Idx = N->getOperand(1); 10325 unsigned Opc = Vec.getOpcode(); 10326 10327 switch(Opc) { 10328 default: 10329 break; 10330 // TODO: Support other binary operations. 10331 case ISD::FADD: 10332 case ISD::FSUB: 10333 case ISD::FMUL: 10334 case ISD::ADD: 10335 case ISD::UMIN: 10336 case ISD::UMAX: 10337 case ISD::SMIN: 10338 case ISD::SMAX: 10339 case ISD::FMAXNUM: 10340 case ISD::FMINNUM: 10341 case ISD::FMAXNUM_IEEE: 10342 case ISD::FMINNUM_IEEE: { 10343 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10344 Vec.getOperand(0), Idx); 10345 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10346 Vec.getOperand(1), Idx); 10347 10348 DCI.AddToWorklist(Elt0.getNode()); 10349 DCI.AddToWorklist(Elt1.getNode()); 10350 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 10351 } 10352 } 10353 } 10354 10355 unsigned VecSize = VecVT.getSizeInBits(); 10356 unsigned EltSize = EltVT.getSizeInBits(); 10357 10358 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 10359 if (::shouldExpandVectorDynExt(N)) { 10360 SDLoc SL(N); 10361 SDValue Idx = N->getOperand(1); 10362 SDValue V; 10363 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10364 SDValue IC = DAG.getVectorIdxConstant(I, SL); 10365 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10366 if (I == 0) 10367 V = Elt; 10368 else 10369 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 10370 } 10371 return V; 10372 } 10373 10374 if (!DCI.isBeforeLegalize()) 10375 return SDValue(); 10376 10377 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 10378 // elements. This exposes more load reduction opportunities by replacing 10379 // multiple small extract_vector_elements with a single 32-bit extract. 10380 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10381 if (isa<MemSDNode>(Vec) && 10382 EltSize <= 16 && 10383 EltVT.isByteSized() && 10384 VecSize > 32 && 10385 VecSize % 32 == 0 && 10386 Idx) { 10387 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 10388 10389 unsigned BitIndex = Idx->getZExtValue() * EltSize; 10390 unsigned EltIdx = BitIndex / 32; 10391 unsigned LeftoverBitIdx = BitIndex % 32; 10392 SDLoc SL(N); 10393 10394 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 10395 DCI.AddToWorklist(Cast.getNode()); 10396 10397 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 10398 DAG.getConstant(EltIdx, SL, MVT::i32)); 10399 DCI.AddToWorklist(Elt.getNode()); 10400 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 10401 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 10402 DCI.AddToWorklist(Srl.getNode()); 10403 10404 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 10405 DCI.AddToWorklist(Trunc.getNode()); 10406 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 10407 } 10408 10409 return SDValue(); 10410 } 10411 10412 SDValue 10413 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 10414 DAGCombinerInfo &DCI) const { 10415 SDValue Vec = N->getOperand(0); 10416 SDValue Idx = N->getOperand(2); 10417 EVT VecVT = Vec.getValueType(); 10418 EVT EltVT = VecVT.getVectorElementType(); 10419 10420 // INSERT_VECTOR_ELT (<n x e>, var-idx) 10421 // => BUILD_VECTOR n x select (e, const-idx) 10422 if (!::shouldExpandVectorDynExt(N)) 10423 return SDValue(); 10424 10425 SelectionDAG &DAG = DCI.DAG; 10426 SDLoc SL(N); 10427 SDValue Ins = N->getOperand(1); 10428 EVT IdxVT = Idx.getValueType(); 10429 10430 SmallVector<SDValue, 16> Ops; 10431 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10432 SDValue IC = DAG.getConstant(I, SL, IdxVT); 10433 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10434 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 10435 Ops.push_back(V); 10436 } 10437 10438 return DAG.getBuildVector(VecVT, SL, Ops); 10439 } 10440 10441 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 10442 const SDNode *N0, 10443 const SDNode *N1) const { 10444 EVT VT = N0->getValueType(0); 10445 10446 // Only do this if we are not trying to support denormals. v_mad_f32 does not 10447 // support denormals ever. 10448 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 10449 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 10450 getSubtarget()->hasMadF16())) && 10451 isOperationLegal(ISD::FMAD, VT)) 10452 return ISD::FMAD; 10453 10454 const TargetOptions &Options = DAG.getTarget().Options; 10455 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10456 (N0->getFlags().hasAllowContract() && 10457 N1->getFlags().hasAllowContract())) && 10458 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10459 return ISD::FMA; 10460 } 10461 10462 return 0; 10463 } 10464 10465 // For a reassociatable opcode perform: 10466 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10467 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10468 SelectionDAG &DAG) const { 10469 EVT VT = N->getValueType(0); 10470 if (VT != MVT::i32 && VT != MVT::i64) 10471 return SDValue(); 10472 10473 unsigned Opc = N->getOpcode(); 10474 SDValue Op0 = N->getOperand(0); 10475 SDValue Op1 = N->getOperand(1); 10476 10477 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10478 return SDValue(); 10479 10480 if (Op0->isDivergent()) 10481 std::swap(Op0, Op1); 10482 10483 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10484 return SDValue(); 10485 10486 SDValue Op2 = Op1.getOperand(1); 10487 Op1 = Op1.getOperand(0); 10488 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10489 return SDValue(); 10490 10491 if (Op1->isDivergent()) 10492 std::swap(Op1, Op2); 10493 10494 // If either operand is constant this will conflict with 10495 // DAGCombiner::ReassociateOps(). 10496 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 10497 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 10498 return SDValue(); 10499 10500 SDLoc SL(N); 10501 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10502 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10503 } 10504 10505 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10506 EVT VT, 10507 SDValue N0, SDValue N1, SDValue N2, 10508 bool Signed) { 10509 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10510 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10511 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10512 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10513 } 10514 10515 SDValue SITargetLowering::performAddCombine(SDNode *N, 10516 DAGCombinerInfo &DCI) const { 10517 SelectionDAG &DAG = DCI.DAG; 10518 EVT VT = N->getValueType(0); 10519 SDLoc SL(N); 10520 SDValue LHS = N->getOperand(0); 10521 SDValue RHS = N->getOperand(1); 10522 10523 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10524 && Subtarget->hasMad64_32() && 10525 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10526 VT.getScalarSizeInBits() <= 64) { 10527 if (LHS.getOpcode() != ISD::MUL) 10528 std::swap(LHS, RHS); 10529 10530 SDValue MulLHS = LHS.getOperand(0); 10531 SDValue MulRHS = LHS.getOperand(1); 10532 SDValue AddRHS = RHS; 10533 10534 // TODO: Maybe restrict if SGPR inputs. 10535 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10536 numBitsUnsigned(MulRHS, DAG) <= 32) { 10537 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10538 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10539 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10540 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10541 } 10542 10543 if (numBitsSigned(MulLHS, DAG) <= 32 && numBitsSigned(MulRHS, DAG) <= 32) { 10544 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10545 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10546 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10547 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10548 } 10549 10550 return SDValue(); 10551 } 10552 10553 if (SDValue V = reassociateScalarOps(N, DAG)) { 10554 return V; 10555 } 10556 10557 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10558 return SDValue(); 10559 10560 // add x, zext (setcc) => addcarry x, 0, setcc 10561 // add x, sext (setcc) => subcarry x, 0, setcc 10562 unsigned Opc = LHS.getOpcode(); 10563 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10564 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10565 std::swap(RHS, LHS); 10566 10567 Opc = RHS.getOpcode(); 10568 switch (Opc) { 10569 default: break; 10570 case ISD::ZERO_EXTEND: 10571 case ISD::SIGN_EXTEND: 10572 case ISD::ANY_EXTEND: { 10573 auto Cond = RHS.getOperand(0); 10574 // If this won't be a real VOPC output, we would still need to insert an 10575 // extra instruction anyway. 10576 if (!isBoolSGPR(Cond)) 10577 break; 10578 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10579 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10580 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10581 return DAG.getNode(Opc, SL, VTList, Args); 10582 } 10583 case ISD::ADDCARRY: { 10584 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10585 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10586 if (!C || C->getZExtValue() != 0) break; 10587 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10588 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10589 } 10590 } 10591 return SDValue(); 10592 } 10593 10594 SDValue SITargetLowering::performSubCombine(SDNode *N, 10595 DAGCombinerInfo &DCI) const { 10596 SelectionDAG &DAG = DCI.DAG; 10597 EVT VT = N->getValueType(0); 10598 10599 if (VT != MVT::i32) 10600 return SDValue(); 10601 10602 SDLoc SL(N); 10603 SDValue LHS = N->getOperand(0); 10604 SDValue RHS = N->getOperand(1); 10605 10606 // sub x, zext (setcc) => subcarry x, 0, setcc 10607 // sub x, sext (setcc) => addcarry x, 0, setcc 10608 unsigned Opc = RHS.getOpcode(); 10609 switch (Opc) { 10610 default: break; 10611 case ISD::ZERO_EXTEND: 10612 case ISD::SIGN_EXTEND: 10613 case ISD::ANY_EXTEND: { 10614 auto Cond = RHS.getOperand(0); 10615 // If this won't be a real VOPC output, we would still need to insert an 10616 // extra instruction anyway. 10617 if (!isBoolSGPR(Cond)) 10618 break; 10619 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10620 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10621 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10622 return DAG.getNode(Opc, SL, VTList, Args); 10623 } 10624 } 10625 10626 if (LHS.getOpcode() == ISD::SUBCARRY) { 10627 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10628 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10629 if (!C || !C->isZero()) 10630 return SDValue(); 10631 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10632 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10633 } 10634 return SDValue(); 10635 } 10636 10637 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10638 DAGCombinerInfo &DCI) const { 10639 10640 if (N->getValueType(0) != MVT::i32) 10641 return SDValue(); 10642 10643 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10644 if (!C || C->getZExtValue() != 0) 10645 return SDValue(); 10646 10647 SelectionDAG &DAG = DCI.DAG; 10648 SDValue LHS = N->getOperand(0); 10649 10650 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10651 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10652 unsigned LHSOpc = LHS.getOpcode(); 10653 unsigned Opc = N->getOpcode(); 10654 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10655 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10656 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10657 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10658 } 10659 return SDValue(); 10660 } 10661 10662 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10663 DAGCombinerInfo &DCI) const { 10664 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10665 return SDValue(); 10666 10667 SelectionDAG &DAG = DCI.DAG; 10668 EVT VT = N->getValueType(0); 10669 10670 SDLoc SL(N); 10671 SDValue LHS = N->getOperand(0); 10672 SDValue RHS = N->getOperand(1); 10673 10674 // These should really be instruction patterns, but writing patterns with 10675 // source modiifiers is a pain. 10676 10677 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10678 if (LHS.getOpcode() == ISD::FADD) { 10679 SDValue A = LHS.getOperand(0); 10680 if (A == LHS.getOperand(1)) { 10681 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10682 if (FusedOp != 0) { 10683 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10684 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10685 } 10686 } 10687 } 10688 10689 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10690 if (RHS.getOpcode() == ISD::FADD) { 10691 SDValue A = RHS.getOperand(0); 10692 if (A == RHS.getOperand(1)) { 10693 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10694 if (FusedOp != 0) { 10695 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10696 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10697 } 10698 } 10699 } 10700 10701 return SDValue(); 10702 } 10703 10704 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10705 DAGCombinerInfo &DCI) const { 10706 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10707 return SDValue(); 10708 10709 SelectionDAG &DAG = DCI.DAG; 10710 SDLoc SL(N); 10711 EVT VT = N->getValueType(0); 10712 assert(!VT.isVector()); 10713 10714 // Try to get the fneg to fold into the source modifier. This undoes generic 10715 // DAG combines and folds them into the mad. 10716 // 10717 // Only do this if we are not trying to support denormals. v_mad_f32 does 10718 // not support denormals ever. 10719 SDValue LHS = N->getOperand(0); 10720 SDValue RHS = N->getOperand(1); 10721 if (LHS.getOpcode() == ISD::FADD) { 10722 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10723 SDValue A = LHS.getOperand(0); 10724 if (A == LHS.getOperand(1)) { 10725 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10726 if (FusedOp != 0){ 10727 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10728 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10729 10730 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10731 } 10732 } 10733 } 10734 10735 if (RHS.getOpcode() == ISD::FADD) { 10736 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10737 10738 SDValue A = RHS.getOperand(0); 10739 if (A == RHS.getOperand(1)) { 10740 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10741 if (FusedOp != 0){ 10742 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10743 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10744 } 10745 } 10746 } 10747 10748 return SDValue(); 10749 } 10750 10751 SDValue SITargetLowering::performFMACombine(SDNode *N, 10752 DAGCombinerInfo &DCI) const { 10753 SelectionDAG &DAG = DCI.DAG; 10754 EVT VT = N->getValueType(0); 10755 SDLoc SL(N); 10756 10757 if (!Subtarget->hasDot7Insts() || VT != MVT::f32) 10758 return SDValue(); 10759 10760 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10761 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10762 SDValue Op1 = N->getOperand(0); 10763 SDValue Op2 = N->getOperand(1); 10764 SDValue FMA = N->getOperand(2); 10765 10766 if (FMA.getOpcode() != ISD::FMA || 10767 Op1.getOpcode() != ISD::FP_EXTEND || 10768 Op2.getOpcode() != ISD::FP_EXTEND) 10769 return SDValue(); 10770 10771 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10772 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10773 // is sufficient to allow generaing fdot2. 10774 const TargetOptions &Options = DAG.getTarget().Options; 10775 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10776 (N->getFlags().hasAllowContract() && 10777 FMA->getFlags().hasAllowContract())) { 10778 Op1 = Op1.getOperand(0); 10779 Op2 = Op2.getOperand(0); 10780 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10781 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10782 return SDValue(); 10783 10784 SDValue Vec1 = Op1.getOperand(0); 10785 SDValue Idx1 = Op1.getOperand(1); 10786 SDValue Vec2 = Op2.getOperand(0); 10787 10788 SDValue FMAOp1 = FMA.getOperand(0); 10789 SDValue FMAOp2 = FMA.getOperand(1); 10790 SDValue FMAAcc = FMA.getOperand(2); 10791 10792 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10793 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10794 return SDValue(); 10795 10796 FMAOp1 = FMAOp1.getOperand(0); 10797 FMAOp2 = FMAOp2.getOperand(0); 10798 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10799 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10800 return SDValue(); 10801 10802 SDValue Vec3 = FMAOp1.getOperand(0); 10803 SDValue Vec4 = FMAOp2.getOperand(0); 10804 SDValue Idx2 = FMAOp1.getOperand(1); 10805 10806 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10807 // Idx1 and Idx2 cannot be the same. 10808 Idx1 == Idx2) 10809 return SDValue(); 10810 10811 if (Vec1 == Vec2 || Vec3 == Vec4) 10812 return SDValue(); 10813 10814 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10815 return SDValue(); 10816 10817 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10818 (Vec1 == Vec4 && Vec2 == Vec3)) { 10819 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10820 DAG.getTargetConstant(0, SL, MVT::i1)); 10821 } 10822 } 10823 return SDValue(); 10824 } 10825 10826 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10827 DAGCombinerInfo &DCI) const { 10828 SelectionDAG &DAG = DCI.DAG; 10829 SDLoc SL(N); 10830 10831 SDValue LHS = N->getOperand(0); 10832 SDValue RHS = N->getOperand(1); 10833 EVT VT = LHS.getValueType(); 10834 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10835 10836 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10837 if (!CRHS) { 10838 CRHS = dyn_cast<ConstantSDNode>(LHS); 10839 if (CRHS) { 10840 std::swap(LHS, RHS); 10841 CC = getSetCCSwappedOperands(CC); 10842 } 10843 } 10844 10845 if (CRHS) { 10846 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10847 isBoolSGPR(LHS.getOperand(0))) { 10848 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10849 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10850 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10851 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10852 if ((CRHS->isAllOnes() && 10853 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10854 (CRHS->isZero() && 10855 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10856 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10857 DAG.getConstant(-1, SL, MVT::i1)); 10858 if ((CRHS->isAllOnes() && 10859 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10860 (CRHS->isZero() && 10861 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10862 return LHS.getOperand(0); 10863 } 10864 10865 const APInt &CRHSVal = CRHS->getAPIntValue(); 10866 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10867 LHS.getOpcode() == ISD::SELECT && 10868 isa<ConstantSDNode>(LHS.getOperand(1)) && 10869 isa<ConstantSDNode>(LHS.getOperand(2)) && 10870 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10871 isBoolSGPR(LHS.getOperand(0))) { 10872 // Given CT != FT: 10873 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10874 // setcc (select cc, CT, CF), CF, ne => cc 10875 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10876 // setcc (select cc, CT, CF), CT, eq => cc 10877 const APInt &CT = LHS.getConstantOperandAPInt(1); 10878 const APInt &CF = LHS.getConstantOperandAPInt(2); 10879 10880 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10881 (CT == CRHSVal && CC == ISD::SETNE)) 10882 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10883 DAG.getConstant(-1, SL, MVT::i1)); 10884 if ((CF == CRHSVal && CC == ISD::SETNE) || 10885 (CT == CRHSVal && CC == ISD::SETEQ)) 10886 return LHS.getOperand(0); 10887 } 10888 } 10889 10890 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10891 VT != MVT::f16)) 10892 return SDValue(); 10893 10894 // Match isinf/isfinite pattern 10895 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10896 // (fcmp one (fabs x), inf) -> (fp_class x, 10897 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10898 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10899 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10900 if (!CRHS) 10901 return SDValue(); 10902 10903 const APFloat &APF = CRHS->getValueAPF(); 10904 if (APF.isInfinity() && !APF.isNegative()) { 10905 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10906 SIInstrFlags::N_INFINITY; 10907 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10908 SIInstrFlags::P_ZERO | 10909 SIInstrFlags::N_NORMAL | 10910 SIInstrFlags::P_NORMAL | 10911 SIInstrFlags::N_SUBNORMAL | 10912 SIInstrFlags::P_SUBNORMAL; 10913 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10914 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10915 DAG.getConstant(Mask, SL, MVT::i32)); 10916 } 10917 } 10918 10919 return SDValue(); 10920 } 10921 10922 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10923 DAGCombinerInfo &DCI) const { 10924 SelectionDAG &DAG = DCI.DAG; 10925 SDLoc SL(N); 10926 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10927 10928 SDValue Src = N->getOperand(0); 10929 SDValue Shift = N->getOperand(0); 10930 10931 // TODO: Extend type shouldn't matter (assuming legal types). 10932 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10933 Shift = Shift.getOperand(0); 10934 10935 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10936 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10937 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10938 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10939 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10940 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10941 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10942 SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0), 10943 SDLoc(Shift.getOperand(0)), MVT::i32); 10944 10945 unsigned ShiftOffset = 8 * Offset; 10946 if (Shift.getOpcode() == ISD::SHL) 10947 ShiftOffset -= C->getZExtValue(); 10948 else 10949 ShiftOffset += C->getZExtValue(); 10950 10951 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10952 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10953 MVT::f32, Shifted); 10954 } 10955 } 10956 } 10957 10958 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10959 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10960 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10961 // We simplified Src. If this node is not dead, visit it again so it is 10962 // folded properly. 10963 if (N->getOpcode() != ISD::DELETED_NODE) 10964 DCI.AddToWorklist(N); 10965 return SDValue(N, 0); 10966 } 10967 10968 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10969 if (SDValue DemandedSrc = 10970 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10971 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10972 10973 return SDValue(); 10974 } 10975 10976 SDValue SITargetLowering::performClampCombine(SDNode *N, 10977 DAGCombinerInfo &DCI) const { 10978 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10979 if (!CSrc) 10980 return SDValue(); 10981 10982 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10983 const APFloat &F = CSrc->getValueAPF(); 10984 APFloat Zero = APFloat::getZero(F.getSemantics()); 10985 if (F < Zero || 10986 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10987 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10988 } 10989 10990 APFloat One(F.getSemantics(), "1.0"); 10991 if (F > One) 10992 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10993 10994 return SDValue(CSrc, 0); 10995 } 10996 10997 10998 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10999 DAGCombinerInfo &DCI) const { 11000 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 11001 return SDValue(); 11002 switch (N->getOpcode()) { 11003 case ISD::ADD: 11004 return performAddCombine(N, DCI); 11005 case ISD::SUB: 11006 return performSubCombine(N, DCI); 11007 case ISD::ADDCARRY: 11008 case ISD::SUBCARRY: 11009 return performAddCarrySubCarryCombine(N, DCI); 11010 case ISD::FADD: 11011 return performFAddCombine(N, DCI); 11012 case ISD::FSUB: 11013 return performFSubCombine(N, DCI); 11014 case ISD::SETCC: 11015 return performSetCCCombine(N, DCI); 11016 case ISD::FMAXNUM: 11017 case ISD::FMINNUM: 11018 case ISD::FMAXNUM_IEEE: 11019 case ISD::FMINNUM_IEEE: 11020 case ISD::SMAX: 11021 case ISD::SMIN: 11022 case ISD::UMAX: 11023 case ISD::UMIN: 11024 case AMDGPUISD::FMIN_LEGACY: 11025 case AMDGPUISD::FMAX_LEGACY: 11026 return performMinMaxCombine(N, DCI); 11027 case ISD::FMA: 11028 return performFMACombine(N, DCI); 11029 case ISD::AND: 11030 return performAndCombine(N, DCI); 11031 case ISD::OR: 11032 return performOrCombine(N, DCI); 11033 case ISD::XOR: 11034 return performXorCombine(N, DCI); 11035 case ISD::ZERO_EXTEND: 11036 return performZeroExtendCombine(N, DCI); 11037 case ISD::SIGN_EXTEND_INREG: 11038 return performSignExtendInRegCombine(N , DCI); 11039 case AMDGPUISD::FP_CLASS: 11040 return performClassCombine(N, DCI); 11041 case ISD::FCANONICALIZE: 11042 return performFCanonicalizeCombine(N, DCI); 11043 case AMDGPUISD::RCP: 11044 return performRcpCombine(N, DCI); 11045 case AMDGPUISD::FRACT: 11046 case AMDGPUISD::RSQ: 11047 case AMDGPUISD::RCP_LEGACY: 11048 case AMDGPUISD::RCP_IFLAG: 11049 case AMDGPUISD::RSQ_CLAMP: 11050 case AMDGPUISD::LDEXP: { 11051 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 11052 SDValue Src = N->getOperand(0); 11053 if (Src.isUndef()) 11054 return Src; 11055 break; 11056 } 11057 case ISD::SINT_TO_FP: 11058 case ISD::UINT_TO_FP: 11059 return performUCharToFloatCombine(N, DCI); 11060 case AMDGPUISD::CVT_F32_UBYTE0: 11061 case AMDGPUISD::CVT_F32_UBYTE1: 11062 case AMDGPUISD::CVT_F32_UBYTE2: 11063 case AMDGPUISD::CVT_F32_UBYTE3: 11064 return performCvtF32UByteNCombine(N, DCI); 11065 case AMDGPUISD::FMED3: 11066 return performFMed3Combine(N, DCI); 11067 case AMDGPUISD::CVT_PKRTZ_F16_F32: 11068 return performCvtPkRTZCombine(N, DCI); 11069 case AMDGPUISD::CLAMP: 11070 return performClampCombine(N, DCI); 11071 case ISD::SCALAR_TO_VECTOR: { 11072 SelectionDAG &DAG = DCI.DAG; 11073 EVT VT = N->getValueType(0); 11074 11075 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 11076 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 11077 SDLoc SL(N); 11078 SDValue Src = N->getOperand(0); 11079 EVT EltVT = Src.getValueType(); 11080 if (EltVT == MVT::f16) 11081 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 11082 11083 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 11084 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 11085 } 11086 11087 break; 11088 } 11089 case ISD::EXTRACT_VECTOR_ELT: 11090 return performExtractVectorEltCombine(N, DCI); 11091 case ISD::INSERT_VECTOR_ELT: 11092 return performInsertVectorEltCombine(N, DCI); 11093 case ISD::LOAD: { 11094 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 11095 return Widended; 11096 LLVM_FALLTHROUGH; 11097 } 11098 default: { 11099 if (!DCI.isBeforeLegalize()) { 11100 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 11101 return performMemSDNodeCombine(MemNode, DCI); 11102 } 11103 11104 break; 11105 } 11106 } 11107 11108 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 11109 } 11110 11111 /// Helper function for adjustWritemask 11112 static unsigned SubIdx2Lane(unsigned Idx) { 11113 switch (Idx) { 11114 default: return ~0u; 11115 case AMDGPU::sub0: return 0; 11116 case AMDGPU::sub1: return 1; 11117 case AMDGPU::sub2: return 2; 11118 case AMDGPU::sub3: return 3; 11119 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 11120 } 11121 } 11122 11123 /// Adjust the writemask of MIMG instructions 11124 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 11125 SelectionDAG &DAG) const { 11126 unsigned Opcode = Node->getMachineOpcode(); 11127 11128 // Subtract 1 because the vdata output is not a MachineSDNode operand. 11129 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 11130 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 11131 return Node; // not implemented for D16 11132 11133 SDNode *Users[5] = { nullptr }; 11134 unsigned Lane = 0; 11135 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 11136 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 11137 unsigned NewDmask = 0; 11138 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 11139 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 11140 bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) || 11141 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 11142 unsigned TFCLane = 0; 11143 bool HasChain = Node->getNumValues() > 1; 11144 11145 if (OldDmask == 0) { 11146 // These are folded out, but on the chance it happens don't assert. 11147 return Node; 11148 } 11149 11150 unsigned OldBitsSet = countPopulation(OldDmask); 11151 // Work out which is the TFE/LWE lane if that is enabled. 11152 if (UsesTFC) { 11153 TFCLane = OldBitsSet; 11154 } 11155 11156 // Try to figure out the used register components 11157 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 11158 I != E; ++I) { 11159 11160 // Don't look at users of the chain. 11161 if (I.getUse().getResNo() != 0) 11162 continue; 11163 11164 // Abort if we can't understand the usage 11165 if (!I->isMachineOpcode() || 11166 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 11167 return Node; 11168 11169 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 11170 // Note that subregs are packed, i.e. Lane==0 is the first bit set 11171 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 11172 // set, etc. 11173 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 11174 if (Lane == ~0u) 11175 return Node; 11176 11177 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 11178 if (UsesTFC && Lane == TFCLane) { 11179 Users[Lane] = *I; 11180 } else { 11181 // Set which texture component corresponds to the lane. 11182 unsigned Comp; 11183 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 11184 Comp = countTrailingZeros(Dmask); 11185 Dmask &= ~(1 << Comp); 11186 } 11187 11188 // Abort if we have more than one user per component. 11189 if (Users[Lane]) 11190 return Node; 11191 11192 Users[Lane] = *I; 11193 NewDmask |= 1 << Comp; 11194 } 11195 } 11196 11197 // Don't allow 0 dmask, as hardware assumes one channel enabled. 11198 bool NoChannels = !NewDmask; 11199 if (NoChannels) { 11200 if (!UsesTFC) { 11201 // No uses of the result and not using TFC. Then do nothing. 11202 return Node; 11203 } 11204 // If the original dmask has one channel - then nothing to do 11205 if (OldBitsSet == 1) 11206 return Node; 11207 // Use an arbitrary dmask - required for the instruction to work 11208 NewDmask = 1; 11209 } 11210 // Abort if there's no change 11211 if (NewDmask == OldDmask) 11212 return Node; 11213 11214 unsigned BitsSet = countPopulation(NewDmask); 11215 11216 // Check for TFE or LWE - increase the number of channels by one to account 11217 // for the extra return value 11218 // This will need adjustment for D16 if this is also included in 11219 // adjustWriteMask (this function) but at present D16 are excluded. 11220 unsigned NewChannels = BitsSet + UsesTFC; 11221 11222 int NewOpcode = 11223 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 11224 assert(NewOpcode != -1 && 11225 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 11226 "failed to find equivalent MIMG op"); 11227 11228 // Adjust the writemask in the node 11229 SmallVector<SDValue, 12> Ops; 11230 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 11231 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 11232 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 11233 11234 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 11235 11236 MVT ResultVT = NewChannels == 1 ? 11237 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 11238 NewChannels == 5 ? 8 : NewChannels); 11239 SDVTList NewVTList = HasChain ? 11240 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 11241 11242 11243 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 11244 NewVTList, Ops); 11245 11246 if (HasChain) { 11247 // Update chain. 11248 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 11249 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 11250 } 11251 11252 if (NewChannels == 1) { 11253 assert(Node->hasNUsesOfValue(1, 0)); 11254 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 11255 SDLoc(Node), Users[Lane]->getValueType(0), 11256 SDValue(NewNode, 0)); 11257 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 11258 return nullptr; 11259 } 11260 11261 // Update the users of the node with the new indices 11262 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 11263 SDNode *User = Users[i]; 11264 if (!User) { 11265 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 11266 // Users[0] is still nullptr because channel 0 doesn't really have a use. 11267 if (i || !NoChannels) 11268 continue; 11269 } else { 11270 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 11271 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 11272 } 11273 11274 switch (Idx) { 11275 default: break; 11276 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 11277 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 11278 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 11279 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 11280 } 11281 } 11282 11283 DAG.RemoveDeadNode(Node); 11284 return nullptr; 11285 } 11286 11287 static bool isFrameIndexOp(SDValue Op) { 11288 if (Op.getOpcode() == ISD::AssertZext) 11289 Op = Op.getOperand(0); 11290 11291 return isa<FrameIndexSDNode>(Op); 11292 } 11293 11294 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 11295 /// with frame index operands. 11296 /// LLVM assumes that inputs are to these instructions are registers. 11297 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 11298 SelectionDAG &DAG) const { 11299 if (Node->getOpcode() == ISD::CopyToReg) { 11300 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 11301 SDValue SrcVal = Node->getOperand(2); 11302 11303 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 11304 // to try understanding copies to physical registers. 11305 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 11306 SDLoc SL(Node); 11307 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11308 SDValue VReg = DAG.getRegister( 11309 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 11310 11311 SDNode *Glued = Node->getGluedNode(); 11312 SDValue ToVReg 11313 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 11314 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 11315 SDValue ToResultReg 11316 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 11317 VReg, ToVReg.getValue(1)); 11318 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 11319 DAG.RemoveDeadNode(Node); 11320 return ToResultReg.getNode(); 11321 } 11322 } 11323 11324 SmallVector<SDValue, 8> Ops; 11325 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 11326 if (!isFrameIndexOp(Node->getOperand(i))) { 11327 Ops.push_back(Node->getOperand(i)); 11328 continue; 11329 } 11330 11331 SDLoc DL(Node); 11332 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 11333 Node->getOperand(i).getValueType(), 11334 Node->getOperand(i)), 0)); 11335 } 11336 11337 return DAG.UpdateNodeOperands(Node, Ops); 11338 } 11339 11340 /// Fold the instructions after selecting them. 11341 /// Returns null if users were already updated. 11342 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 11343 SelectionDAG &DAG) const { 11344 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11345 unsigned Opcode = Node->getMachineOpcode(); 11346 11347 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 11348 !TII->isGather4(Opcode) && 11349 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) { 11350 return adjustWritemask(Node, DAG); 11351 } 11352 11353 if (Opcode == AMDGPU::INSERT_SUBREG || 11354 Opcode == AMDGPU::REG_SEQUENCE) { 11355 legalizeTargetIndependentNode(Node, DAG); 11356 return Node; 11357 } 11358 11359 switch (Opcode) { 11360 case AMDGPU::V_DIV_SCALE_F32_e64: 11361 case AMDGPU::V_DIV_SCALE_F64_e64: { 11362 // Satisfy the operand register constraint when one of the inputs is 11363 // undefined. Ordinarily each undef value will have its own implicit_def of 11364 // a vreg, so force these to use a single register. 11365 SDValue Src0 = Node->getOperand(1); 11366 SDValue Src1 = Node->getOperand(3); 11367 SDValue Src2 = Node->getOperand(5); 11368 11369 if ((Src0.isMachineOpcode() && 11370 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 11371 (Src0 == Src1 || Src0 == Src2)) 11372 break; 11373 11374 MVT VT = Src0.getValueType().getSimpleVT(); 11375 const TargetRegisterClass *RC = 11376 getRegClassFor(VT, Src0.getNode()->isDivergent()); 11377 11378 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11379 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 11380 11381 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 11382 UndefReg, Src0, SDValue()); 11383 11384 // src0 must be the same register as src1 or src2, even if the value is 11385 // undefined, so make sure we don't violate this constraint. 11386 if (Src0.isMachineOpcode() && 11387 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 11388 if (Src1.isMachineOpcode() && 11389 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11390 Src0 = Src1; 11391 else if (Src2.isMachineOpcode() && 11392 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11393 Src0 = Src2; 11394 else { 11395 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 11396 Src0 = UndefReg; 11397 Src1 = UndefReg; 11398 } 11399 } else 11400 break; 11401 11402 SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end()); 11403 Ops[1] = Src0; 11404 Ops[3] = Src1; 11405 Ops[5] = Src2; 11406 Ops.push_back(ImpDef.getValue(1)); 11407 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 11408 } 11409 default: 11410 break; 11411 } 11412 11413 return Node; 11414 } 11415 11416 // Any MIMG instructions that use tfe or lwe require an initialization of the 11417 // result register that will be written in the case of a memory access failure. 11418 // The required code is also added to tie this init code to the result of the 11419 // img instruction. 11420 void SITargetLowering::AddIMGInit(MachineInstr &MI) const { 11421 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11422 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 11423 MachineRegisterInfo &MRI = MI.getMF()->getRegInfo(); 11424 MachineBasicBlock &MBB = *MI.getParent(); 11425 11426 MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe); 11427 MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe); 11428 MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16); 11429 11430 if (!TFE && !LWE) // intersect_ray 11431 return; 11432 11433 unsigned TFEVal = TFE ? TFE->getImm() : 0; 11434 unsigned LWEVal = LWE->getImm(); 11435 unsigned D16Val = D16 ? D16->getImm() : 0; 11436 11437 if (!TFEVal && !LWEVal) 11438 return; 11439 11440 // At least one of TFE or LWE are non-zero 11441 // We have to insert a suitable initialization of the result value and 11442 // tie this to the dest of the image instruction. 11443 11444 const DebugLoc &DL = MI.getDebugLoc(); 11445 11446 int DstIdx = 11447 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata); 11448 11449 // Calculate which dword we have to initialize to 0. 11450 MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask); 11451 11452 // check that dmask operand is found. 11453 assert(MO_Dmask && "Expected dmask operand in instruction"); 11454 11455 unsigned dmask = MO_Dmask->getImm(); 11456 // Determine the number of active lanes taking into account the 11457 // Gather4 special case 11458 unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask); 11459 11460 bool Packed = !Subtarget->hasUnpackedD16VMem(); 11461 11462 unsigned InitIdx = 11463 D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1; 11464 11465 // Abandon attempt if the dst size isn't large enough 11466 // - this is in fact an error but this is picked up elsewhere and 11467 // reported correctly. 11468 uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32; 11469 if (DstSize < InitIdx) 11470 return; 11471 11472 // Create a register for the intialization value. 11473 Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11474 unsigned NewDst = 0; // Final initialized value will be in here 11475 11476 // If PRTStrictNull feature is enabled (the default) then initialize 11477 // all the result registers to 0, otherwise just the error indication 11478 // register (VGPRn+1) 11479 unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1; 11480 unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1); 11481 11482 BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst); 11483 for (; SizeLeft; SizeLeft--, CurrIdx++) { 11484 NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11485 // Initialize dword 11486 Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 11487 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg) 11488 .addImm(0); 11489 // Insert into the super-reg 11490 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst) 11491 .addReg(PrevDst) 11492 .addReg(SubReg) 11493 .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx)); 11494 11495 PrevDst = NewDst; 11496 } 11497 11498 // Add as an implicit operand 11499 MI.addOperand(MachineOperand::CreateReg(NewDst, false, true)); 11500 11501 // Tie the just added implicit operand to the dst 11502 MI.tieOperands(DstIdx, MI.getNumOperands() - 1); 11503 } 11504 11505 /// Assign the register class depending on the number of 11506 /// bits set in the writemask 11507 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11508 SDNode *Node) const { 11509 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11510 11511 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 11512 11513 if (TII->isVOP3(MI.getOpcode())) { 11514 // Make sure constant bus requirements are respected. 11515 TII->legalizeOperandsVOP3(MRI, MI); 11516 11517 // Prefer VGPRs over AGPRs in mAI instructions where possible. 11518 // This saves a chain-copy of registers and better ballance register 11519 // use between vgpr and agpr as agpr tuples tend to be big. 11520 if (MI.getDesc().OpInfo) { 11521 unsigned Opc = MI.getOpcode(); 11522 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11523 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 11524 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 11525 if (I == -1) 11526 break; 11527 MachineOperand &Op = MI.getOperand(I); 11528 if (!Op.isReg() || !Op.getReg().isVirtual()) 11529 continue; 11530 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11531 if (!TRI->hasAGPRs(RC)) 11532 continue; 11533 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11534 if (!Src || !Src->isCopy() || 11535 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11536 continue; 11537 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11538 // All uses of agpr64 and agpr32 can also accept vgpr except for 11539 // v_accvgpr_read, but we do not produce agpr reads during selection, 11540 // so no use checks are needed. 11541 MRI.setRegClass(Op.getReg(), NewRC); 11542 } 11543 } 11544 11545 return; 11546 } 11547 11548 // Replace unused atomics with the no return version. 11549 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 11550 if (NoRetAtomicOp != -1) { 11551 if (!Node->hasAnyUseOfValue(0)) { 11552 int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), 11553 AMDGPU::OpName::cpol); 11554 if (CPolIdx != -1) { 11555 MachineOperand &CPol = MI.getOperand(CPolIdx); 11556 CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC); 11557 } 11558 MI.RemoveOperand(0); 11559 MI.setDesc(TII->get(NoRetAtomicOp)); 11560 return; 11561 } 11562 11563 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 11564 // instruction, because the return type of these instructions is a vec2 of 11565 // the memory type, so it can be tied to the input operand. 11566 // This means these instructions always have a use, so we need to add a 11567 // special case to check if the atomic has only one extract_subreg use, 11568 // which itself has no uses. 11569 if ((Node->hasNUsesOfValue(1, 0) && 11570 Node->use_begin()->isMachineOpcode() && 11571 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 11572 !Node->use_begin()->hasAnyUseOfValue(0))) { 11573 Register Def = MI.getOperand(0).getReg(); 11574 11575 // Change this into a noret atomic. 11576 MI.setDesc(TII->get(NoRetAtomicOp)); 11577 MI.RemoveOperand(0); 11578 11579 // If we only remove the def operand from the atomic instruction, the 11580 // extract_subreg will be left with a use of a vreg without a def. 11581 // So we need to insert an implicit_def to avoid machine verifier 11582 // errors. 11583 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 11584 TII->get(AMDGPU::IMPLICIT_DEF), Def); 11585 } 11586 return; 11587 } 11588 11589 if (TII->isMIMG(MI) && !MI.mayStore()) 11590 AddIMGInit(MI); 11591 } 11592 11593 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11594 uint64_t Val) { 11595 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11596 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11597 } 11598 11599 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11600 const SDLoc &DL, 11601 SDValue Ptr) const { 11602 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11603 11604 // Build the half of the subregister with the constants before building the 11605 // full 128-bit register. If we are building multiple resource descriptors, 11606 // this will allow CSEing of the 2-component register. 11607 const SDValue Ops0[] = { 11608 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11609 buildSMovImm32(DAG, DL, 0), 11610 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11611 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11612 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11613 }; 11614 11615 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11616 MVT::v2i32, Ops0), 0); 11617 11618 // Combine the constants and the pointer. 11619 const SDValue Ops1[] = { 11620 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11621 Ptr, 11622 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11623 SubRegHi, 11624 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11625 }; 11626 11627 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11628 } 11629 11630 /// Return a resource descriptor with the 'Add TID' bit enabled 11631 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11632 /// of the resource descriptor) to create an offset, which is added to 11633 /// the resource pointer. 11634 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11635 SDValue Ptr, uint32_t RsrcDword1, 11636 uint64_t RsrcDword2And3) const { 11637 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11638 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11639 if (RsrcDword1) { 11640 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11641 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11642 0); 11643 } 11644 11645 SDValue DataLo = buildSMovImm32(DAG, DL, 11646 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11647 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11648 11649 const SDValue Ops[] = { 11650 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11651 PtrLo, 11652 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11653 PtrHi, 11654 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11655 DataLo, 11656 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11657 DataHi, 11658 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11659 }; 11660 11661 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11662 } 11663 11664 //===----------------------------------------------------------------------===// 11665 // SI Inline Assembly Support 11666 //===----------------------------------------------------------------------===// 11667 11668 std::pair<unsigned, const TargetRegisterClass *> 11669 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_, 11670 StringRef Constraint, 11671 MVT VT) const { 11672 const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_); 11673 11674 const TargetRegisterClass *RC = nullptr; 11675 if (Constraint.size() == 1) { 11676 const unsigned BitWidth = VT.getSizeInBits(); 11677 switch (Constraint[0]) { 11678 default: 11679 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11680 case 's': 11681 case 'r': 11682 switch (BitWidth) { 11683 case 16: 11684 RC = &AMDGPU::SReg_32RegClass; 11685 break; 11686 case 64: 11687 RC = &AMDGPU::SGPR_64RegClass; 11688 break; 11689 default: 11690 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11691 if (!RC) 11692 return std::make_pair(0U, nullptr); 11693 break; 11694 } 11695 break; 11696 case 'v': 11697 switch (BitWidth) { 11698 case 16: 11699 RC = &AMDGPU::VGPR_32RegClass; 11700 break; 11701 default: 11702 RC = TRI->getVGPRClassForBitWidth(BitWidth); 11703 if (!RC) 11704 return std::make_pair(0U, nullptr); 11705 break; 11706 } 11707 break; 11708 case 'a': 11709 if (!Subtarget->hasMAIInsts()) 11710 break; 11711 switch (BitWidth) { 11712 case 16: 11713 RC = &AMDGPU::AGPR_32RegClass; 11714 break; 11715 default: 11716 RC = TRI->getAGPRClassForBitWidth(BitWidth); 11717 if (!RC) 11718 return std::make_pair(0U, nullptr); 11719 break; 11720 } 11721 break; 11722 } 11723 // We actually support i128, i16 and f16 as inline parameters 11724 // even if they are not reported as legal 11725 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11726 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11727 return std::make_pair(0U, RC); 11728 } 11729 11730 if (Constraint.size() > 1) { 11731 if (Constraint[1] == 'v') { 11732 RC = &AMDGPU::VGPR_32RegClass; 11733 } else if (Constraint[1] == 's') { 11734 RC = &AMDGPU::SGPR_32RegClass; 11735 } else if (Constraint[1] == 'a') { 11736 RC = &AMDGPU::AGPR_32RegClass; 11737 } 11738 11739 if (RC) { 11740 uint32_t Idx; 11741 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 11742 if (!Failed && Idx < RC->getNumRegs()) 11743 return std::make_pair(RC->getRegister(Idx), RC); 11744 } 11745 } 11746 11747 // FIXME: Returns VS_32 for physical SGPR constraints 11748 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11749 } 11750 11751 static bool isImmConstraint(StringRef Constraint) { 11752 if (Constraint.size() == 1) { 11753 switch (Constraint[0]) { 11754 default: break; 11755 case 'I': 11756 case 'J': 11757 case 'A': 11758 case 'B': 11759 case 'C': 11760 return true; 11761 } 11762 } else if (Constraint == "DA" || 11763 Constraint == "DB") { 11764 return true; 11765 } 11766 return false; 11767 } 11768 11769 SITargetLowering::ConstraintType 11770 SITargetLowering::getConstraintType(StringRef Constraint) const { 11771 if (Constraint.size() == 1) { 11772 switch (Constraint[0]) { 11773 default: break; 11774 case 's': 11775 case 'v': 11776 case 'a': 11777 return C_RegisterClass; 11778 } 11779 } 11780 if (isImmConstraint(Constraint)) { 11781 return C_Other; 11782 } 11783 return TargetLowering::getConstraintType(Constraint); 11784 } 11785 11786 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11787 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11788 Val = Val & maskTrailingOnes<uint64_t>(Size); 11789 } 11790 return Val; 11791 } 11792 11793 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11794 std::string &Constraint, 11795 std::vector<SDValue> &Ops, 11796 SelectionDAG &DAG) const { 11797 if (isImmConstraint(Constraint)) { 11798 uint64_t Val; 11799 if (getAsmOperandConstVal(Op, Val) && 11800 checkAsmConstraintVal(Op, Constraint, Val)) { 11801 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11802 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11803 } 11804 } else { 11805 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11806 } 11807 } 11808 11809 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11810 unsigned Size = Op.getScalarValueSizeInBits(); 11811 if (Size > 64) 11812 return false; 11813 11814 if (Size == 16 && !Subtarget->has16BitInsts()) 11815 return false; 11816 11817 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11818 Val = C->getSExtValue(); 11819 return true; 11820 } 11821 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11822 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11823 return true; 11824 } 11825 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11826 if (Size != 16 || Op.getNumOperands() != 2) 11827 return false; 11828 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11829 return false; 11830 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11831 Val = C->getSExtValue(); 11832 return true; 11833 } 11834 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11835 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11836 return true; 11837 } 11838 } 11839 11840 return false; 11841 } 11842 11843 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 11844 const std::string &Constraint, 11845 uint64_t Val) const { 11846 if (Constraint.size() == 1) { 11847 switch (Constraint[0]) { 11848 case 'I': 11849 return AMDGPU::isInlinableIntLiteral(Val); 11850 case 'J': 11851 return isInt<16>(Val); 11852 case 'A': 11853 return checkAsmConstraintValA(Op, Val); 11854 case 'B': 11855 return isInt<32>(Val); 11856 case 'C': 11857 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 11858 AMDGPU::isInlinableIntLiteral(Val); 11859 default: 11860 break; 11861 } 11862 } else if (Constraint.size() == 2) { 11863 if (Constraint == "DA") { 11864 int64_t HiBits = static_cast<int32_t>(Val >> 32); 11865 int64_t LoBits = static_cast<int32_t>(Val); 11866 return checkAsmConstraintValA(Op, HiBits, 32) && 11867 checkAsmConstraintValA(Op, LoBits, 32); 11868 } 11869 if (Constraint == "DB") { 11870 return true; 11871 } 11872 } 11873 llvm_unreachable("Invalid asm constraint"); 11874 } 11875 11876 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 11877 uint64_t Val, 11878 unsigned MaxSize) const { 11879 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 11880 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11881 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11882 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11883 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11884 return true; 11885 } 11886 return false; 11887 } 11888 11889 static int getAlignedAGPRClassID(unsigned UnalignedClassID) { 11890 switch (UnalignedClassID) { 11891 case AMDGPU::VReg_64RegClassID: 11892 return AMDGPU::VReg_64_Align2RegClassID; 11893 case AMDGPU::VReg_96RegClassID: 11894 return AMDGPU::VReg_96_Align2RegClassID; 11895 case AMDGPU::VReg_128RegClassID: 11896 return AMDGPU::VReg_128_Align2RegClassID; 11897 case AMDGPU::VReg_160RegClassID: 11898 return AMDGPU::VReg_160_Align2RegClassID; 11899 case AMDGPU::VReg_192RegClassID: 11900 return AMDGPU::VReg_192_Align2RegClassID; 11901 case AMDGPU::VReg_224RegClassID: 11902 return AMDGPU::VReg_224_Align2RegClassID; 11903 case AMDGPU::VReg_256RegClassID: 11904 return AMDGPU::VReg_256_Align2RegClassID; 11905 case AMDGPU::VReg_512RegClassID: 11906 return AMDGPU::VReg_512_Align2RegClassID; 11907 case AMDGPU::VReg_1024RegClassID: 11908 return AMDGPU::VReg_1024_Align2RegClassID; 11909 case AMDGPU::AReg_64RegClassID: 11910 return AMDGPU::AReg_64_Align2RegClassID; 11911 case AMDGPU::AReg_96RegClassID: 11912 return AMDGPU::AReg_96_Align2RegClassID; 11913 case AMDGPU::AReg_128RegClassID: 11914 return AMDGPU::AReg_128_Align2RegClassID; 11915 case AMDGPU::AReg_160RegClassID: 11916 return AMDGPU::AReg_160_Align2RegClassID; 11917 case AMDGPU::AReg_192RegClassID: 11918 return AMDGPU::AReg_192_Align2RegClassID; 11919 case AMDGPU::AReg_256RegClassID: 11920 return AMDGPU::AReg_256_Align2RegClassID; 11921 case AMDGPU::AReg_512RegClassID: 11922 return AMDGPU::AReg_512_Align2RegClassID; 11923 case AMDGPU::AReg_1024RegClassID: 11924 return AMDGPU::AReg_1024_Align2RegClassID; 11925 default: 11926 return -1; 11927 } 11928 } 11929 11930 // Figure out which registers should be reserved for stack access. Only after 11931 // the function is legalized do we know all of the non-spill stack objects or if 11932 // calls are present. 11933 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 11934 MachineRegisterInfo &MRI = MF.getRegInfo(); 11935 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11936 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 11937 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11938 const SIInstrInfo *TII = ST.getInstrInfo(); 11939 11940 if (Info->isEntryFunction()) { 11941 // Callable functions have fixed registers used for stack access. 11942 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 11943 } 11944 11945 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 11946 Info->getStackPtrOffsetReg())); 11947 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 11948 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 11949 11950 // We need to worry about replacing the default register with itself in case 11951 // of MIR testcases missing the MFI. 11952 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 11953 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 11954 11955 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 11956 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 11957 11958 Info->limitOccupancy(MF); 11959 11960 if (ST.isWave32() && !MF.empty()) { 11961 for (auto &MBB : MF) { 11962 for (auto &MI : MBB) { 11963 TII->fixImplicitOperands(MI); 11964 } 11965 } 11966 } 11967 11968 // FIXME: This is a hack to fixup AGPR classes to use the properly aligned 11969 // classes if required. Ideally the register class constraints would differ 11970 // per-subtarget, but there's no easy way to achieve that right now. This is 11971 // not a problem for VGPRs because the correctly aligned VGPR class is implied 11972 // from using them as the register class for legal types. 11973 if (ST.needsAlignedVGPRs()) { 11974 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) { 11975 const Register Reg = Register::index2VirtReg(I); 11976 const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg); 11977 if (!RC) 11978 continue; 11979 int NewClassID = getAlignedAGPRClassID(RC->getID()); 11980 if (NewClassID != -1) 11981 MRI.setRegClass(Reg, TRI->getRegClass(NewClassID)); 11982 } 11983 } 11984 11985 TargetLoweringBase::finalizeLowering(MF); 11986 11987 // Allocate a VGPR for future SGPR Spill if 11988 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 11989 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 11990 if (VGPRReserveforSGPRSpill && TRI->spillSGPRToVGPR() && 11991 !Info->VGPRReservedForSGPRSpill && !Info->isEntryFunction()) 11992 Info->reserveVGPRforSGPRSpills(MF); 11993 } 11994 11995 void SITargetLowering::computeKnownBitsForFrameIndex( 11996 const int FI, KnownBits &Known, const MachineFunction &MF) const { 11997 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 11998 11999 // Set the high bits to zero based on the maximum allowed scratch size per 12000 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 12001 // calculation won't overflow, so assume the sign bit is never set. 12002 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 12003 } 12004 12005 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 12006 KnownBits &Known, unsigned Dim) { 12007 unsigned MaxValue = 12008 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 12009 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 12010 } 12011 12012 void SITargetLowering::computeKnownBitsForTargetInstr( 12013 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 12014 const MachineRegisterInfo &MRI, unsigned Depth) const { 12015 const MachineInstr *MI = MRI.getVRegDef(R); 12016 switch (MI->getOpcode()) { 12017 case AMDGPU::G_INTRINSIC: { 12018 switch (MI->getIntrinsicID()) { 12019 case Intrinsic::amdgcn_workitem_id_x: 12020 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 12021 break; 12022 case Intrinsic::amdgcn_workitem_id_y: 12023 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 12024 break; 12025 case Intrinsic::amdgcn_workitem_id_z: 12026 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 12027 break; 12028 case Intrinsic::amdgcn_mbcnt_lo: 12029 case Intrinsic::amdgcn_mbcnt_hi: { 12030 // These return at most the wavefront size - 1. 12031 unsigned Size = MRI.getType(R).getSizeInBits(); 12032 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 12033 break; 12034 } 12035 case Intrinsic::amdgcn_groupstaticsize: { 12036 // We can report everything over the maximum size as 0. We can't report 12037 // based on the actual size because we don't know if it's accurate or not 12038 // at any given point. 12039 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 12040 break; 12041 } 12042 } 12043 break; 12044 } 12045 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE: 12046 Known.Zero.setHighBits(24); 12047 break; 12048 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT: 12049 Known.Zero.setHighBits(16); 12050 break; 12051 } 12052 } 12053 12054 Align SITargetLowering::computeKnownAlignForTargetInstr( 12055 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 12056 unsigned Depth) const { 12057 const MachineInstr *MI = MRI.getVRegDef(R); 12058 switch (MI->getOpcode()) { 12059 case AMDGPU::G_INTRINSIC: 12060 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 12061 // FIXME: Can this move to generic code? What about the case where the call 12062 // site specifies a lower alignment? 12063 Intrinsic::ID IID = MI->getIntrinsicID(); 12064 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 12065 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 12066 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 12067 return *RetAlign; 12068 return Align(1); 12069 } 12070 default: 12071 return Align(1); 12072 } 12073 } 12074 12075 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 12076 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 12077 const Align CacheLineAlign = Align(64); 12078 12079 // Pre-GFX10 target did not benefit from loop alignment 12080 if (!ML || DisableLoopAlignment || 12081 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 12082 getSubtarget()->hasInstFwdPrefetchBug()) 12083 return PrefAlign; 12084 12085 // On GFX10 I$ is 4 x 64 bytes cache lines. 12086 // By default prefetcher keeps one cache line behind and reads two ahead. 12087 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 12088 // behind and one ahead. 12089 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 12090 // If loop fits 64 bytes it always spans no more than two cache lines and 12091 // does not need an alignment. 12092 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 12093 // Else if loop is less or equal 192 bytes we need two lines behind. 12094 12095 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 12096 const MachineBasicBlock *Header = ML->getHeader(); 12097 if (Header->getAlignment() != PrefAlign) 12098 return Header->getAlignment(); // Already processed. 12099 12100 unsigned LoopSize = 0; 12101 for (const MachineBasicBlock *MBB : ML->blocks()) { 12102 // If inner loop block is aligned assume in average half of the alignment 12103 // size to be added as nops. 12104 if (MBB != Header) 12105 LoopSize += MBB->getAlignment().value() / 2; 12106 12107 for (const MachineInstr &MI : *MBB) { 12108 LoopSize += TII->getInstSizeInBytes(MI); 12109 if (LoopSize > 192) 12110 return PrefAlign; 12111 } 12112 } 12113 12114 if (LoopSize <= 64) 12115 return PrefAlign; 12116 12117 if (LoopSize <= 128) 12118 return CacheLineAlign; 12119 12120 // If any of parent loops is surrounded by prefetch instructions do not 12121 // insert new for inner loop, which would reset parent's settings. 12122 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 12123 if (MachineBasicBlock *Exit = P->getExitBlock()) { 12124 auto I = Exit->getFirstNonDebugInstr(); 12125 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 12126 return CacheLineAlign; 12127 } 12128 } 12129 12130 MachineBasicBlock *Pre = ML->getLoopPreheader(); 12131 MachineBasicBlock *Exit = ML->getExitBlock(); 12132 12133 if (Pre && Exit) { 12134 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 12135 TII->get(AMDGPU::S_INST_PREFETCH)) 12136 .addImm(1); // prefetch 2 lines behind PC 12137 12138 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 12139 TII->get(AMDGPU::S_INST_PREFETCH)) 12140 .addImm(2); // prefetch 1 line behind PC 12141 } 12142 12143 return CacheLineAlign; 12144 } 12145 12146 LLVM_ATTRIBUTE_UNUSED 12147 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 12148 assert(N->getOpcode() == ISD::CopyFromReg); 12149 do { 12150 // Follow the chain until we find an INLINEASM node. 12151 N = N->getOperand(0).getNode(); 12152 if (N->getOpcode() == ISD::INLINEASM || 12153 N->getOpcode() == ISD::INLINEASM_BR) 12154 return true; 12155 } while (N->getOpcode() == ISD::CopyFromReg); 12156 return false; 12157 } 12158 12159 bool SITargetLowering::isSDNodeSourceOfDivergence( 12160 const SDNode *N, FunctionLoweringInfo *FLI, 12161 LegacyDivergenceAnalysis *KDA) const { 12162 switch (N->getOpcode()) { 12163 case ISD::CopyFromReg: { 12164 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 12165 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 12166 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12167 Register Reg = R->getReg(); 12168 12169 // FIXME: Why does this need to consider isLiveIn? 12170 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 12171 return !TRI->isSGPRReg(MRI, Reg); 12172 12173 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 12174 return KDA->isDivergent(V); 12175 12176 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 12177 return !TRI->isSGPRReg(MRI, Reg); 12178 } 12179 case ISD::LOAD: { 12180 const LoadSDNode *L = cast<LoadSDNode>(N); 12181 unsigned AS = L->getAddressSpace(); 12182 // A flat load may access private memory. 12183 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 12184 } 12185 case ISD::CALLSEQ_END: 12186 return true; 12187 case ISD::INTRINSIC_WO_CHAIN: 12188 return AMDGPU::isIntrinsicSourceOfDivergence( 12189 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 12190 case ISD::INTRINSIC_W_CHAIN: 12191 return AMDGPU::isIntrinsicSourceOfDivergence( 12192 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 12193 case AMDGPUISD::ATOMIC_CMP_SWAP: 12194 case AMDGPUISD::ATOMIC_INC: 12195 case AMDGPUISD::ATOMIC_DEC: 12196 case AMDGPUISD::ATOMIC_LOAD_FMIN: 12197 case AMDGPUISD::ATOMIC_LOAD_FMAX: 12198 case AMDGPUISD::BUFFER_ATOMIC_SWAP: 12199 case AMDGPUISD::BUFFER_ATOMIC_ADD: 12200 case AMDGPUISD::BUFFER_ATOMIC_SUB: 12201 case AMDGPUISD::BUFFER_ATOMIC_SMIN: 12202 case AMDGPUISD::BUFFER_ATOMIC_UMIN: 12203 case AMDGPUISD::BUFFER_ATOMIC_SMAX: 12204 case AMDGPUISD::BUFFER_ATOMIC_UMAX: 12205 case AMDGPUISD::BUFFER_ATOMIC_AND: 12206 case AMDGPUISD::BUFFER_ATOMIC_OR: 12207 case AMDGPUISD::BUFFER_ATOMIC_XOR: 12208 case AMDGPUISD::BUFFER_ATOMIC_INC: 12209 case AMDGPUISD::BUFFER_ATOMIC_DEC: 12210 case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP: 12211 case AMDGPUISD::BUFFER_ATOMIC_CSUB: 12212 case AMDGPUISD::BUFFER_ATOMIC_FADD: 12213 case AMDGPUISD::BUFFER_ATOMIC_FMIN: 12214 case AMDGPUISD::BUFFER_ATOMIC_FMAX: 12215 // Target-specific read-modify-write atomics are sources of divergence. 12216 return true; 12217 default: 12218 if (auto *A = dyn_cast<AtomicSDNode>(N)) { 12219 // Generic read-modify-write atomics are sources of divergence. 12220 return A->readMem() && A->writeMem(); 12221 } 12222 return false; 12223 } 12224 } 12225 12226 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 12227 EVT VT) const { 12228 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 12229 case MVT::f32: 12230 return hasFP32Denormals(DAG.getMachineFunction()); 12231 case MVT::f64: 12232 case MVT::f16: 12233 return hasFP64FP16Denormals(DAG.getMachineFunction()); 12234 default: 12235 return false; 12236 } 12237 } 12238 12239 bool SITargetLowering::denormalsEnabledForType(LLT Ty, 12240 MachineFunction &MF) const { 12241 switch (Ty.getScalarSizeInBits()) { 12242 case 32: 12243 return hasFP32Denormals(MF); 12244 case 64: 12245 case 16: 12246 return hasFP64FP16Denormals(MF); 12247 default: 12248 return false; 12249 } 12250 } 12251 12252 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 12253 const SelectionDAG &DAG, 12254 bool SNaN, 12255 unsigned Depth) const { 12256 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 12257 const MachineFunction &MF = DAG.getMachineFunction(); 12258 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 12259 12260 if (Info->getMode().DX10Clamp) 12261 return true; // Clamped to 0. 12262 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 12263 } 12264 12265 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 12266 SNaN, Depth); 12267 } 12268 12269 // Global FP atomic instructions have a hardcoded FP mode and do not support 12270 // FP32 denormals, and only support v2f16 denormals. 12271 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) { 12272 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics(); 12273 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt); 12274 if (&Flt == &APFloat::IEEEsingle()) 12275 return DenormMode == DenormalMode::getPreserveSign(); 12276 return DenormMode == DenormalMode::getIEEE(); 12277 } 12278 12279 TargetLowering::AtomicExpansionKind 12280 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 12281 12282 auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) { 12283 OptimizationRemarkEmitter ORE(RMW->getFunction()); 12284 LLVMContext &Ctx = RMW->getFunction()->getContext(); 12285 SmallVector<StringRef> SSNs; 12286 Ctx.getSyncScopeNames(SSNs); 12287 auto MemScope = SSNs[RMW->getSyncScopeID()].empty() 12288 ? "system" 12289 : SSNs[RMW->getSyncScopeID()]; 12290 ORE.emit([&]() { 12291 return OptimizationRemark(DEBUG_TYPE, "Passed", RMW) 12292 << "Hardware instruction generated for atomic " 12293 << RMW->getOperationName(RMW->getOperation()) 12294 << " operation at memory scope " << MemScope 12295 << " due to an unsafe request."; 12296 }); 12297 return Kind; 12298 }; 12299 12300 switch (RMW->getOperation()) { 12301 case AtomicRMWInst::FAdd: { 12302 Type *Ty = RMW->getType(); 12303 12304 // We don't have a way to support 16-bit atomics now, so just leave them 12305 // as-is. 12306 if (Ty->isHalfTy()) 12307 return AtomicExpansionKind::None; 12308 12309 if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy())) 12310 return AtomicExpansionKind::CmpXChg; 12311 12312 unsigned AS = RMW->getPointerAddressSpace(); 12313 12314 if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) && 12315 Subtarget->hasAtomicFaddInsts()) { 12316 // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe 12317 // floating point atomic instructions. May generate more efficient code, 12318 // but may not respect rounding and denormal modes, and may give incorrect 12319 // results for certain memory destinations. 12320 if (RMW->getFunction() 12321 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12322 .getValueAsString() != "true") 12323 return AtomicExpansionKind::CmpXChg; 12324 12325 if (Subtarget->hasGFX90AInsts()) { 12326 if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS) 12327 return AtomicExpansionKind::CmpXChg; 12328 12329 auto SSID = RMW->getSyncScopeID(); 12330 if (SSID == SyncScope::System || 12331 SSID == RMW->getContext().getOrInsertSyncScopeID("one-as")) 12332 return AtomicExpansionKind::CmpXChg; 12333 12334 return ReportUnsafeHWInst(AtomicExpansionKind::None); 12335 } 12336 12337 if (AS == AMDGPUAS::FLAT_ADDRESS) 12338 return AtomicExpansionKind::CmpXChg; 12339 12340 return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None) 12341 : AtomicExpansionKind::CmpXChg; 12342 } 12343 12344 // DS FP atomics do repect the denormal mode, but the rounding mode is fixed 12345 // to round-to-nearest-even. 12346 // The only exception is DS_ADD_F64 which never flushes regardless of mode. 12347 if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) { 12348 if (!Ty->isDoubleTy()) 12349 return AtomicExpansionKind::None; 12350 12351 if (fpModeMatchesGlobalFPAtomicMode(RMW)) 12352 return AtomicExpansionKind::None; 12353 12354 return RMW->getFunction() 12355 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12356 .getValueAsString() == "true" 12357 ? ReportUnsafeHWInst(AtomicExpansionKind::None) 12358 : AtomicExpansionKind::CmpXChg; 12359 } 12360 12361 return AtomicExpansionKind::CmpXChg; 12362 } 12363 default: 12364 break; 12365 } 12366 12367 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 12368 } 12369 12370 const TargetRegisterClass * 12371 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 12372 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 12373 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12374 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 12375 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 12376 : &AMDGPU::SReg_32RegClass; 12377 if (!TRI->isSGPRClass(RC) && !isDivergent) 12378 return TRI->getEquivalentSGPRClass(RC); 12379 else if (TRI->isSGPRClass(RC) && isDivergent) 12380 return TRI->getEquivalentVGPRClass(RC); 12381 12382 return RC; 12383 } 12384 12385 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 12386 // uniform values (as produced by the mask results of control flow intrinsics) 12387 // used outside of divergent blocks. The phi users need to also be treated as 12388 // always uniform. 12389 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 12390 unsigned WaveSize) { 12391 // FIXME: We asssume we never cast the mask results of a control flow 12392 // intrinsic. 12393 // Early exit if the type won't be consistent as a compile time hack. 12394 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 12395 if (!IT || IT->getBitWidth() != WaveSize) 12396 return false; 12397 12398 if (!isa<Instruction>(V)) 12399 return false; 12400 if (!Visited.insert(V).second) 12401 return false; 12402 bool Result = false; 12403 for (auto U : V->users()) { 12404 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 12405 if (V == U->getOperand(1)) { 12406 switch (Intrinsic->getIntrinsicID()) { 12407 default: 12408 Result = false; 12409 break; 12410 case Intrinsic::amdgcn_if_break: 12411 case Intrinsic::amdgcn_if: 12412 case Intrinsic::amdgcn_else: 12413 Result = true; 12414 break; 12415 } 12416 } 12417 if (V == U->getOperand(0)) { 12418 switch (Intrinsic->getIntrinsicID()) { 12419 default: 12420 Result = false; 12421 break; 12422 case Intrinsic::amdgcn_end_cf: 12423 case Intrinsic::amdgcn_loop: 12424 Result = true; 12425 break; 12426 } 12427 } 12428 } else { 12429 Result = hasCFUser(U, Visited, WaveSize); 12430 } 12431 if (Result) 12432 break; 12433 } 12434 return Result; 12435 } 12436 12437 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 12438 const Value *V) const { 12439 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 12440 if (CI->isInlineAsm()) { 12441 // FIXME: This cannot give a correct answer. This should only trigger in 12442 // the case where inline asm returns mixed SGPR and VGPR results, used 12443 // outside the defining block. We don't have a specific result to 12444 // consider, so this assumes if any value is SGPR, the overall register 12445 // also needs to be SGPR. 12446 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 12447 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 12448 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 12449 for (auto &TC : TargetConstraints) { 12450 if (TC.Type == InlineAsm::isOutput) { 12451 ComputeConstraintToUse(TC, SDValue()); 12452 unsigned AssignedReg; 12453 const TargetRegisterClass *RC; 12454 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 12455 SIRI, TC.ConstraintCode, TC.ConstraintVT); 12456 if (RC) { 12457 MachineRegisterInfo &MRI = MF.getRegInfo(); 12458 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 12459 return true; 12460 else if (SIRI->isSGPRClass(RC)) 12461 return true; 12462 } 12463 } 12464 } 12465 } 12466 } 12467 SmallPtrSet<const Value *, 16> Visited; 12468 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 12469 } 12470 12471 std::pair<InstructionCost, MVT> 12472 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 12473 Type *Ty) const { 12474 std::pair<InstructionCost, MVT> Cost = 12475 TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 12476 auto Size = DL.getTypeSizeInBits(Ty); 12477 // Maximum load or store can handle 8 dwords for scalar and 4 for 12478 // vector ALU. Let's assume anything above 8 dwords is expensive 12479 // even if legal. 12480 if (Size <= 256) 12481 return Cost; 12482 12483 Cost.first += (Size + 255) / 256; 12484 return Cost; 12485 } 12486