1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 /// \file 10 /// Custom DAG lowering for SI 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "SIISelLowering.h" 15 #include "AMDGPU.h" 16 #include "AMDGPUInstrInfo.h" 17 #include "AMDGPUTargetMachine.h" 18 #include "SIMachineFunctionInfo.h" 19 #include "SIRegisterInfo.h" 20 #include "llvm/ADT/FloatingPointMode.h" 21 #include "llvm/ADT/Statistic.h" 22 #include "llvm/Analysis/LegacyDivergenceAnalysis.h" 23 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 24 #include "llvm/BinaryFormat/ELF.h" 25 #include "llvm/CodeGen/Analysis.h" 26 #include "llvm/CodeGen/FunctionLoweringInfo.h" 27 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h" 28 #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h" 29 #include "llvm/CodeGen/MachineFunction.h" 30 #include "llvm/CodeGen/MachineLoopInfo.h" 31 #include "llvm/IR/DiagnosticInfo.h" 32 #include "llvm/IR/IntrinsicInst.h" 33 #include "llvm/IR/IntrinsicsAMDGPU.h" 34 #include "llvm/IR/IntrinsicsR600.h" 35 #include "llvm/Support/CommandLine.h" 36 #include "llvm/Support/KnownBits.h" 37 38 using namespace llvm; 39 40 #define DEBUG_TYPE "si-lower" 41 42 STATISTIC(NumTailCalls, "Number of tail calls"); 43 44 static cl::opt<bool> DisableLoopAlignment( 45 "amdgpu-disable-loop-alignment", 46 cl::desc("Do not align and prefetch loops"), 47 cl::init(false)); 48 49 static cl::opt<bool> UseDivergentRegisterIndexing( 50 "amdgpu-use-divergent-register-indexing", 51 cl::Hidden, 52 cl::desc("Use indirect register addressing for divergent indexes"), 53 cl::init(false)); 54 55 static bool hasFP32Denormals(const MachineFunction &MF) { 56 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 57 return Info->getMode().allFP32Denormals(); 58 } 59 60 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 61 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 62 return Info->getMode().allFP64FP16Denormals(); 63 } 64 65 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 66 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 67 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 68 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 69 return AMDGPU::SGPR0 + Reg; 70 } 71 } 72 llvm_unreachable("Cannot allocate sgpr"); 73 } 74 75 SITargetLowering::SITargetLowering(const TargetMachine &TM, 76 const GCNSubtarget &STI) 77 : AMDGPUTargetLowering(TM, STI), 78 Subtarget(&STI) { 79 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 80 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 81 82 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 83 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 84 85 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 86 87 const SIRegisterInfo *TRI = STI.getRegisterInfo(); 88 const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class(); 89 90 addRegisterClass(MVT::f64, V64RegClass); 91 addRegisterClass(MVT::v2f32, V64RegClass); 92 93 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 94 addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96)); 95 96 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 97 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 98 99 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 100 addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128)); 101 102 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 103 addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160)); 104 105 addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass); 106 addRegisterClass(MVT::v6f32, TRI->getVGPRClassForBitWidth(192)); 107 108 addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass); 109 addRegisterClass(MVT::v3f64, TRI->getVGPRClassForBitWidth(192)); 110 111 addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass); 112 addRegisterClass(MVT::v7f32, TRI->getVGPRClassForBitWidth(224)); 113 114 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass); 115 addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256)); 116 117 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass); 118 addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256)); 119 120 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass); 121 addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512)); 122 123 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass); 124 addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512)); 125 126 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass); 127 addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024)); 128 129 if (Subtarget->has16BitInsts()) { 130 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 131 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 132 133 // Unless there are also VOP3P operations, not operations are really legal. 134 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 135 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 136 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 137 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 138 addRegisterClass(MVT::v8i16, &AMDGPU::SGPR_128RegClass); 139 addRegisterClass(MVT::v8f16, &AMDGPU::SGPR_128RegClass); 140 } 141 142 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 143 addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024)); 144 145 computeRegisterProperties(Subtarget->getRegisterInfo()); 146 147 // The boolean content concept here is too inflexible. Compares only ever 148 // really produce a 1-bit result. Any copy/extend from these will turn into a 149 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 150 // it's what most targets use. 151 setBooleanContents(ZeroOrOneBooleanContent); 152 setBooleanVectorContents(ZeroOrOneBooleanContent); 153 154 // We need to custom lower vector stores from local memory 155 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 156 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 157 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 158 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 159 setOperationAction(ISD::LOAD, MVT::v6i32, Custom); 160 setOperationAction(ISD::LOAD, MVT::v7i32, Custom); 161 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 162 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 163 setOperationAction(ISD::LOAD, MVT::i1, Custom); 164 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 165 166 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 167 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 168 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 169 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 170 setOperationAction(ISD::STORE, MVT::v6i32, Custom); 171 setOperationAction(ISD::STORE, MVT::v7i32, Custom); 172 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 173 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 174 setOperationAction(ISD::STORE, MVT::i1, Custom); 175 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 176 177 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 178 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 179 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 180 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 181 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 182 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 183 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 184 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 185 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 186 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 187 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 188 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand); 189 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand); 190 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand); 191 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand); 192 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand); 193 194 setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand); 195 setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand); 196 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand); 197 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand); 198 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand); 199 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand); 200 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand); 201 202 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 203 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 204 205 setOperationAction(ISD::SELECT, MVT::i1, Promote); 206 setOperationAction(ISD::SELECT, MVT::i64, Custom); 207 setOperationAction(ISD::SELECT, MVT::f64, Promote); 208 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 209 210 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 211 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 212 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 213 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 214 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 215 216 setOperationAction(ISD::SETCC, MVT::i1, Promote); 217 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 218 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 219 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 220 221 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 222 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 223 setOperationAction(ISD::TRUNCATE, MVT::v3i32, Expand); 224 setOperationAction(ISD::FP_ROUND, MVT::v3f32, Expand); 225 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand); 226 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand); 227 setOperationAction(ISD::TRUNCATE, MVT::v5i32, Expand); 228 setOperationAction(ISD::FP_ROUND, MVT::v5f32, Expand); 229 setOperationAction(ISD::TRUNCATE, MVT::v6i32, Expand); 230 setOperationAction(ISD::FP_ROUND, MVT::v6f32, Expand); 231 setOperationAction(ISD::TRUNCATE, MVT::v7i32, Expand); 232 setOperationAction(ISD::FP_ROUND, MVT::v7f32, Expand); 233 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand); 234 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand); 235 setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand); 236 setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand); 237 238 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 239 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 240 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 241 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 242 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 243 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 244 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 245 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 246 247 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 248 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 249 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 250 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 251 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 252 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 253 254 setOperationAction(ISD::UADDO, MVT::i32, Legal); 255 setOperationAction(ISD::USUBO, MVT::i32, Legal); 256 257 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 258 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 259 260 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 261 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 262 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 263 264 #if 0 265 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 266 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 267 #endif 268 269 // We only support LOAD/STORE and vector manipulation ops for vectors 270 // with > 4 elements. 271 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 272 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 273 MVT::v3i64, MVT::v3f64, MVT::v6i32, MVT::v6f32, 274 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, 275 MVT::v8i16, MVT::v8f16, MVT::v16i64, MVT::v16f64, 276 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 setOperationAction(ISD::FPTRUNC_ROUND, MVT::f16, Custom); 607 608 // F16 - VOP2 Actions. 609 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 610 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 611 612 setOperationAction(ISD::FDIV, MVT::f16, Custom); 613 614 // F16 - VOP3 Actions. 615 setOperationAction(ISD::FMA, MVT::f16, Legal); 616 if (STI.hasMadF16()) 617 setOperationAction(ISD::FMAD, MVT::f16, Legal); 618 619 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16, MVT::v8i16, 620 MVT::v8f16}) { 621 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 622 switch (Op) { 623 case ISD::LOAD: 624 case ISD::STORE: 625 case ISD::BUILD_VECTOR: 626 case ISD::BITCAST: 627 case ISD::EXTRACT_VECTOR_ELT: 628 case ISD::INSERT_VECTOR_ELT: 629 case ISD::INSERT_SUBVECTOR: 630 case ISD::EXTRACT_SUBVECTOR: 631 case ISD::SCALAR_TO_VECTOR: 632 break; 633 case ISD::CONCAT_VECTORS: 634 setOperationAction(Op, VT, Custom); 635 break; 636 default: 637 setOperationAction(Op, VT, Expand); 638 break; 639 } 640 } 641 } 642 643 // v_perm_b32 can handle either of these. 644 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 645 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 646 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 647 648 // XXX - Do these do anything? Vector constants turn into build_vector. 649 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 650 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 651 652 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 653 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 654 655 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 656 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 657 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 658 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 659 660 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 661 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 662 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 663 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 664 665 setOperationAction(ISD::AND, MVT::v2i16, Promote); 666 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 667 setOperationAction(ISD::OR, MVT::v2i16, Promote); 668 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 669 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 670 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 671 672 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 673 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 674 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 675 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 676 677 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 678 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 679 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 680 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 681 682 setOperationAction(ISD::LOAD, MVT::v8i16, Promote); 683 AddPromotedToType(ISD::LOAD, MVT::v8i16, MVT::v4i32); 684 setOperationAction(ISD::LOAD, MVT::v8f16, Promote); 685 AddPromotedToType(ISD::LOAD, MVT::v8f16, MVT::v4i32); 686 687 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 688 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 689 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 690 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 691 692 setOperationAction(ISD::STORE, MVT::v8i16, Promote); 693 AddPromotedToType(ISD::STORE, MVT::v8i16, MVT::v4i32); 694 setOperationAction(ISD::STORE, MVT::v8f16, Promote); 695 AddPromotedToType(ISD::STORE, MVT::v8f16, MVT::v4i32); 696 697 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 698 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 699 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 700 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 701 702 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 703 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 704 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 705 706 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Expand); 707 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Expand); 708 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Expand); 709 710 if (!Subtarget->hasVOP3PInsts()) { 711 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 712 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 713 } 714 715 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 716 // This isn't really legal, but this avoids the legalizer unrolling it (and 717 // allows matching fneg (fabs x) patterns) 718 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 719 720 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 721 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 722 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 723 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 724 725 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 726 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 727 setOperationAction(ISD::FMINNUM_IEEE, MVT::v8f16, Custom); 728 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v8f16, Custom); 729 730 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 731 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 732 setOperationAction(ISD::FMINNUM, MVT::v8f16, Expand); 733 setOperationAction(ISD::FMAXNUM, MVT::v8f16, Expand); 734 735 for (MVT Vec16 : { MVT::v8i16, MVT::v8f16 }) { 736 setOperationAction(ISD::BUILD_VECTOR, Vec16, Custom); 737 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec16, Custom); 738 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec16, Expand); 739 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec16, Expand); 740 } 741 } 742 743 if (Subtarget->hasVOP3PInsts()) { 744 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 745 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 746 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 747 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 748 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 749 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 750 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 751 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 752 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 753 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 754 755 setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal); 756 setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal); 757 setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal); 758 setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal); 759 760 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 761 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 762 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 763 764 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 765 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 766 767 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 768 769 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 770 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 771 772 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 773 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 774 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f16, Custom); 775 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i16, Custom); 776 777 for (MVT VT : { MVT::v4i16, MVT::v8i16 }) { 778 // Split vector operations. 779 setOperationAction(ISD::SHL, VT, Custom); 780 setOperationAction(ISD::SRA, VT, Custom); 781 setOperationAction(ISD::SRL, VT, Custom); 782 setOperationAction(ISD::ADD, VT, Custom); 783 setOperationAction(ISD::SUB, VT, Custom); 784 setOperationAction(ISD::MUL, VT, Custom); 785 786 setOperationAction(ISD::SMIN, VT, Custom); 787 setOperationAction(ISD::SMAX, VT, Custom); 788 setOperationAction(ISD::UMIN, VT, Custom); 789 setOperationAction(ISD::UMAX, VT, Custom); 790 791 setOperationAction(ISD::UADDSAT, VT, Custom); 792 setOperationAction(ISD::SADDSAT, VT, Custom); 793 setOperationAction(ISD::USUBSAT, VT, Custom); 794 setOperationAction(ISD::SSUBSAT, VT, Custom); 795 } 796 797 for (MVT VT : { MVT::v4f16, MVT::v8f16 }) { 798 // Split vector operations. 799 setOperationAction(ISD::FADD, VT, Custom); 800 setOperationAction(ISD::FMUL, VT, Custom); 801 setOperationAction(ISD::FMA, VT, Custom); 802 setOperationAction(ISD::FCANONICALIZE, VT, Custom); 803 } 804 805 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 806 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 807 808 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 809 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 810 811 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 812 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 813 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 814 815 if (Subtarget->hasPackedFP32Ops()) { 816 setOperationAction(ISD::FADD, MVT::v2f32, Legal); 817 setOperationAction(ISD::FMUL, MVT::v2f32, Legal); 818 setOperationAction(ISD::FMA, MVT::v2f32, Legal); 819 setOperationAction(ISD::FNEG, MVT::v2f32, Legal); 820 821 for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) { 822 setOperationAction(ISD::FADD, VT, Custom); 823 setOperationAction(ISD::FMUL, VT, Custom); 824 setOperationAction(ISD::FMA, VT, Custom); 825 } 826 } 827 } 828 829 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 830 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 831 832 if (Subtarget->has16BitInsts()) { 833 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 834 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 835 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 836 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 837 } else { 838 // Legalization hack. 839 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 840 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 841 842 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 843 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 844 } 845 846 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8, 847 MVT::v8i16, MVT::v8f16 }) { 848 setOperationAction(ISD::SELECT, VT, Custom); 849 } 850 851 setOperationAction(ISD::SMULO, MVT::i64, Custom); 852 setOperationAction(ISD::UMULO, MVT::i64, Custom); 853 854 if (Subtarget->hasMad64_32()) { 855 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom); 856 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom); 857 } 858 859 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 860 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 861 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 862 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 863 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 864 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 865 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 866 867 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 868 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 869 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom); 870 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom); 871 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 872 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 873 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 874 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 875 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 876 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 877 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 878 879 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 880 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 881 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 882 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom); 883 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom); 884 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 885 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 886 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 887 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 888 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 889 890 setTargetDAGCombine(ISD::ADD); 891 setTargetDAGCombine(ISD::ADDCARRY); 892 setTargetDAGCombine(ISD::SUB); 893 setTargetDAGCombine(ISD::SUBCARRY); 894 setTargetDAGCombine(ISD::FADD); 895 setTargetDAGCombine(ISD::FSUB); 896 setTargetDAGCombine(ISD::FMINNUM); 897 setTargetDAGCombine(ISD::FMAXNUM); 898 setTargetDAGCombine(ISD::FMINNUM_IEEE); 899 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 900 setTargetDAGCombine(ISD::FMA); 901 setTargetDAGCombine(ISD::SMIN); 902 setTargetDAGCombine(ISD::SMAX); 903 setTargetDAGCombine(ISD::UMIN); 904 setTargetDAGCombine(ISD::UMAX); 905 setTargetDAGCombine(ISD::SETCC); 906 setTargetDAGCombine(ISD::AND); 907 setTargetDAGCombine(ISD::OR); 908 setTargetDAGCombine(ISD::XOR); 909 setTargetDAGCombine(ISD::SINT_TO_FP); 910 setTargetDAGCombine(ISD::UINT_TO_FP); 911 setTargetDAGCombine(ISD::FCANONICALIZE); 912 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 913 setTargetDAGCombine(ISD::ZERO_EXTEND); 914 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 915 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 916 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 917 918 // All memory operations. Some folding on the pointer operand is done to help 919 // matching the constant offsets in the addressing modes. 920 setTargetDAGCombine(ISD::LOAD); 921 setTargetDAGCombine(ISD::STORE); 922 setTargetDAGCombine(ISD::ATOMIC_LOAD); 923 setTargetDAGCombine(ISD::ATOMIC_STORE); 924 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 925 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 926 setTargetDAGCombine(ISD::ATOMIC_SWAP); 927 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 928 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 929 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 930 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 931 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 932 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 933 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 934 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 935 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 936 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 937 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 938 setTargetDAGCombine(ISD::INTRINSIC_VOID); 939 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 940 941 // FIXME: In other contexts we pretend this is a per-function property. 942 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 943 944 setSchedulingPreference(Sched::RegPressure); 945 } 946 947 const GCNSubtarget *SITargetLowering::getSubtarget() const { 948 return Subtarget; 949 } 950 951 //===----------------------------------------------------------------------===// 952 // TargetLowering queries 953 //===----------------------------------------------------------------------===// 954 955 // v_mad_mix* support a conversion from f16 to f32. 956 // 957 // There is only one special case when denormals are enabled we don't currently, 958 // where this is OK to use. 959 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 960 EVT DestVT, EVT SrcVT) const { 961 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 962 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 963 DestVT.getScalarType() == MVT::f32 && 964 SrcVT.getScalarType() == MVT::f16 && 965 // TODO: This probably only requires no input flushing? 966 !hasFP32Denormals(DAG.getMachineFunction()); 967 } 968 969 bool SITargetLowering::isFPExtFoldable(const MachineInstr &MI, unsigned Opcode, 970 LLT DestTy, LLT SrcTy) const { 971 return ((Opcode == TargetOpcode::G_FMAD && Subtarget->hasMadMixInsts()) || 972 (Opcode == TargetOpcode::G_FMA && Subtarget->hasFmaMixInsts())) && 973 DestTy.getScalarSizeInBits() == 32 && 974 SrcTy.getScalarSizeInBits() == 16 && 975 // TODO: This probably only requires no input flushing? 976 !hasFP32Denormals(*MI.getMF()); 977 } 978 979 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 980 // SI has some legal vector types, but no legal vector operations. Say no 981 // shuffles are legal in order to prefer scalarizing some vector operations. 982 return false; 983 } 984 985 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 986 CallingConv::ID CC, 987 EVT VT) const { 988 if (CC == CallingConv::AMDGPU_KERNEL) 989 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 990 991 if (VT.isVector()) { 992 EVT ScalarVT = VT.getScalarType(); 993 unsigned Size = ScalarVT.getSizeInBits(); 994 if (Size == 16) { 995 if (Subtarget->has16BitInsts()) 996 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 997 return VT.isInteger() ? MVT::i32 : MVT::f32; 998 } 999 1000 if (Size < 16) 1001 return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32; 1002 return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32; 1003 } 1004 1005 if (VT.getSizeInBits() > 32) 1006 return MVT::i32; 1007 1008 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1009 } 1010 1011 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1012 CallingConv::ID CC, 1013 EVT VT) const { 1014 if (CC == CallingConv::AMDGPU_KERNEL) 1015 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1016 1017 if (VT.isVector()) { 1018 unsigned NumElts = VT.getVectorNumElements(); 1019 EVT ScalarVT = VT.getScalarType(); 1020 unsigned Size = ScalarVT.getSizeInBits(); 1021 1022 // FIXME: Should probably promote 8-bit vectors to i16. 1023 if (Size == 16 && Subtarget->has16BitInsts()) 1024 return (NumElts + 1) / 2; 1025 1026 if (Size <= 32) 1027 return NumElts; 1028 1029 if (Size > 32) 1030 return NumElts * ((Size + 31) / 32); 1031 } else if (VT.getSizeInBits() > 32) 1032 return (VT.getSizeInBits() + 31) / 32; 1033 1034 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1035 } 1036 1037 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 1038 LLVMContext &Context, CallingConv::ID CC, 1039 EVT VT, EVT &IntermediateVT, 1040 unsigned &NumIntermediates, MVT &RegisterVT) const { 1041 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 1042 unsigned NumElts = VT.getVectorNumElements(); 1043 EVT ScalarVT = VT.getScalarType(); 1044 unsigned Size = ScalarVT.getSizeInBits(); 1045 // FIXME: We should fix the ABI to be the same on targets without 16-bit 1046 // support, but unless we can properly handle 3-vectors, it will be still be 1047 // inconsistent. 1048 if (Size == 16 && Subtarget->has16BitInsts()) { 1049 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 1050 IntermediateVT = RegisterVT; 1051 NumIntermediates = (NumElts + 1) / 2; 1052 return NumIntermediates; 1053 } 1054 1055 if (Size == 32) { 1056 RegisterVT = ScalarVT.getSimpleVT(); 1057 IntermediateVT = RegisterVT; 1058 NumIntermediates = NumElts; 1059 return NumIntermediates; 1060 } 1061 1062 if (Size < 16 && Subtarget->has16BitInsts()) { 1063 // FIXME: Should probably form v2i16 pieces 1064 RegisterVT = MVT::i16; 1065 IntermediateVT = ScalarVT; 1066 NumIntermediates = NumElts; 1067 return NumIntermediates; 1068 } 1069 1070 1071 if (Size != 16 && Size <= 32) { 1072 RegisterVT = MVT::i32; 1073 IntermediateVT = ScalarVT; 1074 NumIntermediates = NumElts; 1075 return NumIntermediates; 1076 } 1077 1078 if (Size > 32) { 1079 RegisterVT = MVT::i32; 1080 IntermediateVT = RegisterVT; 1081 NumIntermediates = NumElts * ((Size + 31) / 32); 1082 return NumIntermediates; 1083 } 1084 } 1085 1086 return TargetLowering::getVectorTypeBreakdownForCallingConv( 1087 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 1088 } 1089 1090 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 1091 assert(DMaskLanes != 0); 1092 1093 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 1094 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 1095 return EVT::getVectorVT(Ty->getContext(), 1096 EVT::getEVT(VT->getElementType()), 1097 NumElts); 1098 } 1099 1100 return EVT::getEVT(Ty); 1101 } 1102 1103 // Peek through TFE struct returns to only use the data size. 1104 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 1105 auto *ST = dyn_cast<StructType>(Ty); 1106 if (!ST) 1107 return memVTFromImageData(Ty, DMaskLanes); 1108 1109 // Some intrinsics return an aggregate type - special case to work out the 1110 // correct memVT. 1111 // 1112 // Only limited forms of aggregate type currently expected. 1113 if (ST->getNumContainedTypes() != 2 || 1114 !ST->getContainedType(1)->isIntegerTy(32)) 1115 return EVT(); 1116 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 1117 } 1118 1119 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1120 const CallInst &CI, 1121 MachineFunction &MF, 1122 unsigned IntrID) const { 1123 Info.flags = MachineMemOperand::MONone; 1124 if (CI.hasMetadata(LLVMContext::MD_invariant_load)) 1125 Info.flags |= MachineMemOperand::MOInvariant; 1126 1127 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 1128 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 1129 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 1130 (Intrinsic::ID)IntrID); 1131 if (Attr.hasFnAttr(Attribute::ReadNone)) 1132 return false; 1133 1134 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1135 1136 if (RsrcIntr->IsImage) { 1137 Info.ptrVal = 1138 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1139 Info.align.reset(); 1140 } else { 1141 Info.ptrVal = 1142 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1143 } 1144 1145 Info.flags |= MachineMemOperand::MODereferenceable; 1146 if (Attr.hasFnAttr(Attribute::ReadOnly)) { 1147 unsigned DMaskLanes = 4; 1148 1149 if (RsrcIntr->IsImage) { 1150 const AMDGPU::ImageDimIntrinsicInfo *Intr 1151 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 1152 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1153 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1154 1155 if (!BaseOpcode->Gather4) { 1156 // If this isn't a gather, we may have excess loaded elements in the 1157 // IR type. Check the dmask for the real number of elements loaded. 1158 unsigned DMask 1159 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1160 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1161 } 1162 1163 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1164 } else 1165 Info.memVT = EVT::getEVT(CI.getType()); 1166 1167 // FIXME: What does alignment mean for an image? 1168 Info.opc = ISD::INTRINSIC_W_CHAIN; 1169 Info.flags |= MachineMemOperand::MOLoad; 1170 } else if (Attr.hasFnAttr(Attribute::WriteOnly)) { 1171 Info.opc = ISD::INTRINSIC_VOID; 1172 1173 Type *DataTy = CI.getArgOperand(0)->getType(); 1174 if (RsrcIntr->IsImage) { 1175 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1176 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1177 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1178 } else 1179 Info.memVT = EVT::getEVT(DataTy); 1180 1181 Info.flags |= MachineMemOperand::MOStore; 1182 } else { 1183 // Atomic 1184 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID : 1185 ISD::INTRINSIC_W_CHAIN; 1186 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 1187 Info.flags |= MachineMemOperand::MOLoad | 1188 MachineMemOperand::MOStore | 1189 MachineMemOperand::MODereferenceable; 1190 1191 // XXX - Should this be volatile without known ordering? 1192 Info.flags |= MachineMemOperand::MOVolatile; 1193 } 1194 return true; 1195 } 1196 1197 switch (IntrID) { 1198 case Intrinsic::amdgcn_atomic_inc: 1199 case Intrinsic::amdgcn_atomic_dec: 1200 case Intrinsic::amdgcn_ds_ordered_add: 1201 case Intrinsic::amdgcn_ds_ordered_swap: 1202 case Intrinsic::amdgcn_ds_fadd: 1203 case Intrinsic::amdgcn_ds_fmin: 1204 case Intrinsic::amdgcn_ds_fmax: { 1205 Info.opc = ISD::INTRINSIC_W_CHAIN; 1206 Info.memVT = MVT::getVT(CI.getType()); 1207 Info.ptrVal = CI.getOperand(0); 1208 Info.align.reset(); 1209 Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1210 1211 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1212 if (!Vol->isZero()) 1213 Info.flags |= MachineMemOperand::MOVolatile; 1214 1215 return true; 1216 } 1217 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1218 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1219 1220 Info.opc = ISD::INTRINSIC_W_CHAIN; 1221 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1222 Info.ptrVal = 1223 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1224 Info.align.reset(); 1225 Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1226 1227 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1228 if (!Vol || !Vol->isZero()) 1229 Info.flags |= MachineMemOperand::MOVolatile; 1230 1231 return true; 1232 } 1233 case Intrinsic::amdgcn_ds_append: 1234 case Intrinsic::amdgcn_ds_consume: { 1235 Info.opc = ISD::INTRINSIC_W_CHAIN; 1236 Info.memVT = MVT::getVT(CI.getType()); 1237 Info.ptrVal = CI.getOperand(0); 1238 Info.align.reset(); 1239 Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1240 1241 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1242 if (!Vol->isZero()) 1243 Info.flags |= MachineMemOperand::MOVolatile; 1244 1245 return true; 1246 } 1247 case Intrinsic::amdgcn_global_atomic_csub: { 1248 Info.opc = ISD::INTRINSIC_W_CHAIN; 1249 Info.memVT = MVT::getVT(CI.getType()); 1250 Info.ptrVal = CI.getOperand(0); 1251 Info.align.reset(); 1252 Info.flags |= MachineMemOperand::MOLoad | 1253 MachineMemOperand::MOStore | 1254 MachineMemOperand::MOVolatile; 1255 return true; 1256 } 1257 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 1258 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1259 Info.opc = ISD::INTRINSIC_W_CHAIN; 1260 Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT? 1261 Info.ptrVal = 1262 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1263 Info.align.reset(); 1264 Info.flags |= MachineMemOperand::MOLoad | 1265 MachineMemOperand::MODereferenceable; 1266 return true; 1267 } 1268 case Intrinsic::amdgcn_global_atomic_fadd: 1269 case Intrinsic::amdgcn_global_atomic_fmin: 1270 case Intrinsic::amdgcn_global_atomic_fmax: 1271 case Intrinsic::amdgcn_flat_atomic_fadd: 1272 case Intrinsic::amdgcn_flat_atomic_fmin: 1273 case Intrinsic::amdgcn_flat_atomic_fmax: { 1274 Info.opc = ISD::INTRINSIC_W_CHAIN; 1275 Info.memVT = MVT::getVT(CI.getType()); 1276 Info.ptrVal = CI.getOperand(0); 1277 Info.align.reset(); 1278 Info.flags |= MachineMemOperand::MOLoad | 1279 MachineMemOperand::MOStore | 1280 MachineMemOperand::MODereferenceable | 1281 MachineMemOperand::MOVolatile; 1282 return true; 1283 } 1284 case Intrinsic::amdgcn_ds_gws_init: 1285 case Intrinsic::amdgcn_ds_gws_barrier: 1286 case Intrinsic::amdgcn_ds_gws_sema_v: 1287 case Intrinsic::amdgcn_ds_gws_sema_br: 1288 case Intrinsic::amdgcn_ds_gws_sema_p: 1289 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1290 Info.opc = ISD::INTRINSIC_VOID; 1291 1292 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1293 Info.ptrVal = 1294 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1295 1296 // This is an abstract access, but we need to specify a type and size. 1297 Info.memVT = MVT::i32; 1298 Info.size = 4; 1299 Info.align = Align(4); 1300 1301 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1302 Info.flags |= MachineMemOperand::MOLoad; 1303 else 1304 Info.flags |= MachineMemOperand::MOStore; 1305 return true; 1306 } 1307 default: 1308 return false; 1309 } 1310 } 1311 1312 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1313 SmallVectorImpl<Value*> &Ops, 1314 Type *&AccessTy) const { 1315 switch (II->getIntrinsicID()) { 1316 case Intrinsic::amdgcn_atomic_inc: 1317 case Intrinsic::amdgcn_atomic_dec: 1318 case Intrinsic::amdgcn_ds_ordered_add: 1319 case Intrinsic::amdgcn_ds_ordered_swap: 1320 case Intrinsic::amdgcn_ds_append: 1321 case Intrinsic::amdgcn_ds_consume: 1322 case Intrinsic::amdgcn_ds_fadd: 1323 case Intrinsic::amdgcn_ds_fmin: 1324 case Intrinsic::amdgcn_ds_fmax: 1325 case Intrinsic::amdgcn_global_atomic_fadd: 1326 case Intrinsic::amdgcn_flat_atomic_fadd: 1327 case Intrinsic::amdgcn_flat_atomic_fmin: 1328 case Intrinsic::amdgcn_flat_atomic_fmax: 1329 case Intrinsic::amdgcn_global_atomic_csub: { 1330 Value *Ptr = II->getArgOperand(0); 1331 AccessTy = II->getType(); 1332 Ops.push_back(Ptr); 1333 return true; 1334 } 1335 default: 1336 return false; 1337 } 1338 } 1339 1340 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1341 if (!Subtarget->hasFlatInstOffsets()) { 1342 // Flat instructions do not have offsets, and only have the register 1343 // address. 1344 return AM.BaseOffs == 0 && AM.Scale == 0; 1345 } 1346 1347 return AM.Scale == 0 && 1348 (AM.BaseOffs == 0 || 1349 Subtarget->getInstrInfo()->isLegalFLATOffset( 1350 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT)); 1351 } 1352 1353 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1354 if (Subtarget->hasFlatGlobalInsts()) 1355 return AM.Scale == 0 && 1356 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1357 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1358 SIInstrFlags::FlatGlobal)); 1359 1360 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1361 // Assume the we will use FLAT for all global memory accesses 1362 // on VI. 1363 // FIXME: This assumption is currently wrong. On VI we still use 1364 // MUBUF instructions for the r + i addressing mode. As currently 1365 // implemented, the MUBUF instructions only work on buffer < 4GB. 1366 // It may be possible to support > 4GB buffers with MUBUF instructions, 1367 // by setting the stride value in the resource descriptor which would 1368 // increase the size limit to (stride * 4GB). However, this is risky, 1369 // because it has never been validated. 1370 return isLegalFlatAddressingMode(AM); 1371 } 1372 1373 return isLegalMUBUFAddressingMode(AM); 1374 } 1375 1376 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1377 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1378 // additionally can do r + r + i with addr64. 32-bit has more addressing 1379 // mode options. Depending on the resource constant, it can also do 1380 // (i64 r0) + (i32 r1) * (i14 i). 1381 // 1382 // Private arrays end up using a scratch buffer most of the time, so also 1383 // assume those use MUBUF instructions. Scratch loads / stores are currently 1384 // implemented as mubuf instructions with offen bit set, so slightly 1385 // different than the normal addr64. 1386 if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs)) 1387 return false; 1388 1389 // FIXME: Since we can split immediate into soffset and immediate offset, 1390 // would it make sense to allow any immediate? 1391 1392 switch (AM.Scale) { 1393 case 0: // r + i or just i, depending on HasBaseReg. 1394 return true; 1395 case 1: 1396 return true; // We have r + r or r + i. 1397 case 2: 1398 if (AM.HasBaseReg) { 1399 // Reject 2 * r + r. 1400 return false; 1401 } 1402 1403 // Allow 2 * r as r + r 1404 // Or 2 * r + i is allowed as r + r + i. 1405 return true; 1406 default: // Don't allow n * r 1407 return false; 1408 } 1409 } 1410 1411 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1412 const AddrMode &AM, Type *Ty, 1413 unsigned AS, Instruction *I) const { 1414 // No global is ever allowed as a base. 1415 if (AM.BaseGV) 1416 return false; 1417 1418 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1419 return isLegalGlobalAddressingMode(AM); 1420 1421 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1422 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1423 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1424 // If the offset isn't a multiple of 4, it probably isn't going to be 1425 // correctly aligned. 1426 // FIXME: Can we get the real alignment here? 1427 if (AM.BaseOffs % 4 != 0) 1428 return isLegalMUBUFAddressingMode(AM); 1429 1430 // There are no SMRD extloads, so if we have to do a small type access we 1431 // will use a MUBUF load. 1432 // FIXME?: We also need to do this if unaligned, but we don't know the 1433 // alignment here. 1434 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1435 return isLegalGlobalAddressingMode(AM); 1436 1437 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1438 // SMRD instructions have an 8-bit, dword offset on SI. 1439 if (!isUInt<8>(AM.BaseOffs / 4)) 1440 return false; 1441 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1442 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1443 // in 8-bits, it can use a smaller encoding. 1444 if (!isUInt<32>(AM.BaseOffs / 4)) 1445 return false; 1446 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1447 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1448 if (!isUInt<20>(AM.BaseOffs)) 1449 return false; 1450 } else 1451 llvm_unreachable("unhandled generation"); 1452 1453 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1454 return true; 1455 1456 if (AM.Scale == 1 && AM.HasBaseReg) 1457 return true; 1458 1459 return false; 1460 1461 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1462 return isLegalMUBUFAddressingMode(AM); 1463 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1464 AS == AMDGPUAS::REGION_ADDRESS) { 1465 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1466 // field. 1467 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1468 // an 8-bit dword offset but we don't know the alignment here. 1469 if (!isUInt<16>(AM.BaseOffs)) 1470 return false; 1471 1472 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1473 return true; 1474 1475 if (AM.Scale == 1 && AM.HasBaseReg) 1476 return true; 1477 1478 return false; 1479 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1480 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1481 // For an unknown address space, this usually means that this is for some 1482 // reason being used for pure arithmetic, and not based on some addressing 1483 // computation. We don't have instructions that compute pointers with any 1484 // addressing modes, so treat them as having no offset like flat 1485 // instructions. 1486 return isLegalFlatAddressingMode(AM); 1487 } 1488 1489 // Assume a user alias of global for unknown address spaces. 1490 return isLegalGlobalAddressingMode(AM); 1491 } 1492 1493 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1494 const MachineFunction &MF) const { 1495 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1496 return (MemVT.getSizeInBits() <= 4 * 32); 1497 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1498 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1499 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1500 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1501 return (MemVT.getSizeInBits() <= 2 * 32); 1502 } 1503 return true; 1504 } 1505 1506 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1507 unsigned Size, unsigned AddrSpace, Align Alignment, 1508 MachineMemOperand::Flags Flags, bool *IsFast) const { 1509 if (IsFast) 1510 *IsFast = false; 1511 1512 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1513 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1514 // Check if alignment requirements for ds_read/write instructions are 1515 // disabled. 1516 if (Subtarget->hasUnalignedDSAccessEnabled() && 1517 !Subtarget->hasLDSMisalignedBug()) { 1518 if (IsFast) 1519 *IsFast = Alignment != Align(2); 1520 return true; 1521 } 1522 1523 // Either, the alignment requirements are "enabled", or there is an 1524 // unaligned LDS access related hardware bug though alignment requirements 1525 // are "disabled". In either case, we need to check for proper alignment 1526 // requirements. 1527 // 1528 if (Size == 64) { 1529 // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we 1530 // can do a 4 byte aligned, 8 byte access in a single operation using 1531 // ds_read2/write2_b32 with adjacent offsets. 1532 bool AlignedBy4 = Alignment >= Align(4); 1533 if (IsFast) 1534 *IsFast = AlignedBy4; 1535 1536 return AlignedBy4; 1537 } 1538 if (Size == 96) { 1539 // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on 1540 // gfx8 and older. 1541 bool AlignedBy16 = Alignment >= Align(16); 1542 if (IsFast) 1543 *IsFast = AlignedBy16; 1544 1545 return AlignedBy16; 1546 } 1547 if (Size == 128) { 1548 // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on 1549 // gfx8 and older, but we can do a 8 byte aligned, 16 byte access in a 1550 // single operation using ds_read2/write2_b64. 1551 bool AlignedBy8 = Alignment >= Align(8); 1552 if (IsFast) 1553 *IsFast = AlignedBy8; 1554 1555 return AlignedBy8; 1556 } 1557 } 1558 1559 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) { 1560 bool AlignedBy4 = Alignment >= Align(4); 1561 if (IsFast) 1562 *IsFast = AlignedBy4; 1563 1564 return AlignedBy4 || 1565 Subtarget->enableFlatScratch() || 1566 Subtarget->hasUnalignedScratchAccess(); 1567 } 1568 1569 // FIXME: We have to be conservative here and assume that flat operations 1570 // will access scratch. If we had access to the IR function, then we 1571 // could determine if any private memory was used in the function. 1572 if (AddrSpace == AMDGPUAS::FLAT_ADDRESS && 1573 !Subtarget->hasUnalignedScratchAccess()) { 1574 bool AlignedBy4 = Alignment >= Align(4); 1575 if (IsFast) 1576 *IsFast = AlignedBy4; 1577 1578 return AlignedBy4; 1579 } 1580 1581 if (Subtarget->hasUnalignedBufferAccessEnabled() && 1582 !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1583 AddrSpace == AMDGPUAS::REGION_ADDRESS)) { 1584 // If we have an uniform constant load, it still requires using a slow 1585 // buffer instruction if unaligned. 1586 if (IsFast) { 1587 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1588 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1589 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1590 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1591 Alignment >= Align(4) : Alignment != Align(2); 1592 } 1593 1594 return true; 1595 } 1596 1597 // Smaller than dword value must be aligned. 1598 if (Size < 32) 1599 return false; 1600 1601 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1602 // byte-address are ignored, thus forcing Dword alignment. 1603 // This applies to private, global, and constant memory. 1604 if (IsFast) 1605 *IsFast = true; 1606 1607 return Size >= 32 && Alignment >= Align(4); 1608 } 1609 1610 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1611 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 1612 bool *IsFast) const { 1613 if (IsFast) 1614 *IsFast = false; 1615 1616 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1617 // which isn't a simple VT. 1618 // Until MVT is extended to handle this, simply check for the size and 1619 // rely on the condition below: allow accesses if the size is a multiple of 4. 1620 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1621 VT.getStoreSize() > 16)) { 1622 return false; 1623 } 1624 1625 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1626 Alignment, Flags, IsFast); 1627 } 1628 1629 EVT SITargetLowering::getOptimalMemOpType( 1630 const MemOp &Op, const AttributeList &FuncAttributes) const { 1631 // FIXME: Should account for address space here. 1632 1633 // The default fallback uses the private pointer size as a guess for a type to 1634 // use. Make sure we switch these to 64-bit accesses. 1635 1636 if (Op.size() >= 16 && 1637 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1638 return MVT::v4i32; 1639 1640 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1641 return MVT::v2i32; 1642 1643 // Use the default. 1644 return MVT::Other; 1645 } 1646 1647 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1648 const MemSDNode *MemNode = cast<MemSDNode>(N); 1649 return MemNode->getMemOperand()->getFlags() & MONoClobber; 1650 } 1651 1652 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) { 1653 return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS || 1654 AS == AMDGPUAS::PRIVATE_ADDRESS; 1655 } 1656 1657 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1658 unsigned DestAS) const { 1659 // Flat -> private/local is a simple truncate. 1660 // Flat -> global is no-op 1661 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1662 return true; 1663 1664 const GCNTargetMachine &TM = 1665 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1666 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 1667 } 1668 1669 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1670 const MemSDNode *MemNode = cast<MemSDNode>(N); 1671 1672 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1673 } 1674 1675 TargetLoweringBase::LegalizeTypeAction 1676 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1677 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 && 1678 VT.getScalarType().bitsLE(MVT::i16)) 1679 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1680 return TargetLoweringBase::getPreferredVectorAction(VT); 1681 } 1682 1683 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1684 Type *Ty) const { 1685 // FIXME: Could be smarter if called for vector constants. 1686 return true; 1687 } 1688 1689 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1690 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1691 switch (Op) { 1692 case ISD::LOAD: 1693 case ISD::STORE: 1694 1695 // These operations are done with 32-bit instructions anyway. 1696 case ISD::AND: 1697 case ISD::OR: 1698 case ISD::XOR: 1699 case ISD::SELECT: 1700 // TODO: Extensions? 1701 return true; 1702 default: 1703 return false; 1704 } 1705 } 1706 1707 // SimplifySetCC uses this function to determine whether or not it should 1708 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1709 if (VT == MVT::i1 && Op == ISD::SETCC) 1710 return false; 1711 1712 return TargetLowering::isTypeDesirableForOp(Op, VT); 1713 } 1714 1715 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1716 const SDLoc &SL, 1717 SDValue Chain, 1718 uint64_t Offset) const { 1719 const DataLayout &DL = DAG.getDataLayout(); 1720 MachineFunction &MF = DAG.getMachineFunction(); 1721 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1722 1723 const ArgDescriptor *InputPtrReg; 1724 const TargetRegisterClass *RC; 1725 LLT ArgTy; 1726 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1727 1728 std::tie(InputPtrReg, RC, ArgTy) = 1729 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1730 1731 // We may not have the kernarg segment argument if we have no kernel 1732 // arguments. 1733 if (!InputPtrReg) 1734 return DAG.getConstant(0, SL, PtrVT); 1735 1736 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1737 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1738 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1739 1740 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset)); 1741 } 1742 1743 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1744 const SDLoc &SL) const { 1745 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1746 FIRST_IMPLICIT); 1747 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1748 } 1749 1750 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1751 const SDLoc &SL, SDValue Val, 1752 bool Signed, 1753 const ISD::InputArg *Arg) const { 1754 // First, if it is a widened vector, narrow it. 1755 if (VT.isVector() && 1756 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1757 EVT NarrowedVT = 1758 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1759 VT.getVectorNumElements()); 1760 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1761 DAG.getConstant(0, SL, MVT::i32)); 1762 } 1763 1764 // Then convert the vector elements or scalar value. 1765 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1766 VT.bitsLT(MemVT)) { 1767 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1768 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1769 } 1770 1771 if (MemVT.isFloatingPoint()) 1772 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1773 else if (Signed) 1774 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1775 else 1776 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1777 1778 return Val; 1779 } 1780 1781 SDValue SITargetLowering::lowerKernargMemParameter( 1782 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1783 uint64_t Offset, Align Alignment, bool Signed, 1784 const ISD::InputArg *Arg) const { 1785 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1786 1787 // Try to avoid using an extload by loading earlier than the argument address, 1788 // and extracting the relevant bits. The load should hopefully be merged with 1789 // the previous argument. 1790 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1791 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1792 int64_t AlignDownOffset = alignDown(Offset, 4); 1793 int64_t OffsetDiff = Offset - AlignDownOffset; 1794 1795 EVT IntVT = MemVT.changeTypeToInteger(); 1796 1797 // TODO: If we passed in the base kernel offset we could have a better 1798 // alignment than 4, but we don't really need it. 1799 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1800 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4), 1801 MachineMemOperand::MODereferenceable | 1802 MachineMemOperand::MOInvariant); 1803 1804 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1805 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1806 1807 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1808 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1809 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1810 1811 1812 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1813 } 1814 1815 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1816 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1817 MachineMemOperand::MODereferenceable | 1818 MachineMemOperand::MOInvariant); 1819 1820 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1821 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1822 } 1823 1824 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1825 const SDLoc &SL, SDValue Chain, 1826 const ISD::InputArg &Arg) const { 1827 MachineFunction &MF = DAG.getMachineFunction(); 1828 MachineFrameInfo &MFI = MF.getFrameInfo(); 1829 1830 if (Arg.Flags.isByVal()) { 1831 unsigned Size = Arg.Flags.getByValSize(); 1832 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1833 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1834 } 1835 1836 unsigned ArgOffset = VA.getLocMemOffset(); 1837 unsigned ArgSize = VA.getValVT().getStoreSize(); 1838 1839 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1840 1841 // Create load nodes to retrieve arguments from the stack. 1842 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1843 SDValue ArgValue; 1844 1845 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1846 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1847 MVT MemVT = VA.getValVT(); 1848 1849 switch (VA.getLocInfo()) { 1850 default: 1851 break; 1852 case CCValAssign::BCvt: 1853 MemVT = VA.getLocVT(); 1854 break; 1855 case CCValAssign::SExt: 1856 ExtType = ISD::SEXTLOAD; 1857 break; 1858 case CCValAssign::ZExt: 1859 ExtType = ISD::ZEXTLOAD; 1860 break; 1861 case CCValAssign::AExt: 1862 ExtType = ISD::EXTLOAD; 1863 break; 1864 } 1865 1866 ArgValue = DAG.getExtLoad( 1867 ExtType, SL, VA.getLocVT(), Chain, FIN, 1868 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1869 MemVT); 1870 return ArgValue; 1871 } 1872 1873 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1874 const SIMachineFunctionInfo &MFI, 1875 EVT VT, 1876 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1877 const ArgDescriptor *Reg; 1878 const TargetRegisterClass *RC; 1879 LLT Ty; 1880 1881 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1882 if (!Reg) { 1883 if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) { 1884 // It's possible for a kernarg intrinsic call to appear in a kernel with 1885 // no allocated segment, in which case we do not add the user sgpr 1886 // argument, so just return null. 1887 return DAG.getConstant(0, SDLoc(), VT); 1888 } 1889 1890 // It's undefined behavior if a function marked with the amdgpu-no-* 1891 // attributes uses the corresponding intrinsic. 1892 return DAG.getUNDEF(VT); 1893 } 1894 1895 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1896 } 1897 1898 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1899 CallingConv::ID CallConv, 1900 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped, 1901 FunctionType *FType, 1902 SIMachineFunctionInfo *Info) { 1903 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1904 const ISD::InputArg *Arg = &Ins[I]; 1905 1906 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1907 "vector type argument should have been split"); 1908 1909 // First check if it's a PS input addr. 1910 if (CallConv == CallingConv::AMDGPU_PS && 1911 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1912 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1913 1914 // Inconveniently only the first part of the split is marked as isSplit, 1915 // so skip to the end. We only want to increment PSInputNum once for the 1916 // entire split argument. 1917 if (Arg->Flags.isSplit()) { 1918 while (!Arg->Flags.isSplitEnd()) { 1919 assert((!Arg->VT.isVector() || 1920 Arg->VT.getScalarSizeInBits() == 16) && 1921 "unexpected vector split in ps argument type"); 1922 if (!SkipArg) 1923 Splits.push_back(*Arg); 1924 Arg = &Ins[++I]; 1925 } 1926 } 1927 1928 if (SkipArg) { 1929 // We can safely skip PS inputs. 1930 Skipped.set(Arg->getOrigArgIndex()); 1931 ++PSInputNum; 1932 continue; 1933 } 1934 1935 Info->markPSInputAllocated(PSInputNum); 1936 if (Arg->Used) 1937 Info->markPSInputEnabled(PSInputNum); 1938 1939 ++PSInputNum; 1940 } 1941 1942 Splits.push_back(*Arg); 1943 } 1944 } 1945 1946 // Allocate special inputs passed in VGPRs. 1947 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1948 MachineFunction &MF, 1949 const SIRegisterInfo &TRI, 1950 SIMachineFunctionInfo &Info) const { 1951 const LLT S32 = LLT::scalar(32); 1952 MachineRegisterInfo &MRI = MF.getRegInfo(); 1953 1954 if (Info.hasWorkItemIDX()) { 1955 Register Reg = AMDGPU::VGPR0; 1956 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1957 1958 CCInfo.AllocateReg(Reg); 1959 unsigned Mask = (Subtarget->hasPackedTID() && 1960 Info.hasWorkItemIDY()) ? 0x3ff : ~0u; 1961 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1962 } 1963 1964 if (Info.hasWorkItemIDY()) { 1965 assert(Info.hasWorkItemIDX()); 1966 if (Subtarget->hasPackedTID()) { 1967 Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1968 0x3ff << 10)); 1969 } else { 1970 unsigned Reg = AMDGPU::VGPR1; 1971 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1972 1973 CCInfo.AllocateReg(Reg); 1974 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1975 } 1976 } 1977 1978 if (Info.hasWorkItemIDZ()) { 1979 assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY()); 1980 if (Subtarget->hasPackedTID()) { 1981 Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1982 0x3ff << 20)); 1983 } else { 1984 unsigned Reg = AMDGPU::VGPR2; 1985 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1986 1987 CCInfo.AllocateReg(Reg); 1988 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1989 } 1990 } 1991 } 1992 1993 // Try to allocate a VGPR at the end of the argument list, or if no argument 1994 // VGPRs are left allocating a stack slot. 1995 // If \p Mask is is given it indicates bitfield position in the register. 1996 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1997 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1998 ArgDescriptor Arg = ArgDescriptor()) { 1999 if (Arg.isSet()) 2000 return ArgDescriptor::createArg(Arg, Mask); 2001 2002 ArrayRef<MCPhysReg> ArgVGPRs 2003 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 2004 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 2005 if (RegIdx == ArgVGPRs.size()) { 2006 // Spill to stack required. 2007 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 2008 2009 return ArgDescriptor::createStack(Offset, Mask); 2010 } 2011 2012 unsigned Reg = ArgVGPRs[RegIdx]; 2013 Reg = CCInfo.AllocateReg(Reg); 2014 assert(Reg != AMDGPU::NoRegister); 2015 2016 MachineFunction &MF = CCInfo.getMachineFunction(); 2017 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 2018 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 2019 return ArgDescriptor::createRegister(Reg, Mask); 2020 } 2021 2022 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 2023 const TargetRegisterClass *RC, 2024 unsigned NumArgRegs) { 2025 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 2026 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 2027 if (RegIdx == ArgSGPRs.size()) 2028 report_fatal_error("ran out of SGPRs for arguments"); 2029 2030 unsigned Reg = ArgSGPRs[RegIdx]; 2031 Reg = CCInfo.AllocateReg(Reg); 2032 assert(Reg != AMDGPU::NoRegister); 2033 2034 MachineFunction &MF = CCInfo.getMachineFunction(); 2035 MF.addLiveIn(Reg, RC); 2036 return ArgDescriptor::createRegister(Reg); 2037 } 2038 2039 // If this has a fixed position, we still should allocate the register in the 2040 // CCInfo state. Technically we could get away with this for values passed 2041 // outside of the normal argument range. 2042 static void allocateFixedSGPRInputImpl(CCState &CCInfo, 2043 const TargetRegisterClass *RC, 2044 MCRegister Reg) { 2045 Reg = CCInfo.AllocateReg(Reg); 2046 assert(Reg != AMDGPU::NoRegister); 2047 MachineFunction &MF = CCInfo.getMachineFunction(); 2048 MF.addLiveIn(Reg, RC); 2049 } 2050 2051 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) { 2052 if (Arg) { 2053 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 2054 Arg.getRegister()); 2055 } else 2056 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 2057 } 2058 2059 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) { 2060 if (Arg) { 2061 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 2062 Arg.getRegister()); 2063 } else 2064 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 2065 } 2066 2067 /// Allocate implicit function VGPR arguments at the end of allocated user 2068 /// arguments. 2069 void SITargetLowering::allocateSpecialInputVGPRs( 2070 CCState &CCInfo, MachineFunction &MF, 2071 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 2072 const unsigned Mask = 0x3ff; 2073 ArgDescriptor Arg; 2074 2075 if (Info.hasWorkItemIDX()) { 2076 Arg = allocateVGPR32Input(CCInfo, Mask); 2077 Info.setWorkItemIDX(Arg); 2078 } 2079 2080 if (Info.hasWorkItemIDY()) { 2081 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 2082 Info.setWorkItemIDY(Arg); 2083 } 2084 2085 if (Info.hasWorkItemIDZ()) 2086 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 2087 } 2088 2089 /// Allocate implicit function VGPR arguments in fixed registers. 2090 void SITargetLowering::allocateSpecialInputVGPRsFixed( 2091 CCState &CCInfo, MachineFunction &MF, 2092 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 2093 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 2094 if (!Reg) 2095 report_fatal_error("failed to allocated VGPR for implicit arguments"); 2096 2097 const unsigned Mask = 0x3ff; 2098 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 2099 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 2100 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 2101 } 2102 2103 void SITargetLowering::allocateSpecialInputSGPRs( 2104 CCState &CCInfo, 2105 MachineFunction &MF, 2106 const SIRegisterInfo &TRI, 2107 SIMachineFunctionInfo &Info) const { 2108 auto &ArgInfo = Info.getArgInfo(); 2109 2110 // TODO: Unify handling with private memory pointers. 2111 if (Info.hasDispatchPtr()) 2112 allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr); 2113 2114 if (Info.hasQueuePtr()) 2115 allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr); 2116 2117 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 2118 // constant offset from the kernarg segment. 2119 if (Info.hasImplicitArgPtr()) 2120 allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr); 2121 2122 if (Info.hasDispatchID()) 2123 allocateSGPR64Input(CCInfo, ArgInfo.DispatchID); 2124 2125 // flat_scratch_init is not applicable for non-kernel functions. 2126 2127 if (Info.hasWorkGroupIDX()) 2128 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX); 2129 2130 if (Info.hasWorkGroupIDY()) 2131 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY); 2132 2133 if (Info.hasWorkGroupIDZ()) 2134 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ); 2135 } 2136 2137 // Allocate special inputs passed in user SGPRs. 2138 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 2139 MachineFunction &MF, 2140 const SIRegisterInfo &TRI, 2141 SIMachineFunctionInfo &Info) const { 2142 if (Info.hasImplicitBufferPtr()) { 2143 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 2144 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 2145 CCInfo.AllocateReg(ImplicitBufferPtrReg); 2146 } 2147 2148 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 2149 if (Info.hasPrivateSegmentBuffer()) { 2150 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 2151 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 2152 CCInfo.AllocateReg(PrivateSegmentBufferReg); 2153 } 2154 2155 if (Info.hasDispatchPtr()) { 2156 Register DispatchPtrReg = Info.addDispatchPtr(TRI); 2157 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 2158 CCInfo.AllocateReg(DispatchPtrReg); 2159 } 2160 2161 if (Info.hasQueuePtr()) { 2162 Register QueuePtrReg = Info.addQueuePtr(TRI); 2163 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 2164 CCInfo.AllocateReg(QueuePtrReg); 2165 } 2166 2167 if (Info.hasKernargSegmentPtr()) { 2168 MachineRegisterInfo &MRI = MF.getRegInfo(); 2169 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 2170 CCInfo.AllocateReg(InputPtrReg); 2171 2172 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 2173 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 2174 } 2175 2176 if (Info.hasDispatchID()) { 2177 Register DispatchIDReg = Info.addDispatchID(TRI); 2178 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 2179 CCInfo.AllocateReg(DispatchIDReg); 2180 } 2181 2182 if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) { 2183 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI); 2184 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 2185 CCInfo.AllocateReg(FlatScratchInitReg); 2186 } 2187 2188 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 2189 // these from the dispatch pointer. 2190 } 2191 2192 // Allocate special input registers that are initialized per-wave. 2193 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 2194 MachineFunction &MF, 2195 SIMachineFunctionInfo &Info, 2196 CallingConv::ID CallConv, 2197 bool IsShader) const { 2198 if (Info.hasWorkGroupIDX()) { 2199 Register Reg = Info.addWorkGroupIDX(); 2200 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2201 CCInfo.AllocateReg(Reg); 2202 } 2203 2204 if (Info.hasWorkGroupIDY()) { 2205 Register Reg = Info.addWorkGroupIDY(); 2206 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2207 CCInfo.AllocateReg(Reg); 2208 } 2209 2210 if (Info.hasWorkGroupIDZ()) { 2211 Register Reg = Info.addWorkGroupIDZ(); 2212 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2213 CCInfo.AllocateReg(Reg); 2214 } 2215 2216 if (Info.hasWorkGroupInfo()) { 2217 Register Reg = Info.addWorkGroupInfo(); 2218 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2219 CCInfo.AllocateReg(Reg); 2220 } 2221 2222 if (Info.hasPrivateSegmentWaveByteOffset()) { 2223 // Scratch wave offset passed in system SGPR. 2224 unsigned PrivateSegmentWaveByteOffsetReg; 2225 2226 if (IsShader) { 2227 PrivateSegmentWaveByteOffsetReg = 2228 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 2229 2230 // This is true if the scratch wave byte offset doesn't have a fixed 2231 // location. 2232 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 2233 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 2234 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 2235 } 2236 } else 2237 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 2238 2239 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 2240 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 2241 } 2242 } 2243 2244 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2245 MachineFunction &MF, 2246 const SIRegisterInfo &TRI, 2247 SIMachineFunctionInfo &Info) { 2248 // Now that we've figured out where the scratch register inputs are, see if 2249 // should reserve the arguments and use them directly. 2250 MachineFrameInfo &MFI = MF.getFrameInfo(); 2251 bool HasStackObjects = MFI.hasStackObjects(); 2252 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2253 2254 // Record that we know we have non-spill stack objects so we don't need to 2255 // check all stack objects later. 2256 if (HasStackObjects) 2257 Info.setHasNonSpillStackObjects(true); 2258 2259 // Everything live out of a block is spilled with fast regalloc, so it's 2260 // almost certain that spilling will be required. 2261 if (TM.getOptLevel() == CodeGenOpt::None) 2262 HasStackObjects = true; 2263 2264 // For now assume stack access is needed in any callee functions, so we need 2265 // the scratch registers to pass in. 2266 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2267 2268 if (!ST.enableFlatScratch()) { 2269 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2270 // If we have stack objects, we unquestionably need the private buffer 2271 // resource. For the Code Object V2 ABI, this will be the first 4 user 2272 // SGPR inputs. We can reserve those and use them directly. 2273 2274 Register PrivateSegmentBufferReg = 2275 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2276 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2277 } else { 2278 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2279 // We tentatively reserve the last registers (skipping the last registers 2280 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2281 // we'll replace these with the ones immediately after those which were 2282 // really allocated. In the prologue copies will be inserted from the 2283 // argument to these reserved registers. 2284 2285 // Without HSA, relocations are used for the scratch pointer and the 2286 // buffer resource setup is always inserted in the prologue. Scratch wave 2287 // offset is still in an input SGPR. 2288 Info.setScratchRSrcReg(ReservedBufferReg); 2289 } 2290 } 2291 2292 MachineRegisterInfo &MRI = MF.getRegInfo(); 2293 2294 // For entry functions we have to set up the stack pointer if we use it, 2295 // whereas non-entry functions get this "for free". This means there is no 2296 // intrinsic advantage to using S32 over S34 in cases where we do not have 2297 // calls but do need a frame pointer (i.e. if we are requested to have one 2298 // because frame pointer elimination is disabled). To keep things simple we 2299 // only ever use S32 as the call ABI stack pointer, and so using it does not 2300 // imply we need a separate frame pointer. 2301 // 2302 // Try to use s32 as the SP, but move it if it would interfere with input 2303 // arguments. This won't work with calls though. 2304 // 2305 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2306 // registers. 2307 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2308 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2309 } else { 2310 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2311 2312 if (MFI.hasCalls()) 2313 report_fatal_error("call in graphics shader with too many input SGPRs"); 2314 2315 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2316 if (!MRI.isLiveIn(Reg)) { 2317 Info.setStackPtrOffsetReg(Reg); 2318 break; 2319 } 2320 } 2321 2322 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2323 report_fatal_error("failed to find register for SP"); 2324 } 2325 2326 // hasFP should be accurate for entry functions even before the frame is 2327 // finalized, because it does not rely on the known stack size, only 2328 // properties like whether variable sized objects are present. 2329 if (ST.getFrameLowering()->hasFP(MF)) { 2330 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2331 } 2332 } 2333 2334 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2335 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2336 return !Info->isEntryFunction(); 2337 } 2338 2339 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2340 2341 } 2342 2343 void SITargetLowering::insertCopiesSplitCSR( 2344 MachineBasicBlock *Entry, 2345 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2346 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2347 2348 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2349 if (!IStart) 2350 return; 2351 2352 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2353 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2354 MachineBasicBlock::iterator MBBI = Entry->begin(); 2355 for (const MCPhysReg *I = IStart; *I; ++I) { 2356 const TargetRegisterClass *RC = nullptr; 2357 if (AMDGPU::SReg_64RegClass.contains(*I)) 2358 RC = &AMDGPU::SGPR_64RegClass; 2359 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2360 RC = &AMDGPU::SGPR_32RegClass; 2361 else 2362 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2363 2364 Register NewVR = MRI->createVirtualRegister(RC); 2365 // Create copy from CSR to a virtual register. 2366 Entry->addLiveIn(*I); 2367 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2368 .addReg(*I); 2369 2370 // Insert the copy-back instructions right before the terminator. 2371 for (auto *Exit : Exits) 2372 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2373 TII->get(TargetOpcode::COPY), *I) 2374 .addReg(NewVR); 2375 } 2376 } 2377 2378 SDValue SITargetLowering::LowerFormalArguments( 2379 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2380 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2381 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2382 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2383 2384 MachineFunction &MF = DAG.getMachineFunction(); 2385 const Function &Fn = MF.getFunction(); 2386 FunctionType *FType = MF.getFunction().getFunctionType(); 2387 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2388 2389 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) { 2390 DiagnosticInfoUnsupported NoGraphicsHSA( 2391 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2392 DAG.getContext()->diagnose(NoGraphicsHSA); 2393 return DAG.getEntryNode(); 2394 } 2395 2396 Info->allocateModuleLDSGlobal(Fn.getParent()); 2397 2398 SmallVector<ISD::InputArg, 16> Splits; 2399 SmallVector<CCValAssign, 16> ArgLocs; 2400 BitVector Skipped(Ins.size()); 2401 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2402 *DAG.getContext()); 2403 2404 bool IsGraphics = AMDGPU::isGraphics(CallConv); 2405 bool IsKernel = AMDGPU::isKernel(CallConv); 2406 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2407 2408 if (IsGraphics) { 2409 assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && 2410 (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && 2411 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2412 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2413 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2414 !Info->hasWorkItemIDZ()); 2415 } 2416 2417 if (CallConv == CallingConv::AMDGPU_PS) { 2418 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2419 2420 // At least one interpolation mode must be enabled or else the GPU will 2421 // hang. 2422 // 2423 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2424 // set PSInputAddr, the user wants to enable some bits after the compilation 2425 // based on run-time states. Since we can't know what the final PSInputEna 2426 // will look like, so we shouldn't do anything here and the user should take 2427 // responsibility for the correct programming. 2428 // 2429 // Otherwise, the following restrictions apply: 2430 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2431 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2432 // enabled too. 2433 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2434 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) { 2435 CCInfo.AllocateReg(AMDGPU::VGPR0); 2436 CCInfo.AllocateReg(AMDGPU::VGPR1); 2437 Info->markPSInputAllocated(0); 2438 Info->markPSInputEnabled(0); 2439 } 2440 if (Subtarget->isAmdPalOS()) { 2441 // For isAmdPalOS, the user does not enable some bits after compilation 2442 // based on run-time states; the register values being generated here are 2443 // the final ones set in hardware. Therefore we need to apply the 2444 // workaround to PSInputAddr and PSInputEnable together. (The case where 2445 // a bit is set in PSInputAddr but not PSInputEnable is where the 2446 // frontend set up an input arg for a particular interpolation mode, but 2447 // nothing uses that input arg. Really we should have an earlier pass 2448 // that removes such an arg.) 2449 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2450 if ((PsInputBits & 0x7F) == 0 || 2451 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1))) 2452 Info->markPSInputEnabled( 2453 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2454 } 2455 } else if (IsKernel) { 2456 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2457 } else { 2458 Splits.append(Ins.begin(), Ins.end()); 2459 } 2460 2461 if (IsEntryFunc) { 2462 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2463 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2464 } else if (!IsGraphics) { 2465 // For the fixed ABI, pass workitem IDs in the last argument register. 2466 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2467 } 2468 2469 if (IsKernel) { 2470 analyzeFormalArgumentsCompute(CCInfo, Ins); 2471 } else { 2472 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2473 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2474 } 2475 2476 SmallVector<SDValue, 16> Chains; 2477 2478 // FIXME: This is the minimum kernel argument alignment. We should improve 2479 // this to the maximum alignment of the arguments. 2480 // 2481 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2482 // kern arg offset. 2483 const Align KernelArgBaseAlign = Align(16); 2484 2485 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2486 const ISD::InputArg &Arg = Ins[i]; 2487 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2488 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2489 continue; 2490 } 2491 2492 CCValAssign &VA = ArgLocs[ArgIdx++]; 2493 MVT VT = VA.getLocVT(); 2494 2495 if (IsEntryFunc && VA.isMemLoc()) { 2496 VT = Ins[i].VT; 2497 EVT MemVT = VA.getLocVT(); 2498 2499 const uint64_t Offset = VA.getLocMemOffset(); 2500 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2501 2502 if (Arg.Flags.isByRef()) { 2503 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset); 2504 2505 const GCNTargetMachine &TM = 2506 static_cast<const GCNTargetMachine &>(getTargetMachine()); 2507 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS, 2508 Arg.Flags.getPointerAddrSpace())) { 2509 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS, 2510 Arg.Flags.getPointerAddrSpace()); 2511 } 2512 2513 InVals.push_back(Ptr); 2514 continue; 2515 } 2516 2517 SDValue Arg = lowerKernargMemParameter( 2518 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]); 2519 Chains.push_back(Arg.getValue(1)); 2520 2521 auto *ParamTy = 2522 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2523 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2524 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2525 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2526 // On SI local pointers are just offsets into LDS, so they are always 2527 // less than 16-bits. On CI and newer they could potentially be 2528 // real pointers, so we can't guarantee their size. 2529 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2530 DAG.getValueType(MVT::i16)); 2531 } 2532 2533 InVals.push_back(Arg); 2534 continue; 2535 } else if (!IsEntryFunc && VA.isMemLoc()) { 2536 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2537 InVals.push_back(Val); 2538 if (!Arg.Flags.isByVal()) 2539 Chains.push_back(Val.getValue(1)); 2540 continue; 2541 } 2542 2543 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2544 2545 Register Reg = VA.getLocReg(); 2546 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2547 EVT ValVT = VA.getValVT(); 2548 2549 Reg = MF.addLiveIn(Reg, RC); 2550 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2551 2552 if (Arg.Flags.isSRet()) { 2553 // The return object should be reasonably addressable. 2554 2555 // FIXME: This helps when the return is a real sret. If it is a 2556 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2557 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2558 unsigned NumBits 2559 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2560 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2561 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2562 } 2563 2564 // If this is an 8 or 16-bit value, it is really passed promoted 2565 // to 32 bits. Insert an assert[sz]ext to capture this, then 2566 // truncate to the right size. 2567 switch (VA.getLocInfo()) { 2568 case CCValAssign::Full: 2569 break; 2570 case CCValAssign::BCvt: 2571 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2572 break; 2573 case CCValAssign::SExt: 2574 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2575 DAG.getValueType(ValVT)); 2576 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2577 break; 2578 case CCValAssign::ZExt: 2579 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2580 DAG.getValueType(ValVT)); 2581 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2582 break; 2583 case CCValAssign::AExt: 2584 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2585 break; 2586 default: 2587 llvm_unreachable("Unknown loc info!"); 2588 } 2589 2590 InVals.push_back(Val); 2591 } 2592 2593 // Start adding system SGPRs. 2594 if (IsEntryFunc) { 2595 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics); 2596 } else { 2597 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2598 if (!IsGraphics) 2599 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2600 } 2601 2602 auto &ArgUsageInfo = 2603 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2604 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2605 2606 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2607 Info->setBytesInStackArgArea(StackArgSize); 2608 2609 return Chains.empty() ? Chain : 2610 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2611 } 2612 2613 // TODO: If return values can't fit in registers, we should return as many as 2614 // possible in registers before passing on stack. 2615 bool SITargetLowering::CanLowerReturn( 2616 CallingConv::ID CallConv, 2617 MachineFunction &MF, bool IsVarArg, 2618 const SmallVectorImpl<ISD::OutputArg> &Outs, 2619 LLVMContext &Context) const { 2620 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2621 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2622 // for shaders. Vector types should be explicitly handled by CC. 2623 if (AMDGPU::isEntryFunctionCC(CallConv)) 2624 return true; 2625 2626 SmallVector<CCValAssign, 16> RVLocs; 2627 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2628 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2629 } 2630 2631 SDValue 2632 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2633 bool isVarArg, 2634 const SmallVectorImpl<ISD::OutputArg> &Outs, 2635 const SmallVectorImpl<SDValue> &OutVals, 2636 const SDLoc &DL, SelectionDAG &DAG) const { 2637 MachineFunction &MF = DAG.getMachineFunction(); 2638 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2639 2640 if (AMDGPU::isKernel(CallConv)) { 2641 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2642 OutVals, DL, DAG); 2643 } 2644 2645 bool IsShader = AMDGPU::isShader(CallConv); 2646 2647 Info->setIfReturnsVoid(Outs.empty()); 2648 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2649 2650 // CCValAssign - represent the assignment of the return value to a location. 2651 SmallVector<CCValAssign, 48> RVLocs; 2652 SmallVector<ISD::OutputArg, 48> Splits; 2653 2654 // CCState - Info about the registers and stack slots. 2655 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2656 *DAG.getContext()); 2657 2658 // Analyze outgoing return values. 2659 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2660 2661 SDValue Flag; 2662 SmallVector<SDValue, 48> RetOps; 2663 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2664 2665 // Add return address for callable functions. 2666 if (!Info->isEntryFunction()) { 2667 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2668 SDValue ReturnAddrReg = CreateLiveInRegister( 2669 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2670 2671 SDValue ReturnAddrVirtualReg = 2672 DAG.getRegister(MF.getRegInfo().createVirtualRegister( 2673 CallConv != CallingConv::AMDGPU_Gfx 2674 ? &AMDGPU::CCR_SGPR_64RegClass 2675 : &AMDGPU::Gfx_CCR_SGPR_64RegClass), 2676 MVT::i64); 2677 Chain = 2678 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2679 Flag = Chain.getValue(1); 2680 RetOps.push_back(ReturnAddrVirtualReg); 2681 } 2682 2683 // Copy the result values into the output registers. 2684 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2685 ++I, ++RealRVLocIdx) { 2686 CCValAssign &VA = RVLocs[I]; 2687 assert(VA.isRegLoc() && "Can only return in registers!"); 2688 // TODO: Partially return in registers if return values don't fit. 2689 SDValue Arg = OutVals[RealRVLocIdx]; 2690 2691 // Copied from other backends. 2692 switch (VA.getLocInfo()) { 2693 case CCValAssign::Full: 2694 break; 2695 case CCValAssign::BCvt: 2696 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2697 break; 2698 case CCValAssign::SExt: 2699 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2700 break; 2701 case CCValAssign::ZExt: 2702 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2703 break; 2704 case CCValAssign::AExt: 2705 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2706 break; 2707 default: 2708 llvm_unreachable("Unknown loc info!"); 2709 } 2710 2711 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2712 Flag = Chain.getValue(1); 2713 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2714 } 2715 2716 // FIXME: Does sret work properly? 2717 if (!Info->isEntryFunction()) { 2718 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2719 const MCPhysReg *I = 2720 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2721 if (I) { 2722 for (; *I; ++I) { 2723 if (AMDGPU::SReg_64RegClass.contains(*I)) 2724 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2725 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2726 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2727 else 2728 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2729 } 2730 } 2731 } 2732 2733 // Update chain and glue. 2734 RetOps[0] = Chain; 2735 if (Flag.getNode()) 2736 RetOps.push_back(Flag); 2737 2738 unsigned Opc = AMDGPUISD::ENDPGM; 2739 if (!IsWaveEnd) { 2740 if (IsShader) 2741 Opc = AMDGPUISD::RETURN_TO_EPILOG; 2742 else if (CallConv == CallingConv::AMDGPU_Gfx) 2743 Opc = AMDGPUISD::RET_GFX_FLAG; 2744 else 2745 Opc = AMDGPUISD::RET_FLAG; 2746 } 2747 2748 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2749 } 2750 2751 SDValue SITargetLowering::LowerCallResult( 2752 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2753 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2754 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2755 SDValue ThisVal) const { 2756 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2757 2758 // Assign locations to each value returned by this call. 2759 SmallVector<CCValAssign, 16> RVLocs; 2760 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2761 *DAG.getContext()); 2762 CCInfo.AnalyzeCallResult(Ins, RetCC); 2763 2764 // Copy all of the result registers out of their specified physreg. 2765 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2766 CCValAssign VA = RVLocs[i]; 2767 SDValue Val; 2768 2769 if (VA.isRegLoc()) { 2770 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2771 Chain = Val.getValue(1); 2772 InFlag = Val.getValue(2); 2773 } else if (VA.isMemLoc()) { 2774 report_fatal_error("TODO: return values in memory"); 2775 } else 2776 llvm_unreachable("unknown argument location type"); 2777 2778 switch (VA.getLocInfo()) { 2779 case CCValAssign::Full: 2780 break; 2781 case CCValAssign::BCvt: 2782 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2783 break; 2784 case CCValAssign::ZExt: 2785 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2786 DAG.getValueType(VA.getValVT())); 2787 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2788 break; 2789 case CCValAssign::SExt: 2790 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2791 DAG.getValueType(VA.getValVT())); 2792 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2793 break; 2794 case CCValAssign::AExt: 2795 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2796 break; 2797 default: 2798 llvm_unreachable("Unknown loc info!"); 2799 } 2800 2801 InVals.push_back(Val); 2802 } 2803 2804 return Chain; 2805 } 2806 2807 // Add code to pass special inputs required depending on used features separate 2808 // from the explicit user arguments present in the IR. 2809 void SITargetLowering::passSpecialInputs( 2810 CallLoweringInfo &CLI, 2811 CCState &CCInfo, 2812 const SIMachineFunctionInfo &Info, 2813 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2814 SmallVectorImpl<SDValue> &MemOpChains, 2815 SDValue Chain) const { 2816 // If we don't have a call site, this was a call inserted by 2817 // legalization. These can never use special inputs. 2818 if (!CLI.CB) 2819 return; 2820 2821 SelectionDAG &DAG = CLI.DAG; 2822 const SDLoc &DL = CLI.DL; 2823 const Function &F = DAG.getMachineFunction().getFunction(); 2824 2825 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2826 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2827 2828 const AMDGPUFunctionArgInfo *CalleeArgInfo 2829 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2830 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2831 auto &ArgUsageInfo = 2832 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2833 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2834 } 2835 2836 // TODO: Unify with private memory register handling. This is complicated by 2837 // the fact that at least in kernels, the input argument is not necessarily 2838 // in the same location as the input. 2839 static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue, 2840 StringLiteral> ImplicitAttrs[] = { 2841 {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"}, 2842 {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" }, 2843 {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"}, 2844 {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"}, 2845 {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"}, 2846 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"}, 2847 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"} 2848 }; 2849 2850 for (auto Attr : ImplicitAttrs) { 2851 const ArgDescriptor *OutgoingArg; 2852 const TargetRegisterClass *ArgRC; 2853 LLT ArgTy; 2854 2855 AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first; 2856 2857 // If the callee does not use the attribute value, skip copying the value. 2858 if (CLI.CB->hasFnAttr(Attr.second)) 2859 continue; 2860 2861 std::tie(OutgoingArg, ArgRC, ArgTy) = 2862 CalleeArgInfo->getPreloadedValue(InputID); 2863 if (!OutgoingArg) 2864 continue; 2865 2866 const ArgDescriptor *IncomingArg; 2867 const TargetRegisterClass *IncomingArgRC; 2868 LLT Ty; 2869 std::tie(IncomingArg, IncomingArgRC, Ty) = 2870 CallerArgInfo.getPreloadedValue(InputID); 2871 assert(IncomingArgRC == ArgRC); 2872 2873 // All special arguments are ints for now. 2874 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2875 SDValue InputReg; 2876 2877 if (IncomingArg) { 2878 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2879 } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) { 2880 // The implicit arg ptr is special because it doesn't have a corresponding 2881 // input for kernels, and is computed from the kernarg segment pointer. 2882 InputReg = getImplicitArgPtr(DAG, DL); 2883 } else { 2884 // We may have proven the input wasn't needed, although the ABI is 2885 // requiring it. We just need to allocate the register appropriately. 2886 InputReg = DAG.getUNDEF(ArgVT); 2887 } 2888 2889 if (OutgoingArg->isRegister()) { 2890 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2891 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2892 report_fatal_error("failed to allocate implicit input argument"); 2893 } else { 2894 unsigned SpecialArgOffset = 2895 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2896 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2897 SpecialArgOffset); 2898 MemOpChains.push_back(ArgStore); 2899 } 2900 } 2901 2902 // Pack workitem IDs into a single register or pass it as is if already 2903 // packed. 2904 const ArgDescriptor *OutgoingArg; 2905 const TargetRegisterClass *ArgRC; 2906 LLT Ty; 2907 2908 std::tie(OutgoingArg, ArgRC, Ty) = 2909 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2910 if (!OutgoingArg) 2911 std::tie(OutgoingArg, ArgRC, Ty) = 2912 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2913 if (!OutgoingArg) 2914 std::tie(OutgoingArg, ArgRC, Ty) = 2915 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2916 if (!OutgoingArg) 2917 return; 2918 2919 const ArgDescriptor *IncomingArgX = std::get<0>( 2920 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2921 const ArgDescriptor *IncomingArgY = std::get<0>( 2922 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2923 const ArgDescriptor *IncomingArgZ = std::get<0>( 2924 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2925 2926 SDValue InputReg; 2927 SDLoc SL; 2928 2929 const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x"); 2930 const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y"); 2931 const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z"); 2932 2933 // If incoming ids are not packed we need to pack them. 2934 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX && 2935 NeedWorkItemIDX) { 2936 if (Subtarget->getMaxWorkitemID(F, 0) != 0) { 2937 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2938 } else { 2939 InputReg = DAG.getConstant(0, DL, MVT::i32); 2940 } 2941 } 2942 2943 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY && 2944 NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) { 2945 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2946 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2947 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2948 InputReg = InputReg.getNode() ? 2949 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2950 } 2951 2952 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ && 2953 NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) { 2954 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2955 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2956 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2957 InputReg = InputReg.getNode() ? 2958 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2959 } 2960 2961 if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) { 2962 if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) { 2963 // We're in a situation where the outgoing function requires the workitem 2964 // ID, but the calling function does not have it (e.g a graphics function 2965 // calling a C calling convention function). This is illegal, but we need 2966 // to produce something. 2967 InputReg = DAG.getUNDEF(MVT::i32); 2968 } else { 2969 // Workitem ids are already packed, any of present incoming arguments 2970 // will carry all required fields. 2971 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2972 IncomingArgX ? *IncomingArgX : 2973 IncomingArgY ? *IncomingArgY : 2974 *IncomingArgZ, ~0u); 2975 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2976 } 2977 } 2978 2979 if (OutgoingArg->isRegister()) { 2980 if (InputReg) 2981 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2982 2983 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2984 } else { 2985 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2986 if (InputReg) { 2987 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2988 SpecialArgOffset); 2989 MemOpChains.push_back(ArgStore); 2990 } 2991 } 2992 } 2993 2994 static bool canGuaranteeTCO(CallingConv::ID CC) { 2995 return CC == CallingConv::Fast; 2996 } 2997 2998 /// Return true if we might ever do TCO for calls with this calling convention. 2999 static bool mayTailCallThisCC(CallingConv::ID CC) { 3000 switch (CC) { 3001 case CallingConv::C: 3002 case CallingConv::AMDGPU_Gfx: 3003 return true; 3004 default: 3005 return canGuaranteeTCO(CC); 3006 } 3007 } 3008 3009 bool SITargetLowering::isEligibleForTailCallOptimization( 3010 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 3011 const SmallVectorImpl<ISD::OutputArg> &Outs, 3012 const SmallVectorImpl<SDValue> &OutVals, 3013 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 3014 if (!mayTailCallThisCC(CalleeCC)) 3015 return false; 3016 3017 // For a divergent call target, we need to do a waterfall loop over the 3018 // possible callees which precludes us from using a simple jump. 3019 if (Callee->isDivergent()) 3020 return false; 3021 3022 MachineFunction &MF = DAG.getMachineFunction(); 3023 const Function &CallerF = MF.getFunction(); 3024 CallingConv::ID CallerCC = CallerF.getCallingConv(); 3025 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3026 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 3027 3028 // Kernels aren't callable, and don't have a live in return address so it 3029 // doesn't make sense to do a tail call with entry functions. 3030 if (!CallerPreserved) 3031 return false; 3032 3033 bool CCMatch = CallerCC == CalleeCC; 3034 3035 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 3036 if (canGuaranteeTCO(CalleeCC) && CCMatch) 3037 return true; 3038 return false; 3039 } 3040 3041 // TODO: Can we handle var args? 3042 if (IsVarArg) 3043 return false; 3044 3045 for (const Argument &Arg : CallerF.args()) { 3046 if (Arg.hasByValAttr()) 3047 return false; 3048 } 3049 3050 LLVMContext &Ctx = *DAG.getContext(); 3051 3052 // Check that the call results are passed in the same way. 3053 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 3054 CCAssignFnForCall(CalleeCC, IsVarArg), 3055 CCAssignFnForCall(CallerCC, IsVarArg))) 3056 return false; 3057 3058 // The callee has to preserve all registers the caller needs to preserve. 3059 if (!CCMatch) { 3060 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 3061 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 3062 return false; 3063 } 3064 3065 // Nothing more to check if the callee is taking no arguments. 3066 if (Outs.empty()) 3067 return true; 3068 3069 SmallVector<CCValAssign, 16> ArgLocs; 3070 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 3071 3072 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 3073 3074 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 3075 // If the stack arguments for this call do not fit into our own save area then 3076 // the call cannot be made tail. 3077 // TODO: Is this really necessary? 3078 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 3079 return false; 3080 3081 const MachineRegisterInfo &MRI = MF.getRegInfo(); 3082 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 3083 } 3084 3085 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 3086 if (!CI->isTailCall()) 3087 return false; 3088 3089 const Function *ParentFn = CI->getParent()->getParent(); 3090 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 3091 return false; 3092 return true; 3093 } 3094 3095 // The wave scratch offset register is used as the global base pointer. 3096 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 3097 SmallVectorImpl<SDValue> &InVals) const { 3098 SelectionDAG &DAG = CLI.DAG; 3099 const SDLoc &DL = CLI.DL; 3100 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 3101 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 3102 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 3103 SDValue Chain = CLI.Chain; 3104 SDValue Callee = CLI.Callee; 3105 bool &IsTailCall = CLI.IsTailCall; 3106 CallingConv::ID CallConv = CLI.CallConv; 3107 bool IsVarArg = CLI.IsVarArg; 3108 bool IsSibCall = false; 3109 bool IsThisReturn = false; 3110 MachineFunction &MF = DAG.getMachineFunction(); 3111 3112 if (Callee.isUndef() || isNullConstant(Callee)) { 3113 if (!CLI.IsTailCall) { 3114 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 3115 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 3116 } 3117 3118 return Chain; 3119 } 3120 3121 if (IsVarArg) { 3122 return lowerUnhandledCall(CLI, InVals, 3123 "unsupported call to variadic function "); 3124 } 3125 3126 if (!CLI.CB) 3127 report_fatal_error("unsupported libcall legalization"); 3128 3129 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 3130 return lowerUnhandledCall(CLI, InVals, 3131 "unsupported required tail call to function "); 3132 } 3133 3134 if (AMDGPU::isShader(CallConv)) { 3135 // Note the issue is with the CC of the called function, not of the call 3136 // itself. 3137 return lowerUnhandledCall(CLI, InVals, 3138 "unsupported call to a shader function "); 3139 } 3140 3141 if (AMDGPU::isShader(MF.getFunction().getCallingConv()) && 3142 CallConv != CallingConv::AMDGPU_Gfx) { 3143 // Only allow calls with specific calling conventions. 3144 return lowerUnhandledCall(CLI, InVals, 3145 "unsupported calling convention for call from " 3146 "graphics shader of function "); 3147 } 3148 3149 if (IsTailCall) { 3150 IsTailCall = isEligibleForTailCallOptimization( 3151 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 3152 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 3153 report_fatal_error("failed to perform tail call elimination on a call " 3154 "site marked musttail"); 3155 } 3156 3157 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 3158 3159 // A sibling call is one where we're under the usual C ABI and not planning 3160 // to change that but can still do a tail call: 3161 if (!TailCallOpt && IsTailCall) 3162 IsSibCall = true; 3163 3164 if (IsTailCall) 3165 ++NumTailCalls; 3166 } 3167 3168 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3169 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3170 SmallVector<SDValue, 8> MemOpChains; 3171 3172 // Analyze operands of the call, assigning locations to each operand. 3173 SmallVector<CCValAssign, 16> ArgLocs; 3174 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 3175 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 3176 3177 if (CallConv != CallingConv::AMDGPU_Gfx) { 3178 // With a fixed ABI, allocate fixed registers before user arguments. 3179 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3180 } 3181 3182 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 3183 3184 // Get a count of how many bytes are to be pushed on the stack. 3185 unsigned NumBytes = CCInfo.getNextStackOffset(); 3186 3187 if (IsSibCall) { 3188 // Since we're not changing the ABI to make this a tail call, the memory 3189 // operands are already available in the caller's incoming argument space. 3190 NumBytes = 0; 3191 } 3192 3193 // FPDiff is the byte offset of the call's argument area from the callee's. 3194 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3195 // by this amount for a tail call. In a sibling call it must be 0 because the 3196 // caller will deallocate the entire stack and the callee still expects its 3197 // arguments to begin at SP+0. Completely unused for non-tail calls. 3198 int32_t FPDiff = 0; 3199 MachineFrameInfo &MFI = MF.getFrameInfo(); 3200 3201 // Adjust the stack pointer for the new arguments... 3202 // These operations are automatically eliminated by the prolog/epilog pass 3203 if (!IsSibCall) { 3204 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 3205 3206 if (!Subtarget->enableFlatScratch()) { 3207 SmallVector<SDValue, 4> CopyFromChains; 3208 3209 // In the HSA case, this should be an identity copy. 3210 SDValue ScratchRSrcReg 3211 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 3212 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 3213 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 3214 Chain = DAG.getTokenFactor(DL, CopyFromChains); 3215 } 3216 } 3217 3218 MVT PtrVT = MVT::i32; 3219 3220 // Walk the register/memloc assignments, inserting copies/loads. 3221 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3222 CCValAssign &VA = ArgLocs[i]; 3223 SDValue Arg = OutVals[i]; 3224 3225 // Promote the value if needed. 3226 switch (VA.getLocInfo()) { 3227 case CCValAssign::Full: 3228 break; 3229 case CCValAssign::BCvt: 3230 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3231 break; 3232 case CCValAssign::ZExt: 3233 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3234 break; 3235 case CCValAssign::SExt: 3236 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3237 break; 3238 case CCValAssign::AExt: 3239 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3240 break; 3241 case CCValAssign::FPExt: 3242 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3243 break; 3244 default: 3245 llvm_unreachable("Unknown loc info!"); 3246 } 3247 3248 if (VA.isRegLoc()) { 3249 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3250 } else { 3251 assert(VA.isMemLoc()); 3252 3253 SDValue DstAddr; 3254 MachinePointerInfo DstInfo; 3255 3256 unsigned LocMemOffset = VA.getLocMemOffset(); 3257 int32_t Offset = LocMemOffset; 3258 3259 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3260 MaybeAlign Alignment; 3261 3262 if (IsTailCall) { 3263 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3264 unsigned OpSize = Flags.isByVal() ? 3265 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3266 3267 // FIXME: We can have better than the minimum byval required alignment. 3268 Alignment = 3269 Flags.isByVal() 3270 ? Flags.getNonZeroByValAlign() 3271 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3272 3273 Offset = Offset + FPDiff; 3274 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3275 3276 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3277 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3278 3279 // Make sure any stack arguments overlapping with where we're storing 3280 // are loaded before this eventual operation. Otherwise they'll be 3281 // clobbered. 3282 3283 // FIXME: Why is this really necessary? This seems to just result in a 3284 // lot of code to copy the stack and write them back to the same 3285 // locations, which are supposed to be immutable? 3286 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3287 } else { 3288 // Stores to the argument stack area are relative to the stack pointer. 3289 SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(), 3290 MVT::i32); 3291 DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff); 3292 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3293 Alignment = 3294 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3295 } 3296 3297 if (Outs[i].Flags.isByVal()) { 3298 SDValue SizeNode = 3299 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3300 SDValue Cpy = 3301 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3302 Outs[i].Flags.getNonZeroByValAlign(), 3303 /*isVol = */ false, /*AlwaysInline = */ true, 3304 /*isTailCall = */ false, DstInfo, 3305 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3306 3307 MemOpChains.push_back(Cpy); 3308 } else { 3309 SDValue Store = 3310 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment); 3311 MemOpChains.push_back(Store); 3312 } 3313 } 3314 } 3315 3316 if (!MemOpChains.empty()) 3317 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3318 3319 // Build a sequence of copy-to-reg nodes chained together with token chain 3320 // and flag operands which copy the outgoing args into the appropriate regs. 3321 SDValue InFlag; 3322 for (auto &RegToPass : RegsToPass) { 3323 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3324 RegToPass.second, InFlag); 3325 InFlag = Chain.getValue(1); 3326 } 3327 3328 3329 SDValue PhysReturnAddrReg; 3330 if (IsTailCall) { 3331 // Since the return is being combined with the call, we need to pass on the 3332 // return address. 3333 3334 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3335 SDValue ReturnAddrReg = CreateLiveInRegister( 3336 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 3337 3338 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3339 MVT::i64); 3340 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3341 InFlag = Chain.getValue(1); 3342 } 3343 3344 // We don't usually want to end the call-sequence here because we would tidy 3345 // the frame up *after* the call, however in the ABI-changing tail-call case 3346 // we've carefully laid out the parameters so that when sp is reset they'll be 3347 // in the correct location. 3348 if (IsTailCall && !IsSibCall) { 3349 Chain = DAG.getCALLSEQ_END(Chain, 3350 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3351 DAG.getTargetConstant(0, DL, MVT::i32), 3352 InFlag, DL); 3353 InFlag = Chain.getValue(1); 3354 } 3355 3356 std::vector<SDValue> Ops; 3357 Ops.push_back(Chain); 3358 Ops.push_back(Callee); 3359 // Add a redundant copy of the callee global which will not be legalized, as 3360 // we need direct access to the callee later. 3361 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3362 const GlobalValue *GV = GSD->getGlobal(); 3363 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3364 } else { 3365 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3366 } 3367 3368 if (IsTailCall) { 3369 // Each tail call may have to adjust the stack by a different amount, so 3370 // this information must travel along with the operation for eventual 3371 // consumption by emitEpilogue. 3372 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3373 3374 Ops.push_back(PhysReturnAddrReg); 3375 } 3376 3377 // Add argument registers to the end of the list so that they are known live 3378 // into the call. 3379 for (auto &RegToPass : RegsToPass) { 3380 Ops.push_back(DAG.getRegister(RegToPass.first, 3381 RegToPass.second.getValueType())); 3382 } 3383 3384 // Add a register mask operand representing the call-preserved registers. 3385 3386 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3387 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3388 assert(Mask && "Missing call preserved mask for calling convention"); 3389 Ops.push_back(DAG.getRegisterMask(Mask)); 3390 3391 if (InFlag.getNode()) 3392 Ops.push_back(InFlag); 3393 3394 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3395 3396 // If we're doing a tall call, use a TC_RETURN here rather than an 3397 // actual call instruction. 3398 if (IsTailCall) { 3399 MFI.setHasTailCall(); 3400 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3401 } 3402 3403 // Returns a chain and a flag for retval copy to use. 3404 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3405 Chain = Call.getValue(0); 3406 InFlag = Call.getValue(1); 3407 3408 uint64_t CalleePopBytes = NumBytes; 3409 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3410 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3411 InFlag, DL); 3412 if (!Ins.empty()) 3413 InFlag = Chain.getValue(1); 3414 3415 // Handle result values, copying them out of physregs into vregs that we 3416 // return. 3417 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3418 InVals, IsThisReturn, 3419 IsThisReturn ? OutVals[0] : SDValue()); 3420 } 3421 3422 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3423 // except for applying the wave size scale to the increment amount. 3424 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3425 SDValue Op, SelectionDAG &DAG) const { 3426 const MachineFunction &MF = DAG.getMachineFunction(); 3427 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3428 3429 SDLoc dl(Op); 3430 EVT VT = Op.getValueType(); 3431 SDValue Tmp1 = Op; 3432 SDValue Tmp2 = Op.getValue(1); 3433 SDValue Tmp3 = Op.getOperand(2); 3434 SDValue Chain = Tmp1.getOperand(0); 3435 3436 Register SPReg = Info->getStackPtrOffsetReg(); 3437 3438 // Chain the dynamic stack allocation so that it doesn't modify the stack 3439 // pointer when other instructions are using the stack. 3440 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3441 3442 SDValue Size = Tmp2.getOperand(1); 3443 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3444 Chain = SP.getValue(1); 3445 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3446 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3447 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3448 unsigned Opc = 3449 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3450 ISD::ADD : ISD::SUB; 3451 3452 SDValue ScaledSize = DAG.getNode( 3453 ISD::SHL, dl, VT, Size, 3454 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3455 3456 Align StackAlign = TFL->getStackAlign(); 3457 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3458 if (Alignment && *Alignment > StackAlign) { 3459 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3460 DAG.getConstant(-(uint64_t)Alignment->value() 3461 << ST.getWavefrontSizeLog2(), 3462 dl, VT)); 3463 } 3464 3465 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3466 Tmp2 = DAG.getCALLSEQ_END( 3467 Chain, DAG.getIntPtrConstant(0, dl, true), 3468 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3469 3470 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3471 } 3472 3473 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3474 SelectionDAG &DAG) const { 3475 // We only handle constant sizes here to allow non-entry block, static sized 3476 // allocas. A truly dynamic value is more difficult to support because we 3477 // don't know if the size value is uniform or not. If the size isn't uniform, 3478 // we would need to do a wave reduction to get the maximum size to know how 3479 // much to increment the uniform stack pointer. 3480 SDValue Size = Op.getOperand(1); 3481 if (isa<ConstantSDNode>(Size)) 3482 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3483 3484 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3485 } 3486 3487 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3488 const MachineFunction &MF) const { 3489 Register Reg = StringSwitch<Register>(RegName) 3490 .Case("m0", AMDGPU::M0) 3491 .Case("exec", AMDGPU::EXEC) 3492 .Case("exec_lo", AMDGPU::EXEC_LO) 3493 .Case("exec_hi", AMDGPU::EXEC_HI) 3494 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3495 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3496 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3497 .Default(Register()); 3498 3499 if (Reg == AMDGPU::NoRegister) { 3500 report_fatal_error(Twine("invalid register name \"" 3501 + StringRef(RegName) + "\".")); 3502 3503 } 3504 3505 if (!Subtarget->hasFlatScrRegister() && 3506 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3507 report_fatal_error(Twine("invalid register \"" 3508 + StringRef(RegName) + "\" for subtarget.")); 3509 } 3510 3511 switch (Reg) { 3512 case AMDGPU::M0: 3513 case AMDGPU::EXEC_LO: 3514 case AMDGPU::EXEC_HI: 3515 case AMDGPU::FLAT_SCR_LO: 3516 case AMDGPU::FLAT_SCR_HI: 3517 if (VT.getSizeInBits() == 32) 3518 return Reg; 3519 break; 3520 case AMDGPU::EXEC: 3521 case AMDGPU::FLAT_SCR: 3522 if (VT.getSizeInBits() == 64) 3523 return Reg; 3524 break; 3525 default: 3526 llvm_unreachable("missing register type checking"); 3527 } 3528 3529 report_fatal_error(Twine("invalid type for register \"" 3530 + StringRef(RegName) + "\".")); 3531 } 3532 3533 // If kill is not the last instruction, split the block so kill is always a 3534 // proper terminator. 3535 MachineBasicBlock * 3536 SITargetLowering::splitKillBlock(MachineInstr &MI, 3537 MachineBasicBlock *BB) const { 3538 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/); 3539 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3540 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3541 return SplitBB; 3542 } 3543 3544 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3545 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3546 // be the first instruction in the remainder block. 3547 // 3548 /// \returns { LoopBody, Remainder } 3549 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3550 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3551 MachineFunction *MF = MBB.getParent(); 3552 MachineBasicBlock::iterator I(&MI); 3553 3554 // To insert the loop we need to split the block. Move everything after this 3555 // point to a new block, and insert a new empty block between the two. 3556 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3557 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3558 MachineFunction::iterator MBBI(MBB); 3559 ++MBBI; 3560 3561 MF->insert(MBBI, LoopBB); 3562 MF->insert(MBBI, RemainderBB); 3563 3564 LoopBB->addSuccessor(LoopBB); 3565 LoopBB->addSuccessor(RemainderBB); 3566 3567 // Move the rest of the block into a new block. 3568 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3569 3570 if (InstInLoop) { 3571 auto Next = std::next(I); 3572 3573 // Move instruction to loop body. 3574 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3575 3576 // Move the rest of the block. 3577 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3578 } else { 3579 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3580 } 3581 3582 MBB.addSuccessor(LoopBB); 3583 3584 return std::make_pair(LoopBB, RemainderBB); 3585 } 3586 3587 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3588 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3589 MachineBasicBlock *MBB = MI.getParent(); 3590 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3591 auto I = MI.getIterator(); 3592 auto E = std::next(I); 3593 3594 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3595 .addImm(0); 3596 3597 MIBundleBuilder Bundler(*MBB, I, E); 3598 finalizeBundle(*MBB, Bundler.begin()); 3599 } 3600 3601 MachineBasicBlock * 3602 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3603 MachineBasicBlock *BB) const { 3604 const DebugLoc &DL = MI.getDebugLoc(); 3605 3606 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3607 3608 MachineBasicBlock *LoopBB; 3609 MachineBasicBlock *RemainderBB; 3610 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3611 3612 // Apparently kill flags are only valid if the def is in the same block? 3613 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3614 Src->setIsKill(false); 3615 3616 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3617 3618 MachineBasicBlock::iterator I = LoopBB->end(); 3619 3620 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3621 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3622 3623 // Clear TRAP_STS.MEM_VIOL 3624 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3625 .addImm(0) 3626 .addImm(EncodedReg); 3627 3628 bundleInstWithWaitcnt(MI); 3629 3630 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3631 3632 // Load and check TRAP_STS.MEM_VIOL 3633 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3634 .addImm(EncodedReg); 3635 3636 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3637 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3638 .addReg(Reg, RegState::Kill) 3639 .addImm(0); 3640 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3641 .addMBB(LoopBB); 3642 3643 return RemainderBB; 3644 } 3645 3646 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3647 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3648 // will only do one iteration. In the worst case, this will loop 64 times. 3649 // 3650 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3651 static MachineBasicBlock::iterator 3652 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI, 3653 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB, 3654 const DebugLoc &DL, const MachineOperand &Idx, 3655 unsigned InitReg, unsigned ResultReg, unsigned PhiReg, 3656 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode, 3657 Register &SGPRIdxReg) { 3658 3659 MachineFunction *MF = OrigBB.getParent(); 3660 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3661 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3662 MachineBasicBlock::iterator I = LoopBB.begin(); 3663 3664 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3665 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3666 Register NewExec = MRI.createVirtualRegister(BoolRC); 3667 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3668 Register CondReg = MRI.createVirtualRegister(BoolRC); 3669 3670 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3671 .addReg(InitReg) 3672 .addMBB(&OrigBB) 3673 .addReg(ResultReg) 3674 .addMBB(&LoopBB); 3675 3676 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3677 .addReg(InitSaveExecReg) 3678 .addMBB(&OrigBB) 3679 .addReg(NewExec) 3680 .addMBB(&LoopBB); 3681 3682 // Read the next variant <- also loop target. 3683 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3684 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef())); 3685 3686 // Compare the just read M0 value to all possible Idx values. 3687 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3688 .addReg(CurrentIdxReg) 3689 .addReg(Idx.getReg(), 0, Idx.getSubReg()); 3690 3691 // Update EXEC, save the original EXEC value to VCC. 3692 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3693 : AMDGPU::S_AND_SAVEEXEC_B64), 3694 NewExec) 3695 .addReg(CondReg, RegState::Kill); 3696 3697 MRI.setSimpleHint(NewExec, CondReg); 3698 3699 if (UseGPRIdxMode) { 3700 if (Offset == 0) { 3701 SGPRIdxReg = CurrentIdxReg; 3702 } else { 3703 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3704 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg) 3705 .addReg(CurrentIdxReg, RegState::Kill) 3706 .addImm(Offset); 3707 } 3708 } else { 3709 // Move index from VCC into M0 3710 if (Offset == 0) { 3711 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3712 .addReg(CurrentIdxReg, RegState::Kill); 3713 } else { 3714 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3715 .addReg(CurrentIdxReg, RegState::Kill) 3716 .addImm(Offset); 3717 } 3718 } 3719 3720 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3721 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3722 MachineInstr *InsertPt = 3723 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3724 : AMDGPU::S_XOR_B64_term), Exec) 3725 .addReg(Exec) 3726 .addReg(NewExec); 3727 3728 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3729 // s_cbranch_scc0? 3730 3731 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3732 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3733 .addMBB(&LoopBB); 3734 3735 return InsertPt->getIterator(); 3736 } 3737 3738 // This has slightly sub-optimal regalloc when the source vector is killed by 3739 // the read. The register allocator does not understand that the kill is 3740 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3741 // subregister from it, using 1 more VGPR than necessary. This was saved when 3742 // this was expanded after register allocation. 3743 static MachineBasicBlock::iterator 3744 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI, 3745 unsigned InitResultReg, unsigned PhiReg, int Offset, 3746 bool UseGPRIdxMode, Register &SGPRIdxReg) { 3747 MachineFunction *MF = MBB.getParent(); 3748 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3749 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3750 MachineRegisterInfo &MRI = MF->getRegInfo(); 3751 const DebugLoc &DL = MI.getDebugLoc(); 3752 MachineBasicBlock::iterator I(&MI); 3753 3754 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3755 Register DstReg = MI.getOperand(0).getReg(); 3756 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3757 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3758 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3759 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3760 3761 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3762 3763 // Save the EXEC mask 3764 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3765 .addReg(Exec); 3766 3767 MachineBasicBlock *LoopBB; 3768 MachineBasicBlock *RemainderBB; 3769 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3770 3771 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3772 3773 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3774 InitResultReg, DstReg, PhiReg, TmpExec, 3775 Offset, UseGPRIdxMode, SGPRIdxReg); 3776 3777 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3778 MachineFunction::iterator MBBI(LoopBB); 3779 ++MBBI; 3780 MF->insert(MBBI, LandingPad); 3781 LoopBB->removeSuccessor(RemainderBB); 3782 LandingPad->addSuccessor(RemainderBB); 3783 LoopBB->addSuccessor(LandingPad); 3784 MachineBasicBlock::iterator First = LandingPad->begin(); 3785 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3786 .addReg(SaveExec); 3787 3788 return InsPt; 3789 } 3790 3791 // Returns subreg index, offset 3792 static std::pair<unsigned, int> 3793 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3794 const TargetRegisterClass *SuperRC, 3795 unsigned VecReg, 3796 int Offset) { 3797 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3798 3799 // Skip out of bounds offsets, or else we would end up using an undefined 3800 // register. 3801 if (Offset >= NumElts || Offset < 0) 3802 return std::make_pair(AMDGPU::sub0, Offset); 3803 3804 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3805 } 3806 3807 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3808 MachineRegisterInfo &MRI, MachineInstr &MI, 3809 int Offset) { 3810 MachineBasicBlock *MBB = MI.getParent(); 3811 const DebugLoc &DL = MI.getDebugLoc(); 3812 MachineBasicBlock::iterator I(&MI); 3813 3814 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3815 3816 assert(Idx->getReg() != AMDGPU::NoRegister); 3817 3818 if (Offset == 0) { 3819 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx); 3820 } else { 3821 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3822 .add(*Idx) 3823 .addImm(Offset); 3824 } 3825 } 3826 3827 static Register getIndirectSGPRIdx(const SIInstrInfo *TII, 3828 MachineRegisterInfo &MRI, MachineInstr &MI, 3829 int Offset) { 3830 MachineBasicBlock *MBB = MI.getParent(); 3831 const DebugLoc &DL = MI.getDebugLoc(); 3832 MachineBasicBlock::iterator I(&MI); 3833 3834 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3835 3836 if (Offset == 0) 3837 return Idx->getReg(); 3838 3839 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3840 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3841 .add(*Idx) 3842 .addImm(Offset); 3843 return Tmp; 3844 } 3845 3846 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3847 MachineBasicBlock &MBB, 3848 const GCNSubtarget &ST) { 3849 const SIInstrInfo *TII = ST.getInstrInfo(); 3850 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3851 MachineFunction *MF = MBB.getParent(); 3852 MachineRegisterInfo &MRI = MF->getRegInfo(); 3853 3854 Register Dst = MI.getOperand(0).getReg(); 3855 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3856 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3857 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3858 3859 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3860 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3861 3862 unsigned SubReg; 3863 std::tie(SubReg, Offset) 3864 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3865 3866 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3867 3868 // Check for a SGPR index. 3869 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3870 MachineBasicBlock::iterator I(&MI); 3871 const DebugLoc &DL = MI.getDebugLoc(); 3872 3873 if (UseGPRIdxMode) { 3874 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3875 // to avoid interfering with other uses, so probably requires a new 3876 // optimization pass. 3877 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3878 3879 const MCInstrDesc &GPRIDXDesc = 3880 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3881 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3882 .addReg(SrcReg) 3883 .addReg(Idx) 3884 .addImm(SubReg); 3885 } else { 3886 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3887 3888 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3889 .addReg(SrcReg, 0, SubReg) 3890 .addReg(SrcReg, RegState::Implicit); 3891 } 3892 3893 MI.eraseFromParent(); 3894 3895 return &MBB; 3896 } 3897 3898 // Control flow needs to be inserted if indexing with a VGPR. 3899 const DebugLoc &DL = MI.getDebugLoc(); 3900 MachineBasicBlock::iterator I(&MI); 3901 3902 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3903 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3904 3905 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3906 3907 Register SGPRIdxReg; 3908 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, 3909 UseGPRIdxMode, SGPRIdxReg); 3910 3911 MachineBasicBlock *LoopBB = InsPt->getParent(); 3912 3913 if (UseGPRIdxMode) { 3914 const MCInstrDesc &GPRIDXDesc = 3915 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3916 3917 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3918 .addReg(SrcReg) 3919 .addReg(SGPRIdxReg) 3920 .addImm(SubReg); 3921 } else { 3922 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3923 .addReg(SrcReg, 0, SubReg) 3924 .addReg(SrcReg, RegState::Implicit); 3925 } 3926 3927 MI.eraseFromParent(); 3928 3929 return LoopBB; 3930 } 3931 3932 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3933 MachineBasicBlock &MBB, 3934 const GCNSubtarget &ST) { 3935 const SIInstrInfo *TII = ST.getInstrInfo(); 3936 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3937 MachineFunction *MF = MBB.getParent(); 3938 MachineRegisterInfo &MRI = MF->getRegInfo(); 3939 3940 Register Dst = MI.getOperand(0).getReg(); 3941 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3942 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3943 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3944 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3945 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3946 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3947 3948 // This can be an immediate, but will be folded later. 3949 assert(Val->getReg()); 3950 3951 unsigned SubReg; 3952 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3953 SrcVec->getReg(), 3954 Offset); 3955 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3956 3957 if (Idx->getReg() == AMDGPU::NoRegister) { 3958 MachineBasicBlock::iterator I(&MI); 3959 const DebugLoc &DL = MI.getDebugLoc(); 3960 3961 assert(Offset == 0); 3962 3963 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3964 .add(*SrcVec) 3965 .add(*Val) 3966 .addImm(SubReg); 3967 3968 MI.eraseFromParent(); 3969 return &MBB; 3970 } 3971 3972 // Check for a SGPR index. 3973 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3974 MachineBasicBlock::iterator I(&MI); 3975 const DebugLoc &DL = MI.getDebugLoc(); 3976 3977 if (UseGPRIdxMode) { 3978 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3979 3980 const MCInstrDesc &GPRIDXDesc = 3981 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3982 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3983 .addReg(SrcVec->getReg()) 3984 .add(*Val) 3985 .addReg(Idx) 3986 .addImm(SubReg); 3987 } else { 3988 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3989 3990 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3991 TRI.getRegSizeInBits(*VecRC), 32, false); 3992 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3993 .addReg(SrcVec->getReg()) 3994 .add(*Val) 3995 .addImm(SubReg); 3996 } 3997 MI.eraseFromParent(); 3998 return &MBB; 3999 } 4000 4001 // Control flow needs to be inserted if indexing with a VGPR. 4002 if (Val->isReg()) 4003 MRI.clearKillFlags(Val->getReg()); 4004 4005 const DebugLoc &DL = MI.getDebugLoc(); 4006 4007 Register PhiReg = MRI.createVirtualRegister(VecRC); 4008 4009 Register SGPRIdxReg; 4010 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset, 4011 UseGPRIdxMode, SGPRIdxReg); 4012 MachineBasicBlock *LoopBB = InsPt->getParent(); 4013 4014 if (UseGPRIdxMode) { 4015 const MCInstrDesc &GPRIDXDesc = 4016 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 4017 4018 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 4019 .addReg(PhiReg) 4020 .add(*Val) 4021 .addReg(SGPRIdxReg) 4022 .addImm(AMDGPU::sub0); 4023 } else { 4024 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 4025 TRI.getRegSizeInBits(*VecRC), 32, false); 4026 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 4027 .addReg(PhiReg) 4028 .add(*Val) 4029 .addImm(AMDGPU::sub0); 4030 } 4031 4032 MI.eraseFromParent(); 4033 return LoopBB; 4034 } 4035 4036 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 4037 MachineInstr &MI, MachineBasicBlock *BB) const { 4038 4039 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4040 MachineFunction *MF = BB->getParent(); 4041 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 4042 4043 switch (MI.getOpcode()) { 4044 case AMDGPU::S_UADDO_PSEUDO: 4045 case AMDGPU::S_USUBO_PSEUDO: { 4046 const DebugLoc &DL = MI.getDebugLoc(); 4047 MachineOperand &Dest0 = MI.getOperand(0); 4048 MachineOperand &Dest1 = MI.getOperand(1); 4049 MachineOperand &Src0 = MI.getOperand(2); 4050 MachineOperand &Src1 = MI.getOperand(3); 4051 4052 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 4053 ? AMDGPU::S_ADD_I32 4054 : AMDGPU::S_SUB_I32; 4055 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 4056 4057 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 4058 .addImm(1) 4059 .addImm(0); 4060 4061 MI.eraseFromParent(); 4062 return BB; 4063 } 4064 case AMDGPU::S_ADD_U64_PSEUDO: 4065 case AMDGPU::S_SUB_U64_PSEUDO: { 4066 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4067 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4068 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4069 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 4070 const DebugLoc &DL = MI.getDebugLoc(); 4071 4072 MachineOperand &Dest = MI.getOperand(0); 4073 MachineOperand &Src0 = MI.getOperand(1); 4074 MachineOperand &Src1 = MI.getOperand(2); 4075 4076 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4077 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4078 4079 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 4080 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 4081 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 4082 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 4083 4084 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 4085 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 4086 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 4087 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 4088 4089 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 4090 4091 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 4092 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 4093 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 4094 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 4095 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 4096 .addReg(DestSub0) 4097 .addImm(AMDGPU::sub0) 4098 .addReg(DestSub1) 4099 .addImm(AMDGPU::sub1); 4100 MI.eraseFromParent(); 4101 return BB; 4102 } 4103 case AMDGPU::V_ADD_U64_PSEUDO: 4104 case AMDGPU::V_SUB_U64_PSEUDO: { 4105 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4106 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4107 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4108 const DebugLoc &DL = MI.getDebugLoc(); 4109 4110 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 4111 4112 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4113 4114 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4115 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4116 4117 Register CarryReg = MRI.createVirtualRegister(CarryRC); 4118 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 4119 4120 MachineOperand &Dest = MI.getOperand(0); 4121 MachineOperand &Src0 = MI.getOperand(1); 4122 MachineOperand &Src1 = MI.getOperand(2); 4123 4124 const TargetRegisterClass *Src0RC = Src0.isReg() 4125 ? MRI.getRegClass(Src0.getReg()) 4126 : &AMDGPU::VReg_64RegClass; 4127 const TargetRegisterClass *Src1RC = Src1.isReg() 4128 ? MRI.getRegClass(Src1.getReg()) 4129 : &AMDGPU::VReg_64RegClass; 4130 4131 const TargetRegisterClass *Src0SubRC = 4132 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 4133 const TargetRegisterClass *Src1SubRC = 4134 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 4135 4136 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 4137 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 4138 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 4139 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 4140 4141 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 4142 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 4143 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 4144 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 4145 4146 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 4147 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 4148 .addReg(CarryReg, RegState::Define) 4149 .add(SrcReg0Sub0) 4150 .add(SrcReg1Sub0) 4151 .addImm(0); // clamp bit 4152 4153 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 4154 MachineInstr *HiHalf = 4155 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 4156 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 4157 .add(SrcReg0Sub1) 4158 .add(SrcReg1Sub1) 4159 .addReg(CarryReg, RegState::Kill) 4160 .addImm(0); // clamp bit 4161 4162 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 4163 .addReg(DestSub0) 4164 .addImm(AMDGPU::sub0) 4165 .addReg(DestSub1) 4166 .addImm(AMDGPU::sub1); 4167 TII->legalizeOperands(*LoHalf); 4168 TII->legalizeOperands(*HiHalf); 4169 MI.eraseFromParent(); 4170 return BB; 4171 } 4172 case AMDGPU::S_ADD_CO_PSEUDO: 4173 case AMDGPU::S_SUB_CO_PSEUDO: { 4174 // This pseudo has a chance to be selected 4175 // only from uniform add/subcarry node. All the VGPR operands 4176 // therefore assumed to be splat vectors. 4177 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4178 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4179 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4180 MachineBasicBlock::iterator MII = MI; 4181 const DebugLoc &DL = MI.getDebugLoc(); 4182 MachineOperand &Dest = MI.getOperand(0); 4183 MachineOperand &CarryDest = MI.getOperand(1); 4184 MachineOperand &Src0 = MI.getOperand(2); 4185 MachineOperand &Src1 = MI.getOperand(3); 4186 MachineOperand &Src2 = MI.getOperand(4); 4187 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 4188 ? AMDGPU::S_ADDC_U32 4189 : AMDGPU::S_SUBB_U32; 4190 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 4191 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4192 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 4193 .addReg(Src0.getReg()); 4194 Src0.setReg(RegOp0); 4195 } 4196 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 4197 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4198 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 4199 .addReg(Src1.getReg()); 4200 Src1.setReg(RegOp1); 4201 } 4202 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4203 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 4204 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 4205 .addReg(Src2.getReg()); 4206 Src2.setReg(RegOp2); 4207 } 4208 4209 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg()); 4210 unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC); 4211 assert(WaveSize == 64 || WaveSize == 32); 4212 4213 if (WaveSize == 64) { 4214 if (ST.hasScalarCompareEq64()) { 4215 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 4216 .addReg(Src2.getReg()) 4217 .addImm(0); 4218 } else { 4219 const TargetRegisterClass *SubRC = 4220 TRI->getSubRegClass(Src2RC, AMDGPU::sub0); 4221 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm( 4222 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC); 4223 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm( 4224 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC); 4225 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4226 4227 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32) 4228 .add(Src2Sub0) 4229 .add(Src2Sub1); 4230 4231 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 4232 .addReg(Src2_32, RegState::Kill) 4233 .addImm(0); 4234 } 4235 } else { 4236 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4237 .addReg(Src2.getReg()) 4238 .addImm(0); 4239 } 4240 4241 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4242 4243 unsigned SelOpc = 4244 (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32; 4245 4246 BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg()) 4247 .addImm(-1) 4248 .addImm(0); 4249 4250 MI.eraseFromParent(); 4251 return BB; 4252 } 4253 case AMDGPU::SI_INIT_M0: { 4254 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4255 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4256 .add(MI.getOperand(0)); 4257 MI.eraseFromParent(); 4258 return BB; 4259 } 4260 case AMDGPU::GET_GROUPSTATICSIZE: { 4261 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4262 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4263 DebugLoc DL = MI.getDebugLoc(); 4264 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4265 .add(MI.getOperand(0)) 4266 .addImm(MFI->getLDSSize()); 4267 MI.eraseFromParent(); 4268 return BB; 4269 } 4270 case AMDGPU::SI_INDIRECT_SRC_V1: 4271 case AMDGPU::SI_INDIRECT_SRC_V2: 4272 case AMDGPU::SI_INDIRECT_SRC_V4: 4273 case AMDGPU::SI_INDIRECT_SRC_V8: 4274 case AMDGPU::SI_INDIRECT_SRC_V16: 4275 case AMDGPU::SI_INDIRECT_SRC_V32: 4276 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4277 case AMDGPU::SI_INDIRECT_DST_V1: 4278 case AMDGPU::SI_INDIRECT_DST_V2: 4279 case AMDGPU::SI_INDIRECT_DST_V4: 4280 case AMDGPU::SI_INDIRECT_DST_V8: 4281 case AMDGPU::SI_INDIRECT_DST_V16: 4282 case AMDGPU::SI_INDIRECT_DST_V32: 4283 return emitIndirectDst(MI, *BB, *getSubtarget()); 4284 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4285 case AMDGPU::SI_KILL_I1_PSEUDO: 4286 return splitKillBlock(MI, BB); 4287 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4288 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4289 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4290 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4291 4292 Register Dst = MI.getOperand(0).getReg(); 4293 Register Src0 = MI.getOperand(1).getReg(); 4294 Register Src1 = MI.getOperand(2).getReg(); 4295 const DebugLoc &DL = MI.getDebugLoc(); 4296 Register SrcCond = MI.getOperand(3).getReg(); 4297 4298 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4299 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4300 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4301 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4302 4303 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4304 .addReg(SrcCond); 4305 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4306 .addImm(0) 4307 .addReg(Src0, 0, AMDGPU::sub0) 4308 .addImm(0) 4309 .addReg(Src1, 0, AMDGPU::sub0) 4310 .addReg(SrcCondCopy); 4311 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4312 .addImm(0) 4313 .addReg(Src0, 0, AMDGPU::sub1) 4314 .addImm(0) 4315 .addReg(Src1, 0, AMDGPU::sub1) 4316 .addReg(SrcCondCopy); 4317 4318 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4319 .addReg(DstLo) 4320 .addImm(AMDGPU::sub0) 4321 .addReg(DstHi) 4322 .addImm(AMDGPU::sub1); 4323 MI.eraseFromParent(); 4324 return BB; 4325 } 4326 case AMDGPU::SI_BR_UNDEF: { 4327 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4328 const DebugLoc &DL = MI.getDebugLoc(); 4329 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4330 .add(MI.getOperand(0)); 4331 Br->getOperand(1).setIsUndef(true); // read undef SCC 4332 MI.eraseFromParent(); 4333 return BB; 4334 } 4335 case AMDGPU::ADJCALLSTACKUP: 4336 case AMDGPU::ADJCALLSTACKDOWN: { 4337 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4338 MachineInstrBuilder MIB(*MF, &MI); 4339 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4340 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 4341 return BB; 4342 } 4343 case AMDGPU::SI_CALL_ISEL: { 4344 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4345 const DebugLoc &DL = MI.getDebugLoc(); 4346 4347 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4348 4349 MachineInstrBuilder MIB; 4350 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4351 4352 for (const MachineOperand &MO : MI.operands()) 4353 MIB.add(MO); 4354 4355 MIB.cloneMemRefs(MI); 4356 MI.eraseFromParent(); 4357 return BB; 4358 } 4359 case AMDGPU::V_ADD_CO_U32_e32: 4360 case AMDGPU::V_SUB_CO_U32_e32: 4361 case AMDGPU::V_SUBREV_CO_U32_e32: { 4362 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4363 const DebugLoc &DL = MI.getDebugLoc(); 4364 unsigned Opc = MI.getOpcode(); 4365 4366 bool NeedClampOperand = false; 4367 if (TII->pseudoToMCOpcode(Opc) == -1) { 4368 Opc = AMDGPU::getVOPe64(Opc); 4369 NeedClampOperand = true; 4370 } 4371 4372 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4373 if (TII->isVOP3(*I)) { 4374 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4375 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4376 I.addReg(TRI->getVCC(), RegState::Define); 4377 } 4378 I.add(MI.getOperand(1)) 4379 .add(MI.getOperand(2)); 4380 if (NeedClampOperand) 4381 I.addImm(0); // clamp bit for e64 encoding 4382 4383 TII->legalizeOperands(*I); 4384 4385 MI.eraseFromParent(); 4386 return BB; 4387 } 4388 case AMDGPU::V_ADDC_U32_e32: 4389 case AMDGPU::V_SUBB_U32_e32: 4390 case AMDGPU::V_SUBBREV_U32_e32: 4391 // These instructions have an implicit use of vcc which counts towards the 4392 // constant bus limit. 4393 TII->legalizeOperands(MI); 4394 return BB; 4395 case AMDGPU::DS_GWS_INIT: 4396 case AMDGPU::DS_GWS_SEMA_BR: 4397 case AMDGPU::DS_GWS_BARRIER: 4398 if (Subtarget->needsAlignedVGPRs()) { 4399 // Add implicit aligned super-reg to force alignment on the data operand. 4400 const DebugLoc &DL = MI.getDebugLoc(); 4401 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4402 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 4403 MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0); 4404 Register DataReg = Op->getReg(); 4405 bool IsAGPR = TRI->isAGPR(MRI, DataReg); 4406 Register Undef = MRI.createVirtualRegister( 4407 IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass); 4408 BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef); 4409 Register NewVR = 4410 MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass 4411 : &AMDGPU::VReg_64_Align2RegClass); 4412 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR) 4413 .addReg(DataReg, 0, Op->getSubReg()) 4414 .addImm(AMDGPU::sub0) 4415 .addReg(Undef) 4416 .addImm(AMDGPU::sub1); 4417 Op->setReg(NewVR); 4418 Op->setSubReg(AMDGPU::sub0); 4419 MI.addOperand(MachineOperand::CreateReg(NewVR, false, true)); 4420 } 4421 LLVM_FALLTHROUGH; 4422 case AMDGPU::DS_GWS_SEMA_V: 4423 case AMDGPU::DS_GWS_SEMA_P: 4424 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4425 // A s_waitcnt 0 is required to be the instruction immediately following. 4426 if (getSubtarget()->hasGWSAutoReplay()) { 4427 bundleInstWithWaitcnt(MI); 4428 return BB; 4429 } 4430 4431 return emitGWSMemViolTestLoop(MI, BB); 4432 case AMDGPU::S_SETREG_B32: { 4433 // Try to optimize cases that only set the denormal mode or rounding mode. 4434 // 4435 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4436 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4437 // instead. 4438 // 4439 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4440 // allow you to have a no side effect instruction in the output of a 4441 // sideeffecting pattern. 4442 unsigned ID, Offset, Width; 4443 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4444 if (ID != AMDGPU::Hwreg::ID_MODE) 4445 return BB; 4446 4447 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4448 const unsigned SetMask = WidthMask << Offset; 4449 4450 if (getSubtarget()->hasDenormModeInst()) { 4451 unsigned SetDenormOp = 0; 4452 unsigned SetRoundOp = 0; 4453 4454 // The dedicated instructions can only set the whole denorm or round mode 4455 // at once, not a subset of bits in either. 4456 if (SetMask == 4457 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4458 // If this fully sets both the round and denorm mode, emit the two 4459 // dedicated instructions for these. 4460 SetRoundOp = AMDGPU::S_ROUND_MODE; 4461 SetDenormOp = AMDGPU::S_DENORM_MODE; 4462 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4463 SetRoundOp = AMDGPU::S_ROUND_MODE; 4464 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4465 SetDenormOp = AMDGPU::S_DENORM_MODE; 4466 } 4467 4468 if (SetRoundOp || SetDenormOp) { 4469 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4470 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4471 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4472 unsigned ImmVal = Def->getOperand(1).getImm(); 4473 if (SetRoundOp) { 4474 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4475 .addImm(ImmVal & 0xf); 4476 4477 // If we also have the denorm mode, get just the denorm mode bits. 4478 ImmVal >>= 4; 4479 } 4480 4481 if (SetDenormOp) { 4482 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4483 .addImm(ImmVal & 0xf); 4484 } 4485 4486 MI.eraseFromParent(); 4487 return BB; 4488 } 4489 } 4490 } 4491 4492 // If only FP bits are touched, used the no side effects pseudo. 4493 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4494 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) 4495 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode)); 4496 4497 return BB; 4498 } 4499 default: 4500 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4501 } 4502 } 4503 4504 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4505 return isTypeLegal(VT.getScalarType()); 4506 } 4507 4508 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4509 // This currently forces unfolding various combinations of fsub into fma with 4510 // free fneg'd operands. As long as we have fast FMA (controlled by 4511 // isFMAFasterThanFMulAndFAdd), we should perform these. 4512 4513 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4514 // most of these combines appear to be cycle neutral but save on instruction 4515 // count / code size. 4516 return true; 4517 } 4518 4519 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; } 4520 4521 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4522 EVT VT) const { 4523 if (!VT.isVector()) { 4524 return MVT::i1; 4525 } 4526 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4527 } 4528 4529 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4530 // TODO: Should i16 be used always if legal? For now it would force VALU 4531 // shifts. 4532 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4533 } 4534 4535 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4536 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4537 ? Ty.changeElementSize(16) 4538 : Ty.changeElementSize(32); 4539 } 4540 4541 // Answering this is somewhat tricky and depends on the specific device which 4542 // have different rates for fma or all f64 operations. 4543 // 4544 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4545 // regardless of which device (although the number of cycles differs between 4546 // devices), so it is always profitable for f64. 4547 // 4548 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4549 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4550 // which we can always do even without fused FP ops since it returns the same 4551 // result as the separate operations and since it is always full 4552 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4553 // however does not support denormals, so we do report fma as faster if we have 4554 // a fast fma device and require denormals. 4555 // 4556 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4557 EVT VT) const { 4558 VT = VT.getScalarType(); 4559 4560 switch (VT.getSimpleVT().SimpleTy) { 4561 case MVT::f32: { 4562 // If mad is not available this depends only on if f32 fma is full rate. 4563 if (!Subtarget->hasMadMacF32Insts()) 4564 return Subtarget->hasFastFMAF32(); 4565 4566 // Otherwise f32 mad is always full rate and returns the same result as 4567 // the separate operations so should be preferred over fma. 4568 // However does not support denomals. 4569 if (hasFP32Denormals(MF)) 4570 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4571 4572 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4573 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4574 } 4575 case MVT::f64: 4576 return true; 4577 case MVT::f16: 4578 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4579 default: 4580 break; 4581 } 4582 4583 return false; 4584 } 4585 4586 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4587 LLT Ty) const { 4588 switch (Ty.getScalarSizeInBits()) { 4589 case 16: 4590 return isFMAFasterThanFMulAndFAdd(MF, MVT::f16); 4591 case 32: 4592 return isFMAFasterThanFMulAndFAdd(MF, MVT::f32); 4593 case 64: 4594 return isFMAFasterThanFMulAndFAdd(MF, MVT::f64); 4595 default: 4596 break; 4597 } 4598 4599 return false; 4600 } 4601 4602 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const { 4603 if (!Ty.isScalar()) 4604 return false; 4605 4606 if (Ty.getScalarSizeInBits() == 16) 4607 return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF()); 4608 if (Ty.getScalarSizeInBits() == 32) 4609 return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF()); 4610 4611 return false; 4612 } 4613 4614 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4615 const SDNode *N) const { 4616 // TODO: Check future ftz flag 4617 // v_mad_f32/v_mac_f32 do not support denormals. 4618 EVT VT = N->getValueType(0); 4619 if (VT == MVT::f32) 4620 return Subtarget->hasMadMacF32Insts() && 4621 !hasFP32Denormals(DAG.getMachineFunction()); 4622 if (VT == MVT::f16) { 4623 return Subtarget->hasMadF16() && 4624 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4625 } 4626 4627 return false; 4628 } 4629 4630 //===----------------------------------------------------------------------===// 4631 // Custom DAG Lowering Operations 4632 //===----------------------------------------------------------------------===// 4633 4634 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4635 // wider vector type is legal. 4636 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4637 SelectionDAG &DAG) const { 4638 unsigned Opc = Op.getOpcode(); 4639 EVT VT = Op.getValueType(); 4640 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4641 4642 SDValue Lo, Hi; 4643 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4644 4645 SDLoc SL(Op); 4646 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4647 Op->getFlags()); 4648 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4649 Op->getFlags()); 4650 4651 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4652 } 4653 4654 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4655 // wider vector type is legal. 4656 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4657 SelectionDAG &DAG) const { 4658 unsigned Opc = Op.getOpcode(); 4659 EVT VT = Op.getValueType(); 4660 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4661 VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8f32 || 4662 VT == MVT::v16f32 || VT == MVT::v32f32); 4663 4664 SDValue Lo0, Hi0; 4665 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4666 SDValue Lo1, Hi1; 4667 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4668 4669 SDLoc SL(Op); 4670 4671 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4672 Op->getFlags()); 4673 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4674 Op->getFlags()); 4675 4676 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4677 } 4678 4679 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4680 SelectionDAG &DAG) const { 4681 unsigned Opc = Op.getOpcode(); 4682 EVT VT = Op.getValueType(); 4683 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 || 4684 VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v8f32 || 4685 VT == MVT::v16f32 || VT == MVT::v32f32); 4686 4687 SDValue Lo0, Hi0; 4688 SDValue Op0 = Op.getOperand(0); 4689 std::tie(Lo0, Hi0) = Op0.getValueType().isVector() 4690 ? DAG.SplitVectorOperand(Op.getNode(), 0) 4691 : std::make_pair(Op0, Op0); 4692 SDValue Lo1, Hi1; 4693 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4694 SDValue Lo2, Hi2; 4695 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4696 4697 SDLoc SL(Op); 4698 auto ResVT = DAG.GetSplitDestVTs(VT); 4699 4700 SDValue OpLo = DAG.getNode(Opc, SL, ResVT.first, Lo0, Lo1, Lo2, 4701 Op->getFlags()); 4702 SDValue OpHi = DAG.getNode(Opc, SL, ResVT.second, Hi0, Hi1, Hi2, 4703 Op->getFlags()); 4704 4705 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4706 } 4707 4708 4709 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4710 switch (Op.getOpcode()) { 4711 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4712 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4713 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4714 case ISD::LOAD: { 4715 SDValue Result = LowerLOAD(Op, DAG); 4716 assert((!Result.getNode() || 4717 Result.getNode()->getNumValues() == 2) && 4718 "Load should return a value and a chain"); 4719 return Result; 4720 } 4721 4722 case ISD::FSIN: 4723 case ISD::FCOS: 4724 return LowerTrig(Op, DAG); 4725 case ISD::SELECT: return LowerSELECT(Op, DAG); 4726 case ISD::FDIV: return LowerFDIV(Op, DAG); 4727 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4728 case ISD::STORE: return LowerSTORE(Op, DAG); 4729 case ISD::GlobalAddress: { 4730 MachineFunction &MF = DAG.getMachineFunction(); 4731 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4732 return LowerGlobalAddress(MFI, Op, DAG); 4733 } 4734 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4735 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4736 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4737 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4738 case ISD::INSERT_SUBVECTOR: 4739 return lowerINSERT_SUBVECTOR(Op, DAG); 4740 case ISD::INSERT_VECTOR_ELT: 4741 return lowerINSERT_VECTOR_ELT(Op, DAG); 4742 case ISD::EXTRACT_VECTOR_ELT: 4743 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4744 case ISD::VECTOR_SHUFFLE: 4745 return lowerVECTOR_SHUFFLE(Op, DAG); 4746 case ISD::BUILD_VECTOR: 4747 return lowerBUILD_VECTOR(Op, DAG); 4748 case ISD::FP_ROUND: 4749 return lowerFP_ROUND(Op, DAG); 4750 case ISD::FPTRUNC_ROUND: { 4751 unsigned Opc; 4752 SDLoc DL(Op); 4753 4754 if (Op.getOperand(0)->getValueType(0) != MVT::f32) 4755 return SDValue(); 4756 4757 // Get the rounding mode from the last operand 4758 int RoundMode = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 4759 if (RoundMode == (int)RoundingMode::TowardPositive) 4760 Opc = AMDGPUISD::FPTRUNC_ROUND_UPWARD; 4761 else if (RoundMode == (int)RoundingMode::TowardNegative) 4762 Opc = AMDGPUISD::FPTRUNC_ROUND_DOWNWARD; 4763 else 4764 return SDValue(); 4765 4766 return DAG.getNode(Opc, DL, Op.getNode()->getVTList(), Op->getOperand(0)); 4767 } 4768 case ISD::TRAP: 4769 return lowerTRAP(Op, DAG); 4770 case ISD::DEBUGTRAP: 4771 return lowerDEBUGTRAP(Op, DAG); 4772 case ISD::FABS: 4773 case ISD::FNEG: 4774 case ISD::FCANONICALIZE: 4775 case ISD::BSWAP: 4776 return splitUnaryVectorOp(Op, DAG); 4777 case ISD::FMINNUM: 4778 case ISD::FMAXNUM: 4779 return lowerFMINNUM_FMAXNUM(Op, DAG); 4780 case ISD::FMA: 4781 return splitTernaryVectorOp(Op, DAG); 4782 case ISD::FP_TO_SINT: 4783 case ISD::FP_TO_UINT: 4784 return LowerFP_TO_INT(Op, DAG); 4785 case ISD::SHL: 4786 case ISD::SRA: 4787 case ISD::SRL: 4788 case ISD::ADD: 4789 case ISD::SUB: 4790 case ISD::MUL: 4791 case ISD::SMIN: 4792 case ISD::SMAX: 4793 case ISD::UMIN: 4794 case ISD::UMAX: 4795 case ISD::FADD: 4796 case ISD::FMUL: 4797 case ISD::FMINNUM_IEEE: 4798 case ISD::FMAXNUM_IEEE: 4799 case ISD::UADDSAT: 4800 case ISD::USUBSAT: 4801 case ISD::SADDSAT: 4802 case ISD::SSUBSAT: 4803 return splitBinaryVectorOp(Op, DAG); 4804 case ISD::SMULO: 4805 case ISD::UMULO: 4806 return lowerXMULO(Op, DAG); 4807 case ISD::SMUL_LOHI: 4808 case ISD::UMUL_LOHI: 4809 return lowerXMUL_LOHI(Op, DAG); 4810 case ISD::DYNAMIC_STACKALLOC: 4811 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4812 } 4813 return SDValue(); 4814 } 4815 4816 // Used for D16: Casts the result of an instruction into the right vector, 4817 // packs values if loads return unpacked values. 4818 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4819 const SDLoc &DL, 4820 SelectionDAG &DAG, bool Unpacked) { 4821 if (!LoadVT.isVector()) 4822 return Result; 4823 4824 // Cast back to the original packed type or to a larger type that is a 4825 // multiple of 32 bit for D16. Widening the return type is a required for 4826 // legalization. 4827 EVT FittingLoadVT = LoadVT; 4828 if ((LoadVT.getVectorNumElements() % 2) == 1) { 4829 FittingLoadVT = 4830 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4831 LoadVT.getVectorNumElements() + 1); 4832 } 4833 4834 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4835 // Truncate to v2i16/v4i16. 4836 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger(); 4837 4838 // Workaround legalizer not scalarizing truncate after vector op 4839 // legalization but not creating intermediate vector trunc. 4840 SmallVector<SDValue, 4> Elts; 4841 DAG.ExtractVectorElements(Result, Elts); 4842 for (SDValue &Elt : Elts) 4843 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4844 4845 // Pad illegal v1i16/v3fi6 to v4i16 4846 if ((LoadVT.getVectorNumElements() % 2) == 1) 4847 Elts.push_back(DAG.getUNDEF(MVT::i16)); 4848 4849 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4850 4851 // Bitcast to original type (v2f16/v4f16). 4852 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4853 } 4854 4855 // Cast back to the original packed type. 4856 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4857 } 4858 4859 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4860 MemSDNode *M, 4861 SelectionDAG &DAG, 4862 ArrayRef<SDValue> Ops, 4863 bool IsIntrinsic) const { 4864 SDLoc DL(M); 4865 4866 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4867 EVT LoadVT = M->getValueType(0); 4868 4869 EVT EquivLoadVT = LoadVT; 4870 if (LoadVT.isVector()) { 4871 if (Unpacked) { 4872 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4873 LoadVT.getVectorNumElements()); 4874 } else if ((LoadVT.getVectorNumElements() % 2) == 1) { 4875 // Widen v3f16 to legal type 4876 EquivLoadVT = 4877 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4878 LoadVT.getVectorNumElements() + 1); 4879 } 4880 } 4881 4882 // Change from v4f16/v2f16 to EquivLoadVT. 4883 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4884 4885 SDValue Load 4886 = DAG.getMemIntrinsicNode( 4887 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4888 VTList, Ops, M->getMemoryVT(), 4889 M->getMemOperand()); 4890 4891 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4892 4893 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4894 } 4895 4896 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4897 SelectionDAG &DAG, 4898 ArrayRef<SDValue> Ops) const { 4899 SDLoc DL(M); 4900 EVT LoadVT = M->getValueType(0); 4901 EVT EltType = LoadVT.getScalarType(); 4902 EVT IntVT = LoadVT.changeTypeToInteger(); 4903 4904 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4905 4906 unsigned Opc = 4907 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4908 4909 if (IsD16) { 4910 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4911 } 4912 4913 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4914 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4915 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4916 4917 if (isTypeLegal(LoadVT)) { 4918 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4919 M->getMemOperand(), DAG); 4920 } 4921 4922 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4923 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4924 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4925 M->getMemOperand(), DAG); 4926 return DAG.getMergeValues( 4927 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4928 DL); 4929 } 4930 4931 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4932 SDNode *N, SelectionDAG &DAG) { 4933 EVT VT = N->getValueType(0); 4934 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4935 unsigned CondCode = CD->getZExtValue(); 4936 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4937 return DAG.getUNDEF(VT); 4938 4939 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4940 4941 SDValue LHS = N->getOperand(1); 4942 SDValue RHS = N->getOperand(2); 4943 4944 SDLoc DL(N); 4945 4946 EVT CmpVT = LHS.getValueType(); 4947 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4948 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4949 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4950 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4951 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4952 } 4953 4954 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4955 4956 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4957 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4958 4959 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4960 DAG.getCondCode(CCOpcode)); 4961 if (VT.bitsEq(CCVT)) 4962 return SetCC; 4963 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4964 } 4965 4966 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4967 SDNode *N, SelectionDAG &DAG) { 4968 EVT VT = N->getValueType(0); 4969 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4970 4971 unsigned CondCode = CD->getZExtValue(); 4972 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4973 return DAG.getUNDEF(VT); 4974 4975 SDValue Src0 = N->getOperand(1); 4976 SDValue Src1 = N->getOperand(2); 4977 EVT CmpVT = Src0.getValueType(); 4978 SDLoc SL(N); 4979 4980 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4981 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4982 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4983 } 4984 4985 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4986 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4987 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4988 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4989 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4990 Src1, DAG.getCondCode(CCOpcode)); 4991 if (VT.bitsEq(CCVT)) 4992 return SetCC; 4993 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4994 } 4995 4996 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4997 SelectionDAG &DAG) { 4998 EVT VT = N->getValueType(0); 4999 SDValue Src = N->getOperand(1); 5000 SDLoc SL(N); 5001 5002 if (Src.getOpcode() == ISD::SETCC) { 5003 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 5004 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 5005 Src.getOperand(1), Src.getOperand(2)); 5006 } 5007 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 5008 // (ballot 0) -> 0 5009 if (Arg->isZero()) 5010 return DAG.getConstant(0, SL, VT); 5011 5012 // (ballot 1) -> EXEC/EXEC_LO 5013 if (Arg->isOne()) { 5014 Register Exec; 5015 if (VT.getScalarSizeInBits() == 32) 5016 Exec = AMDGPU::EXEC_LO; 5017 else if (VT.getScalarSizeInBits() == 64) 5018 Exec = AMDGPU::EXEC; 5019 else 5020 return SDValue(); 5021 5022 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 5023 } 5024 } 5025 5026 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 5027 // ISD::SETNE) 5028 return DAG.getNode( 5029 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 5030 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 5031 } 5032 5033 void SITargetLowering::ReplaceNodeResults(SDNode *N, 5034 SmallVectorImpl<SDValue> &Results, 5035 SelectionDAG &DAG) const { 5036 switch (N->getOpcode()) { 5037 case ISD::INSERT_VECTOR_ELT: { 5038 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 5039 Results.push_back(Res); 5040 return; 5041 } 5042 case ISD::EXTRACT_VECTOR_ELT: { 5043 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 5044 Results.push_back(Res); 5045 return; 5046 } 5047 case ISD::INTRINSIC_WO_CHAIN: { 5048 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 5049 switch (IID) { 5050 case Intrinsic::amdgcn_cvt_pkrtz: { 5051 SDValue Src0 = N->getOperand(1); 5052 SDValue Src1 = N->getOperand(2); 5053 SDLoc SL(N); 5054 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 5055 Src0, Src1); 5056 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 5057 return; 5058 } 5059 case Intrinsic::amdgcn_cvt_pknorm_i16: 5060 case Intrinsic::amdgcn_cvt_pknorm_u16: 5061 case Intrinsic::amdgcn_cvt_pk_i16: 5062 case Intrinsic::amdgcn_cvt_pk_u16: { 5063 SDValue Src0 = N->getOperand(1); 5064 SDValue Src1 = N->getOperand(2); 5065 SDLoc SL(N); 5066 unsigned Opcode; 5067 5068 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 5069 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 5070 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 5071 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 5072 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 5073 Opcode = AMDGPUISD::CVT_PK_I16_I32; 5074 else 5075 Opcode = AMDGPUISD::CVT_PK_U16_U32; 5076 5077 EVT VT = N->getValueType(0); 5078 if (isTypeLegal(VT)) 5079 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 5080 else { 5081 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 5082 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 5083 } 5084 return; 5085 } 5086 } 5087 break; 5088 } 5089 case ISD::INTRINSIC_W_CHAIN: { 5090 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 5091 if (Res.getOpcode() == ISD::MERGE_VALUES) { 5092 // FIXME: Hacky 5093 for (unsigned I = 0; I < Res.getNumOperands(); I++) { 5094 Results.push_back(Res.getOperand(I)); 5095 } 5096 } else { 5097 Results.push_back(Res); 5098 Results.push_back(Res.getValue(1)); 5099 } 5100 return; 5101 } 5102 5103 break; 5104 } 5105 case ISD::SELECT: { 5106 SDLoc SL(N); 5107 EVT VT = N->getValueType(0); 5108 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 5109 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 5110 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 5111 5112 EVT SelectVT = NewVT; 5113 if (NewVT.bitsLT(MVT::i32)) { 5114 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 5115 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 5116 SelectVT = MVT::i32; 5117 } 5118 5119 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 5120 N->getOperand(0), LHS, RHS); 5121 5122 if (NewVT != SelectVT) 5123 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 5124 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 5125 return; 5126 } 5127 case ISD::FNEG: { 5128 if (N->getValueType(0) != MVT::v2f16) 5129 break; 5130 5131 SDLoc SL(N); 5132 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 5133 5134 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 5135 BC, 5136 DAG.getConstant(0x80008000, SL, MVT::i32)); 5137 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 5138 return; 5139 } 5140 case ISD::FABS: { 5141 if (N->getValueType(0) != MVT::v2f16) 5142 break; 5143 5144 SDLoc SL(N); 5145 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 5146 5147 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 5148 BC, 5149 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 5150 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 5151 return; 5152 } 5153 default: 5154 break; 5155 } 5156 } 5157 5158 /// Helper function for LowerBRCOND 5159 static SDNode *findUser(SDValue Value, unsigned Opcode) { 5160 5161 SDNode *Parent = Value.getNode(); 5162 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 5163 I != E; ++I) { 5164 5165 if (I.getUse().get() != Value) 5166 continue; 5167 5168 if (I->getOpcode() == Opcode) 5169 return *I; 5170 } 5171 return nullptr; 5172 } 5173 5174 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 5175 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 5176 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 5177 case Intrinsic::amdgcn_if: 5178 return AMDGPUISD::IF; 5179 case Intrinsic::amdgcn_else: 5180 return AMDGPUISD::ELSE; 5181 case Intrinsic::amdgcn_loop: 5182 return AMDGPUISD::LOOP; 5183 case Intrinsic::amdgcn_end_cf: 5184 llvm_unreachable("should not occur"); 5185 default: 5186 return 0; 5187 } 5188 } 5189 5190 // break, if_break, else_break are all only used as inputs to loop, not 5191 // directly as branch conditions. 5192 return 0; 5193 } 5194 5195 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 5196 const Triple &TT = getTargetMachine().getTargetTriple(); 5197 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5198 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5199 AMDGPU::shouldEmitConstantsToTextSection(TT); 5200 } 5201 5202 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 5203 // FIXME: Either avoid relying on address space here or change the default 5204 // address space for functions to avoid the explicit check. 5205 return (GV->getValueType()->isFunctionTy() || 5206 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 5207 !shouldEmitFixup(GV) && 5208 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 5209 } 5210 5211 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 5212 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 5213 } 5214 5215 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 5216 if (!GV->hasExternalLinkage()) 5217 return true; 5218 5219 const auto OS = getTargetMachine().getTargetTriple().getOS(); 5220 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 5221 } 5222 5223 /// This transforms the control flow intrinsics to get the branch destination as 5224 /// last parameter, also switches branch target with BR if the need arise 5225 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 5226 SelectionDAG &DAG) const { 5227 SDLoc DL(BRCOND); 5228 5229 SDNode *Intr = BRCOND.getOperand(1).getNode(); 5230 SDValue Target = BRCOND.getOperand(2); 5231 SDNode *BR = nullptr; 5232 SDNode *SetCC = nullptr; 5233 5234 if (Intr->getOpcode() == ISD::SETCC) { 5235 // As long as we negate the condition everything is fine 5236 SetCC = Intr; 5237 Intr = SetCC->getOperand(0).getNode(); 5238 5239 } else { 5240 // Get the target from BR if we don't negate the condition 5241 BR = findUser(BRCOND, ISD::BR); 5242 assert(BR && "brcond missing unconditional branch user"); 5243 Target = BR->getOperand(1); 5244 } 5245 5246 unsigned CFNode = isCFIntrinsic(Intr); 5247 if (CFNode == 0) { 5248 // This is a uniform branch so we don't need to legalize. 5249 return BRCOND; 5250 } 5251 5252 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 5253 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 5254 5255 assert(!SetCC || 5256 (SetCC->getConstantOperandVal(1) == 1 && 5257 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 5258 ISD::SETNE)); 5259 5260 // operands of the new intrinsic call 5261 SmallVector<SDValue, 4> Ops; 5262 if (HaveChain) 5263 Ops.push_back(BRCOND.getOperand(0)); 5264 5265 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 5266 Ops.push_back(Target); 5267 5268 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 5269 5270 // build the new intrinsic call 5271 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 5272 5273 if (!HaveChain) { 5274 SDValue Ops[] = { 5275 SDValue(Result, 0), 5276 BRCOND.getOperand(0) 5277 }; 5278 5279 Result = DAG.getMergeValues(Ops, DL).getNode(); 5280 } 5281 5282 if (BR) { 5283 // Give the branch instruction our target 5284 SDValue Ops[] = { 5285 BR->getOperand(0), 5286 BRCOND.getOperand(2) 5287 }; 5288 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5289 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5290 } 5291 5292 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5293 5294 // Copy the intrinsic results to registers 5295 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5296 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5297 if (!CopyToReg) 5298 continue; 5299 5300 Chain = DAG.getCopyToReg( 5301 Chain, DL, 5302 CopyToReg->getOperand(1), 5303 SDValue(Result, i - 1), 5304 SDValue()); 5305 5306 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5307 } 5308 5309 // Remove the old intrinsic from the chain 5310 DAG.ReplaceAllUsesOfValueWith( 5311 SDValue(Intr, Intr->getNumValues() - 1), 5312 Intr->getOperand(0)); 5313 5314 return Chain; 5315 } 5316 5317 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5318 SelectionDAG &DAG) const { 5319 MVT VT = Op.getSimpleValueType(); 5320 SDLoc DL(Op); 5321 // Checking the depth 5322 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5323 return DAG.getConstant(0, DL, VT); 5324 5325 MachineFunction &MF = DAG.getMachineFunction(); 5326 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5327 // Check for kernel and shader functions 5328 if (Info->isEntryFunction()) 5329 return DAG.getConstant(0, DL, VT); 5330 5331 MachineFrameInfo &MFI = MF.getFrameInfo(); 5332 // There is a call to @llvm.returnaddress in this function 5333 MFI.setReturnAddressIsTaken(true); 5334 5335 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5336 // Get the return address reg and mark it as an implicit live-in 5337 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5338 5339 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5340 } 5341 5342 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5343 SDValue Op, 5344 const SDLoc &DL, 5345 EVT VT) const { 5346 return Op.getValueType().bitsLE(VT) ? 5347 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5348 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5349 DAG.getTargetConstant(0, DL, MVT::i32)); 5350 } 5351 5352 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5353 assert(Op.getValueType() == MVT::f16 && 5354 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5355 5356 SDValue Src = Op.getOperand(0); 5357 EVT SrcVT = Src.getValueType(); 5358 if (SrcVT != MVT::f64) 5359 return Op; 5360 5361 SDLoc DL(Op); 5362 5363 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5364 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5365 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5366 } 5367 5368 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5369 SelectionDAG &DAG) const { 5370 EVT VT = Op.getValueType(); 5371 const MachineFunction &MF = DAG.getMachineFunction(); 5372 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5373 bool IsIEEEMode = Info->getMode().IEEE; 5374 5375 // FIXME: Assert during selection that this is only selected for 5376 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5377 // mode functions, but this happens to be OK since it's only done in cases 5378 // where there is known no sNaN. 5379 if (IsIEEEMode) 5380 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5381 5382 if (VT == MVT::v4f16 || VT == MVT::v8f16) 5383 return splitBinaryVectorOp(Op, DAG); 5384 return Op; 5385 } 5386 5387 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5388 EVT VT = Op.getValueType(); 5389 SDLoc SL(Op); 5390 SDValue LHS = Op.getOperand(0); 5391 SDValue RHS = Op.getOperand(1); 5392 bool isSigned = Op.getOpcode() == ISD::SMULO; 5393 5394 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5395 const APInt &C = RHSC->getAPIntValue(); 5396 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5397 if (C.isPowerOf2()) { 5398 // smulo(x, signed_min) is same as umulo(x, signed_min). 5399 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5400 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5401 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5402 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5403 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5404 SL, VT, Result, ShiftAmt), 5405 LHS, ISD::SETNE); 5406 return DAG.getMergeValues({ Result, Overflow }, SL); 5407 } 5408 } 5409 5410 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5411 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5412 SL, VT, LHS, RHS); 5413 5414 SDValue Sign = isSigned 5415 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5416 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5417 : DAG.getConstant(0, SL, VT); 5418 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5419 5420 return DAG.getMergeValues({ Result, Overflow }, SL); 5421 } 5422 5423 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const { 5424 if (Op->isDivergent()) { 5425 // Select to V_MAD_[IU]64_[IU]32. 5426 return Op; 5427 } 5428 if (Subtarget->hasSMulHi()) { 5429 // Expand to S_MUL_I32 + S_MUL_HI_[IU]32. 5430 return SDValue(); 5431 } 5432 // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to 5433 // calculate the high part, so we might as well do the whole thing with 5434 // V_MAD_[IU]64_[IU]32. 5435 return Op; 5436 } 5437 5438 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5439 if (!Subtarget->isTrapHandlerEnabled() || 5440 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) 5441 return lowerTrapEndpgm(Op, DAG); 5442 5443 if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) { 5444 switch (*HsaAbiVer) { 5445 case ELF::ELFABIVERSION_AMDGPU_HSA_V2: 5446 case ELF::ELFABIVERSION_AMDGPU_HSA_V3: 5447 return lowerTrapHsaQueuePtr(Op, DAG); 5448 case ELF::ELFABIVERSION_AMDGPU_HSA_V4: 5449 case ELF::ELFABIVERSION_AMDGPU_HSA_V5: 5450 return Subtarget->supportsGetDoorbellID() ? 5451 lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG); 5452 } 5453 } 5454 5455 llvm_unreachable("Unknown trap handler"); 5456 } 5457 5458 SDValue SITargetLowering::lowerTrapEndpgm( 5459 SDValue Op, SelectionDAG &DAG) const { 5460 SDLoc SL(Op); 5461 SDValue Chain = Op.getOperand(0); 5462 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5463 } 5464 5465 SDValue SITargetLowering::lowerTrapHsaQueuePtr( 5466 SDValue Op, SelectionDAG &DAG) const { 5467 SDLoc SL(Op); 5468 SDValue Chain = Op.getOperand(0); 5469 5470 MachineFunction &MF = DAG.getMachineFunction(); 5471 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5472 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5473 5474 SDValue QueuePtr; 5475 if (UserSGPR == AMDGPU::NoRegister) { 5476 // We probably are in a function incorrectly marked with 5477 // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the trap, 5478 // so just use a null pointer. 5479 QueuePtr = DAG.getConstant(0, SL, MVT::i64); 5480 } else { 5481 QueuePtr = CreateLiveInRegister( 5482 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5483 } 5484 5485 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5486 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5487 QueuePtr, SDValue()); 5488 5489 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5490 SDValue Ops[] = { 5491 ToReg, 5492 DAG.getTargetConstant(TrapID, SL, MVT::i16), 5493 SGPR01, 5494 ToReg.getValue(1) 5495 }; 5496 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5497 } 5498 5499 SDValue SITargetLowering::lowerTrapHsa( 5500 SDValue Op, SelectionDAG &DAG) const { 5501 SDLoc SL(Op); 5502 SDValue Chain = Op.getOperand(0); 5503 5504 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5505 SDValue Ops[] = { 5506 Chain, 5507 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5508 }; 5509 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5510 } 5511 5512 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5513 SDLoc SL(Op); 5514 SDValue Chain = Op.getOperand(0); 5515 MachineFunction &MF = DAG.getMachineFunction(); 5516 5517 if (!Subtarget->isTrapHandlerEnabled() || 5518 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) { 5519 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5520 "debugtrap handler not supported", 5521 Op.getDebugLoc(), 5522 DS_Warning); 5523 LLVMContext &Ctx = MF.getFunction().getContext(); 5524 Ctx.diagnose(NoTrap); 5525 return Chain; 5526 } 5527 5528 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap); 5529 SDValue Ops[] = { 5530 Chain, 5531 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5532 }; 5533 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5534 } 5535 5536 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5537 SelectionDAG &DAG) const { 5538 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5539 if (Subtarget->hasApertureRegs()) { 5540 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5541 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5542 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5543 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5544 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5545 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5546 unsigned Encoding = 5547 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5548 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5549 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5550 5551 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5552 SDValue ApertureReg = SDValue( 5553 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5554 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5555 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5556 } 5557 5558 MachineFunction &MF = DAG.getMachineFunction(); 5559 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5560 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5561 if (UserSGPR == AMDGPU::NoRegister) { 5562 // We probably are in a function incorrectly marked with 5563 // amdgpu-no-queue-ptr. This is undefined. 5564 return DAG.getUNDEF(MVT::i32); 5565 } 5566 5567 SDValue QueuePtr = CreateLiveInRegister( 5568 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5569 5570 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5571 // private_segment_aperture_base_hi. 5572 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5573 5574 SDValue Ptr = 5575 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5576 5577 // TODO: Use custom target PseudoSourceValue. 5578 // TODO: We should use the value from the IR intrinsic call, but it might not 5579 // be available and how do we get it? 5580 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5581 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5582 commonAlignment(Align(64), StructOffset), 5583 MachineMemOperand::MODereferenceable | 5584 MachineMemOperand::MOInvariant); 5585 } 5586 5587 /// Return true if the value is a known valid address, such that a null check is 5588 /// not necessary. 5589 static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG, 5590 const AMDGPUTargetMachine &TM, unsigned AddrSpace) { 5591 if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) || 5592 isa<BasicBlockSDNode>(Val)) 5593 return true; 5594 5595 if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val)) 5596 return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace); 5597 5598 // TODO: Search through arithmetic, handle arguments and loads 5599 // marked nonnull. 5600 return false; 5601 } 5602 5603 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5604 SelectionDAG &DAG) const { 5605 SDLoc SL(Op); 5606 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5607 5608 SDValue Src = ASC->getOperand(0); 5609 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5610 unsigned SrcAS = ASC->getSrcAddressSpace(); 5611 5612 const AMDGPUTargetMachine &TM = 5613 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5614 5615 // flat -> local/private 5616 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) { 5617 unsigned DestAS = ASC->getDestAddressSpace(); 5618 5619 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5620 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5621 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5622 5623 if (isKnownNonNull(Src, DAG, TM, SrcAS)) 5624 return Ptr; 5625 5626 unsigned NullVal = TM.getNullPointerValue(DestAS); 5627 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5628 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5629 5630 return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr, 5631 SegmentNullPtr); 5632 } 5633 } 5634 5635 // local/private -> flat 5636 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5637 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5638 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5639 5640 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5641 SDValue CvtPtr = 5642 DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5643 CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr); 5644 5645 if (isKnownNonNull(Src, DAG, TM, SrcAS)) 5646 return CvtPtr; 5647 5648 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5649 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5650 5651 SDValue NonNull 5652 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5653 5654 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr, 5655 FlatNullPtr); 5656 } 5657 } 5658 5659 if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5660 Op.getValueType() == MVT::i64) { 5661 const SIMachineFunctionInfo *Info = 5662 DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>(); 5663 SDValue Hi = DAG.getConstant(Info->get32BitAddressHighBits(), SL, MVT::i32); 5664 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Hi); 5665 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 5666 } 5667 5668 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5669 Src.getValueType() == MVT::i64) 5670 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5671 5672 // global <-> flat are no-ops and never emitted. 5673 5674 const MachineFunction &MF = DAG.getMachineFunction(); 5675 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5676 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5677 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5678 5679 return DAG.getUNDEF(ASC->getValueType(0)); 5680 } 5681 5682 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5683 // the small vector and inserting them into the big vector. That is better than 5684 // the default expansion of doing it via a stack slot. Even though the use of 5685 // the stack slot would be optimized away afterwards, the stack slot itself 5686 // remains. 5687 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5688 SelectionDAG &DAG) const { 5689 SDValue Vec = Op.getOperand(0); 5690 SDValue Ins = Op.getOperand(1); 5691 SDValue Idx = Op.getOperand(2); 5692 EVT VecVT = Vec.getValueType(); 5693 EVT InsVT = Ins.getValueType(); 5694 EVT EltVT = VecVT.getVectorElementType(); 5695 unsigned InsNumElts = InsVT.getVectorNumElements(); 5696 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5697 SDLoc SL(Op); 5698 5699 for (unsigned I = 0; I != InsNumElts; ++I) { 5700 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5701 DAG.getConstant(I, SL, MVT::i32)); 5702 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5703 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5704 } 5705 return Vec; 5706 } 5707 5708 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5709 SelectionDAG &DAG) const { 5710 SDValue Vec = Op.getOperand(0); 5711 SDValue InsVal = Op.getOperand(1); 5712 SDValue Idx = Op.getOperand(2); 5713 EVT VecVT = Vec.getValueType(); 5714 EVT EltVT = VecVT.getVectorElementType(); 5715 unsigned VecSize = VecVT.getSizeInBits(); 5716 unsigned EltSize = EltVT.getSizeInBits(); 5717 5718 5719 assert(VecSize <= 64); 5720 5721 unsigned NumElts = VecVT.getVectorNumElements(); 5722 SDLoc SL(Op); 5723 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5724 5725 if (NumElts == 4 && EltSize == 16 && KIdx) { 5726 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5727 5728 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5729 DAG.getConstant(0, SL, MVT::i32)); 5730 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5731 DAG.getConstant(1, SL, MVT::i32)); 5732 5733 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5734 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5735 5736 unsigned Idx = KIdx->getZExtValue(); 5737 bool InsertLo = Idx < 2; 5738 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5739 InsertLo ? LoVec : HiVec, 5740 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5741 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5742 5743 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5744 5745 SDValue Concat = InsertLo ? 5746 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5747 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5748 5749 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5750 } 5751 5752 if (isa<ConstantSDNode>(Idx)) 5753 return SDValue(); 5754 5755 MVT IntVT = MVT::getIntegerVT(VecSize); 5756 5757 // Avoid stack access for dynamic indexing. 5758 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5759 5760 // Create a congruent vector with the target value in each element so that 5761 // the required element can be masked and ORed into the target vector. 5762 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5763 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5764 5765 assert(isPowerOf2_32(EltSize)); 5766 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5767 5768 // Convert vector index to bit-index. 5769 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5770 5771 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5772 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5773 DAG.getConstant(0xffff, SL, IntVT), 5774 ScaledIdx); 5775 5776 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5777 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5778 DAG.getNOT(SL, BFM, IntVT), BCVec); 5779 5780 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5781 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5782 } 5783 5784 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5785 SelectionDAG &DAG) const { 5786 SDLoc SL(Op); 5787 5788 EVT ResultVT = Op.getValueType(); 5789 SDValue Vec = Op.getOperand(0); 5790 SDValue Idx = Op.getOperand(1); 5791 EVT VecVT = Vec.getValueType(); 5792 unsigned VecSize = VecVT.getSizeInBits(); 5793 EVT EltVT = VecVT.getVectorElementType(); 5794 5795 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5796 5797 // Make sure we do any optimizations that will make it easier to fold 5798 // source modifiers before obscuring it with bit operations. 5799 5800 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5801 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5802 return Combined; 5803 5804 if (VecSize == 128) { 5805 SDValue Lo, Hi; 5806 EVT LoVT, HiVT; 5807 SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec); 5808 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5809 Lo = 5810 DAG.getBitcast(LoVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, 5811 V2, DAG.getConstant(0, SL, MVT::i32))); 5812 Hi = 5813 DAG.getBitcast(HiVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, 5814 V2, DAG.getConstant(1, SL, MVT::i32))); 5815 EVT IdxVT = Idx.getValueType(); 5816 unsigned NElem = VecVT.getVectorNumElements(); 5817 assert(isPowerOf2_32(NElem)); 5818 SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT); 5819 SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask); 5820 SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT); 5821 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx); 5822 } 5823 5824 assert(VecSize <= 64); 5825 5826 unsigned EltSize = EltVT.getSizeInBits(); 5827 assert(isPowerOf2_32(EltSize)); 5828 5829 MVT IntVT = MVT::getIntegerVT(VecSize); 5830 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5831 5832 // Convert vector index to bit-index (* EltSize) 5833 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5834 5835 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5836 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5837 5838 if (ResultVT == MVT::f16) { 5839 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5840 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5841 } 5842 5843 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5844 } 5845 5846 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5847 assert(Elt % 2 == 0); 5848 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5849 } 5850 5851 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5852 SelectionDAG &DAG) const { 5853 SDLoc SL(Op); 5854 EVT ResultVT = Op.getValueType(); 5855 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5856 5857 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5858 EVT EltVT = PackVT.getVectorElementType(); 5859 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5860 5861 // vector_shuffle <0,1,6,7> lhs, rhs 5862 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5863 // 5864 // vector_shuffle <6,7,2,3> lhs, rhs 5865 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5866 // 5867 // vector_shuffle <6,7,0,1> lhs, rhs 5868 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5869 5870 // Avoid scalarizing when both halves are reading from consecutive elements. 5871 SmallVector<SDValue, 4> Pieces; 5872 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5873 if (elementPairIsContiguous(SVN->getMask(), I)) { 5874 const int Idx = SVN->getMaskElt(I); 5875 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5876 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5877 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5878 PackVT, SVN->getOperand(VecIdx), 5879 DAG.getConstant(EltIdx, SL, MVT::i32)); 5880 Pieces.push_back(SubVec); 5881 } else { 5882 const int Idx0 = SVN->getMaskElt(I); 5883 const int Idx1 = SVN->getMaskElt(I + 1); 5884 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5885 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5886 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5887 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5888 5889 SDValue Vec0 = SVN->getOperand(VecIdx0); 5890 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5891 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5892 5893 SDValue Vec1 = SVN->getOperand(VecIdx1); 5894 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5895 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5896 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5897 } 5898 } 5899 5900 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5901 } 5902 5903 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5904 SelectionDAG &DAG) const { 5905 SDLoc SL(Op); 5906 EVT VT = Op.getValueType(); 5907 5908 if (VT == MVT::v4i16 || VT == MVT::v4f16 || 5909 VT == MVT::v8i16 || VT == MVT::v8f16) { 5910 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 5911 VT.getVectorNumElements() / 2); 5912 MVT HalfIntVT = MVT::getIntegerVT(HalfVT.getSizeInBits()); 5913 5914 // Turn into pair of packed build_vectors. 5915 // TODO: Special case for constants that can be materialized with s_mov_b64. 5916 SmallVector<SDValue, 4> LoOps, HiOps; 5917 for (unsigned I = 0, E = VT.getVectorNumElements() / 2; I != E; ++I) { 5918 LoOps.push_back(Op.getOperand(I)); 5919 HiOps.push_back(Op.getOperand(I + E)); 5920 } 5921 SDValue Lo = DAG.getBuildVector(HalfVT, SL, LoOps); 5922 SDValue Hi = DAG.getBuildVector(HalfVT, SL, HiOps); 5923 5924 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Lo); 5925 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Hi); 5926 5927 SDValue Blend = DAG.getBuildVector(MVT::getVectorVT(HalfIntVT, 2), SL, 5928 { CastLo, CastHi }); 5929 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5930 } 5931 5932 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5933 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5934 5935 SDValue Lo = Op.getOperand(0); 5936 SDValue Hi = Op.getOperand(1); 5937 5938 // Avoid adding defined bits with the zero_extend. 5939 if (Hi.isUndef()) { 5940 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5941 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5942 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5943 } 5944 5945 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5946 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5947 5948 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5949 DAG.getConstant(16, SL, MVT::i32)); 5950 if (Lo.isUndef()) 5951 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5952 5953 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5954 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5955 5956 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5957 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5958 } 5959 5960 bool 5961 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5962 // We can fold offsets for anything that doesn't require a GOT relocation. 5963 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5964 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5965 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5966 !shouldEmitGOTReloc(GA->getGlobal()); 5967 } 5968 5969 static SDValue 5970 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5971 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5972 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5973 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5974 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5975 // lowered to the following code sequence: 5976 // 5977 // For constant address space: 5978 // s_getpc_b64 s[0:1] 5979 // s_add_u32 s0, s0, $symbol 5980 // s_addc_u32 s1, s1, 0 5981 // 5982 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5983 // a fixup or relocation is emitted to replace $symbol with a literal 5984 // constant, which is a pc-relative offset from the encoding of the $symbol 5985 // operand to the global variable. 5986 // 5987 // For global address space: 5988 // s_getpc_b64 s[0:1] 5989 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5990 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5991 // 5992 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5993 // fixups or relocations are emitted to replace $symbol@*@lo and 5994 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5995 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5996 // operand to the global variable. 5997 // 5998 // What we want here is an offset from the value returned by s_getpc 5999 // (which is the address of the s_add_u32 instruction) to the global 6000 // variable, but since the encoding of $symbol starts 4 bytes after the start 6001 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 6002 // small. This requires us to add 4 to the global variable offset in order to 6003 // compute the correct address. Similarly for the s_addc_u32 instruction, the 6004 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 6005 // instruction. 6006 SDValue PtrLo = 6007 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 6008 SDValue PtrHi; 6009 if (GAFlags == SIInstrInfo::MO_NONE) { 6010 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 6011 } else { 6012 PtrHi = 6013 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 6014 } 6015 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 6016 } 6017 6018 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 6019 SDValue Op, 6020 SelectionDAG &DAG) const { 6021 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 6022 SDLoc DL(GSD); 6023 EVT PtrVT = Op.getValueType(); 6024 6025 const GlobalValue *GV = GSD->getGlobal(); 6026 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 6027 shouldUseLDSConstAddress(GV)) || 6028 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 6029 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 6030 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 6031 GV->hasExternalLinkage()) { 6032 Type *Ty = GV->getValueType(); 6033 // HIP uses an unsized array `extern __shared__ T s[]` or similar 6034 // zero-sized type in other languages to declare the dynamic shared 6035 // memory which size is not known at the compile time. They will be 6036 // allocated by the runtime and placed directly after the static 6037 // allocated ones. They all share the same offset. 6038 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 6039 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 6040 // Adjust alignment for that dynamic shared memory array. 6041 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 6042 return SDValue( 6043 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 6044 } 6045 } 6046 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 6047 } 6048 6049 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 6050 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 6051 SIInstrInfo::MO_ABS32_LO); 6052 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 6053 } 6054 6055 if (shouldEmitFixup(GV)) 6056 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 6057 else if (shouldEmitPCReloc(GV)) 6058 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 6059 SIInstrInfo::MO_REL32); 6060 6061 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 6062 SIInstrInfo::MO_GOTPCREL32); 6063 6064 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 6065 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 6066 const DataLayout &DataLayout = DAG.getDataLayout(); 6067 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 6068 MachinePointerInfo PtrInfo 6069 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 6070 6071 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 6072 MachineMemOperand::MODereferenceable | 6073 MachineMemOperand::MOInvariant); 6074 } 6075 6076 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 6077 const SDLoc &DL, SDValue V) const { 6078 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 6079 // the destination register. 6080 // 6081 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 6082 // so we will end up with redundant moves to m0. 6083 // 6084 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 6085 6086 // A Null SDValue creates a glue result. 6087 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 6088 V, Chain); 6089 return SDValue(M0, 0); 6090 } 6091 6092 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 6093 SDValue Op, 6094 MVT VT, 6095 unsigned Offset) const { 6096 SDLoc SL(Op); 6097 SDValue Param = lowerKernargMemParameter( 6098 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 6099 // The local size values will have the hi 16-bits as zero. 6100 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 6101 DAG.getValueType(VT)); 6102 } 6103 6104 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 6105 EVT VT) { 6106 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 6107 "non-hsa intrinsic with hsa target", 6108 DL.getDebugLoc()); 6109 DAG.getContext()->diagnose(BadIntrin); 6110 return DAG.getUNDEF(VT); 6111 } 6112 6113 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 6114 EVT VT) { 6115 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 6116 "intrinsic not supported on subtarget", 6117 DL.getDebugLoc()); 6118 DAG.getContext()->diagnose(BadIntrin); 6119 return DAG.getUNDEF(VT); 6120 } 6121 6122 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 6123 ArrayRef<SDValue> Elts) { 6124 assert(!Elts.empty()); 6125 MVT Type; 6126 unsigned NumElts = Elts.size(); 6127 6128 if (NumElts <= 8) { 6129 Type = MVT::getVectorVT(MVT::f32, NumElts); 6130 } else { 6131 assert(Elts.size() <= 16); 6132 Type = MVT::v16f32; 6133 NumElts = 16; 6134 } 6135 6136 SmallVector<SDValue, 16> VecElts(NumElts); 6137 for (unsigned i = 0; i < Elts.size(); ++i) { 6138 SDValue Elt = Elts[i]; 6139 if (Elt.getValueType() != MVT::f32) 6140 Elt = DAG.getBitcast(MVT::f32, Elt); 6141 VecElts[i] = Elt; 6142 } 6143 for (unsigned i = Elts.size(); i < NumElts; ++i) 6144 VecElts[i] = DAG.getUNDEF(MVT::f32); 6145 6146 if (NumElts == 1) 6147 return VecElts[0]; 6148 return DAG.getBuildVector(Type, DL, VecElts); 6149 } 6150 6151 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 6152 SDValue Src, int ExtraElts) { 6153 EVT SrcVT = Src.getValueType(); 6154 6155 SmallVector<SDValue, 8> Elts; 6156 6157 if (SrcVT.isVector()) 6158 DAG.ExtractVectorElements(Src, Elts); 6159 else 6160 Elts.push_back(Src); 6161 6162 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 6163 while (ExtraElts--) 6164 Elts.push_back(Undef); 6165 6166 return DAG.getBuildVector(CastVT, DL, Elts); 6167 } 6168 6169 // Re-construct the required return value for a image load intrinsic. 6170 // This is more complicated due to the optional use TexFailCtrl which means the required 6171 // return type is an aggregate 6172 static SDValue constructRetValue(SelectionDAG &DAG, 6173 MachineSDNode *Result, 6174 ArrayRef<EVT> ResultTypes, 6175 bool IsTexFail, bool Unpacked, bool IsD16, 6176 int DMaskPop, int NumVDataDwords, 6177 const SDLoc &DL) { 6178 // Determine the required return type. This is the same regardless of IsTexFail flag 6179 EVT ReqRetVT = ResultTypes[0]; 6180 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 6181 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 6182 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 6183 6184 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 6185 DMaskPop : (DMaskPop + 1) / 2; 6186 6187 MVT DataDwordVT = NumDataDwords == 1 ? 6188 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 6189 6190 MVT MaskPopVT = MaskPopDwords == 1 ? 6191 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 6192 6193 SDValue Data(Result, 0); 6194 SDValue TexFail; 6195 6196 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) { 6197 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 6198 if (MaskPopVT.isVector()) { 6199 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 6200 SDValue(Result, 0), ZeroIdx); 6201 } else { 6202 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 6203 SDValue(Result, 0), ZeroIdx); 6204 } 6205 } 6206 6207 if (DataDwordVT.isVector()) 6208 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 6209 NumDataDwords - MaskPopDwords); 6210 6211 if (IsD16) 6212 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 6213 6214 EVT LegalReqRetVT = ReqRetVT; 6215 if (!ReqRetVT.isVector()) { 6216 if (!Data.getValueType().isInteger()) 6217 Data = DAG.getNode(ISD::BITCAST, DL, 6218 Data.getValueType().changeTypeToInteger(), Data); 6219 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 6220 } else { 6221 // We need to widen the return vector to a legal type 6222 if ((ReqRetVT.getVectorNumElements() % 2) == 1 && 6223 ReqRetVT.getVectorElementType().getSizeInBits() == 16) { 6224 LegalReqRetVT = 6225 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(), 6226 ReqRetVT.getVectorNumElements() + 1); 6227 } 6228 } 6229 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data); 6230 6231 if (IsTexFail) { 6232 TexFail = 6233 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0), 6234 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 6235 6236 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 6237 } 6238 6239 if (Result->getNumValues() == 1) 6240 return Data; 6241 6242 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 6243 } 6244 6245 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 6246 SDValue *LWE, bool &IsTexFail) { 6247 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 6248 6249 uint64_t Value = TexFailCtrlConst->getZExtValue(); 6250 if (Value) { 6251 IsTexFail = true; 6252 } 6253 6254 SDLoc DL(TexFailCtrlConst); 6255 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 6256 Value &= ~(uint64_t)0x1; 6257 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 6258 Value &= ~(uint64_t)0x2; 6259 6260 return Value == 0; 6261 } 6262 6263 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op, 6264 MVT PackVectorVT, 6265 SmallVectorImpl<SDValue> &PackedAddrs, 6266 unsigned DimIdx, unsigned EndIdx, 6267 unsigned NumGradients) { 6268 SDLoc DL(Op); 6269 for (unsigned I = DimIdx; I < EndIdx; I++) { 6270 SDValue Addr = Op.getOperand(I); 6271 6272 // Gradients are packed with undef for each coordinate. 6273 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 6274 // 1D: undef,dx/dh; undef,dx/dv 6275 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 6276 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 6277 if (((I + 1) >= EndIdx) || 6278 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 6279 I == DimIdx + NumGradients - 1))) { 6280 if (Addr.getValueType() != MVT::i16) 6281 Addr = DAG.getBitcast(MVT::i16, Addr); 6282 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 6283 } else { 6284 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 6285 I++; 6286 } 6287 Addr = DAG.getBitcast(MVT::f32, Addr); 6288 PackedAddrs.push_back(Addr); 6289 } 6290 } 6291 6292 SDValue SITargetLowering::lowerImage(SDValue Op, 6293 const AMDGPU::ImageDimIntrinsicInfo *Intr, 6294 SelectionDAG &DAG, bool WithChain) const { 6295 SDLoc DL(Op); 6296 MachineFunction &MF = DAG.getMachineFunction(); 6297 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 6298 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 6299 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 6300 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 6301 unsigned IntrOpcode = Intr->BaseOpcode; 6302 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget); 6303 6304 SmallVector<EVT, 3> ResultTypes(Op->values()); 6305 SmallVector<EVT, 3> OrigResultTypes(Op->values()); 6306 bool IsD16 = false; 6307 bool IsG16 = false; 6308 bool IsA16 = false; 6309 SDValue VData; 6310 int NumVDataDwords; 6311 bool AdjustRetType = false; 6312 6313 // Offset of intrinsic arguments 6314 const unsigned ArgOffset = WithChain ? 2 : 1; 6315 6316 unsigned DMask; 6317 unsigned DMaskLanes = 0; 6318 6319 if (BaseOpcode->Atomic) { 6320 VData = Op.getOperand(2); 6321 6322 bool Is64Bit = VData.getValueType() == MVT::i64; 6323 if (BaseOpcode->AtomicX2) { 6324 SDValue VData2 = Op.getOperand(3); 6325 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 6326 {VData, VData2}); 6327 if (Is64Bit) 6328 VData = DAG.getBitcast(MVT::v4i32, VData); 6329 6330 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 6331 DMask = Is64Bit ? 0xf : 0x3; 6332 NumVDataDwords = Is64Bit ? 4 : 2; 6333 } else { 6334 DMask = Is64Bit ? 0x3 : 0x1; 6335 NumVDataDwords = Is64Bit ? 2 : 1; 6336 } 6337 } else { 6338 auto *DMaskConst = 6339 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex)); 6340 DMask = DMaskConst->getZExtValue(); 6341 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 6342 6343 if (BaseOpcode->Store) { 6344 VData = Op.getOperand(2); 6345 6346 MVT StoreVT = VData.getSimpleValueType(); 6347 if (StoreVT.getScalarType() == MVT::f16) { 6348 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6349 return Op; // D16 is unsupported for this instruction 6350 6351 IsD16 = true; 6352 VData = handleD16VData(VData, DAG, true); 6353 } 6354 6355 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 6356 } else { 6357 // Work out the num dwords based on the dmask popcount and underlying type 6358 // and whether packing is supported. 6359 MVT LoadVT = ResultTypes[0].getSimpleVT(); 6360 if (LoadVT.getScalarType() == MVT::f16) { 6361 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6362 return Op; // D16 is unsupported for this instruction 6363 6364 IsD16 = true; 6365 } 6366 6367 // Confirm that the return type is large enough for the dmask specified 6368 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 6369 (!LoadVT.isVector() && DMaskLanes > 1)) 6370 return Op; 6371 6372 // The sq block of gfx8 and gfx9 do not estimate register use correctly 6373 // for d16 image_gather4, image_gather4_l, and image_gather4_lz 6374 // instructions. 6375 if (IsD16 && !Subtarget->hasUnpackedD16VMem() && 6376 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug())) 6377 NumVDataDwords = (DMaskLanes + 1) / 2; 6378 else 6379 NumVDataDwords = DMaskLanes; 6380 6381 AdjustRetType = true; 6382 } 6383 } 6384 6385 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd; 6386 SmallVector<SDValue, 4> VAddrs; 6387 6388 // Check for 16 bit addresses or derivatives and pack if true. 6389 MVT VAddrVT = 6390 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType(); 6391 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6392 MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6393 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6394 6395 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType(); 6396 VAddrScalarVT = VAddrVT.getScalarType(); 6397 MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6398 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6399 6400 // Push back extra arguments. 6401 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) { 6402 if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) { 6403 assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument"); 6404 // Special handling of bias when A16 is on. Bias is of type half but 6405 // occupies full 32-bit. 6406 SDValue Bias = DAG.getBuildVector( 6407 MVT::v2f16, DL, 6408 {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)}); 6409 VAddrs.push_back(Bias); 6410 } else { 6411 assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) && 6412 "Bias needs to be converted to 16 bit in A16 mode"); 6413 VAddrs.push_back(Op.getOperand(ArgOffset + I)); 6414 } 6415 } 6416 6417 if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) { 6418 // 16 bit gradients are supported, but are tied to the A16 control 6419 // so both gradients and addresses must be 16 bit 6420 LLVM_DEBUG( 6421 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6422 "require 16 bit args for both gradients and addresses"); 6423 return Op; 6424 } 6425 6426 if (IsA16) { 6427 if (!ST->hasA16()) { 6428 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6429 "support 16 bit addresses\n"); 6430 return Op; 6431 } 6432 } 6433 6434 // We've dealt with incorrect input so we know that if IsA16, IsG16 6435 // are set then we have to compress/pack operands (either address, 6436 // gradient or both) 6437 // In the case where a16 and gradients are tied (no G16 support) then we 6438 // have already verified that both IsA16 and IsG16 are true 6439 if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) { 6440 // Activate g16 6441 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6442 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6443 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6444 } 6445 6446 // Add gradients (packed or unpacked) 6447 if (IsG16) { 6448 // Pack the gradients 6449 // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart); 6450 packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs, 6451 ArgOffset + Intr->GradientStart, 6452 ArgOffset + Intr->CoordStart, Intr->NumGradients); 6453 } else { 6454 for (unsigned I = ArgOffset + Intr->GradientStart; 6455 I < ArgOffset + Intr->CoordStart; I++) 6456 VAddrs.push_back(Op.getOperand(I)); 6457 } 6458 6459 // Add addresses (packed or unpacked) 6460 if (IsA16) { 6461 packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs, 6462 ArgOffset + Intr->CoordStart, VAddrEnd, 6463 0 /* No gradients */); 6464 } else { 6465 // Add uncompressed address 6466 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++) 6467 VAddrs.push_back(Op.getOperand(I)); 6468 } 6469 6470 // If the register allocator cannot place the address registers contiguously 6471 // without introducing moves, then using the non-sequential address encoding 6472 // is always preferable, since it saves VALU instructions and is usually a 6473 // wash in terms of code size or even better. 6474 // 6475 // However, we currently have no way of hinting to the register allocator that 6476 // MIMG addresses should be placed contiguously when it is possible to do so, 6477 // so force non-NSA for the common 2-address case as a heuristic. 6478 // 6479 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6480 // allocation when possible. 6481 bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) && 6482 VAddrs.size() >= 3 && 6483 VAddrs.size() <= (unsigned)ST->getNSAMaxSize(); 6484 SDValue VAddr; 6485 if (!UseNSA) 6486 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6487 6488 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6489 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6490 SDValue Unorm; 6491 if (!BaseOpcode->Sampler) { 6492 Unorm = True; 6493 } else { 6494 auto UnormConst = 6495 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex)); 6496 6497 Unorm = UnormConst->getZExtValue() ? True : False; 6498 } 6499 6500 SDValue TFE; 6501 SDValue LWE; 6502 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex); 6503 bool IsTexFail = false; 6504 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6505 return Op; 6506 6507 if (IsTexFail) { 6508 if (!DMaskLanes) { 6509 // Expecting to get an error flag since TFC is on - and dmask is 0 6510 // Force dmask to be at least 1 otherwise the instruction will fail 6511 DMask = 0x1; 6512 DMaskLanes = 1; 6513 NumVDataDwords = 1; 6514 } 6515 NumVDataDwords += 1; 6516 AdjustRetType = true; 6517 } 6518 6519 // Has something earlier tagged that the return type needs adjusting 6520 // This happens if the instruction is a load or has set TexFailCtrl flags 6521 if (AdjustRetType) { 6522 // NumVDataDwords reflects the true number of dwords required in the return type 6523 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6524 // This is a no-op load. This can be eliminated 6525 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6526 if (isa<MemSDNode>(Op)) 6527 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6528 return Undef; 6529 } 6530 6531 EVT NewVT = NumVDataDwords > 1 ? 6532 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6533 : MVT::i32; 6534 6535 ResultTypes[0] = NewVT; 6536 if (ResultTypes.size() == 3) { 6537 // Original result was aggregate type used for TexFailCtrl results 6538 // The actual instruction returns as a vector type which has now been 6539 // created. Remove the aggregate result. 6540 ResultTypes.erase(&ResultTypes[1]); 6541 } 6542 } 6543 6544 unsigned CPol = cast<ConstantSDNode>( 6545 Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue(); 6546 if (BaseOpcode->Atomic) 6547 CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization 6548 if (CPol & ~AMDGPU::CPol::ALL) 6549 return Op; 6550 6551 SmallVector<SDValue, 26> Ops; 6552 if (BaseOpcode->Store || BaseOpcode->Atomic) 6553 Ops.push_back(VData); // vdata 6554 if (UseNSA) 6555 append_range(Ops, VAddrs); 6556 else 6557 Ops.push_back(VAddr); 6558 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex)); 6559 if (BaseOpcode->Sampler) 6560 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex)); 6561 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6562 if (IsGFX10Plus) 6563 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6564 Ops.push_back(Unorm); 6565 Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32)); 6566 Ops.push_back(IsA16 && // r128, a16 for gfx9 6567 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6568 if (IsGFX10Plus) 6569 Ops.push_back(IsA16 ? True : False); 6570 if (!Subtarget->hasGFX90AInsts()) { 6571 Ops.push_back(TFE); //tfe 6572 } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) { 6573 report_fatal_error("TFE is not supported on this GPU"); 6574 } 6575 Ops.push_back(LWE); // lwe 6576 if (!IsGFX10Plus) 6577 Ops.push_back(DimInfo->DA ? True : False); 6578 if (BaseOpcode->HasD16) 6579 Ops.push_back(IsD16 ? True : False); 6580 if (isa<MemSDNode>(Op)) 6581 Ops.push_back(Op.getOperand(0)); // chain 6582 6583 int NumVAddrDwords = 6584 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6585 int Opcode = -1; 6586 6587 if (IsGFX10Plus) { 6588 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6589 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6590 : AMDGPU::MIMGEncGfx10Default, 6591 NumVDataDwords, NumVAddrDwords); 6592 } else { 6593 if (Subtarget->hasGFX90AInsts()) { 6594 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a, 6595 NumVDataDwords, NumVAddrDwords); 6596 if (Opcode == -1) 6597 report_fatal_error( 6598 "requested image instruction is not supported on this GPU"); 6599 } 6600 if (Opcode == -1 && 6601 Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6602 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6603 NumVDataDwords, NumVAddrDwords); 6604 if (Opcode == -1) 6605 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6606 NumVDataDwords, NumVAddrDwords); 6607 } 6608 assert(Opcode != -1); 6609 6610 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6611 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6612 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6613 DAG.setNodeMemRefs(NewNode, {MemRef}); 6614 } 6615 6616 if (BaseOpcode->AtomicX2) { 6617 SmallVector<SDValue, 1> Elt; 6618 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6619 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6620 } 6621 if (BaseOpcode->Store) 6622 return SDValue(NewNode, 0); 6623 return constructRetValue(DAG, NewNode, 6624 OrigResultTypes, IsTexFail, 6625 Subtarget->hasUnpackedD16VMem(), IsD16, 6626 DMaskLanes, NumVDataDwords, DL); 6627 } 6628 6629 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6630 SDValue Offset, SDValue CachePolicy, 6631 SelectionDAG &DAG) const { 6632 MachineFunction &MF = DAG.getMachineFunction(); 6633 6634 const DataLayout &DataLayout = DAG.getDataLayout(); 6635 Align Alignment = 6636 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6637 6638 MachineMemOperand *MMO = MF.getMachineMemOperand( 6639 MachinePointerInfo(), 6640 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6641 MachineMemOperand::MOInvariant, 6642 VT.getStoreSize(), Alignment); 6643 6644 if (!Offset->isDivergent()) { 6645 SDValue Ops[] = { 6646 Rsrc, 6647 Offset, // Offset 6648 CachePolicy 6649 }; 6650 6651 // Widen vec3 load to vec4. 6652 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6653 EVT WidenedVT = 6654 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6655 auto WidenedOp = DAG.getMemIntrinsicNode( 6656 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6657 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6658 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6659 DAG.getVectorIdxConstant(0, DL)); 6660 return Subvector; 6661 } 6662 6663 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6664 DAG.getVTList(VT), Ops, VT, MMO); 6665 } 6666 6667 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6668 // assume that the buffer is unswizzled. 6669 SmallVector<SDValue, 4> Loads; 6670 unsigned NumLoads = 1; 6671 MVT LoadVT = VT.getSimpleVT(); 6672 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6673 assert((LoadVT.getScalarType() == MVT::i32 || 6674 LoadVT.getScalarType() == MVT::f32)); 6675 6676 if (NumElts == 8 || NumElts == 16) { 6677 NumLoads = NumElts / 4; 6678 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6679 } 6680 6681 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6682 SDValue Ops[] = { 6683 DAG.getEntryNode(), // Chain 6684 Rsrc, // rsrc 6685 DAG.getConstant(0, DL, MVT::i32), // vindex 6686 {}, // voffset 6687 {}, // soffset 6688 {}, // offset 6689 CachePolicy, // cachepolicy 6690 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6691 }; 6692 6693 // Use the alignment to ensure that the required offsets will fit into the 6694 // immediate offsets. 6695 setBufferOffsets(Offset, DAG, &Ops[3], 6696 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6697 6698 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6699 for (unsigned i = 0; i < NumLoads; ++i) { 6700 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6701 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6702 LoadVT, MMO, DAG)); 6703 } 6704 6705 if (NumElts == 8 || NumElts == 16) 6706 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6707 6708 return Loads[0]; 6709 } 6710 6711 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6712 SelectionDAG &DAG) const { 6713 MachineFunction &MF = DAG.getMachineFunction(); 6714 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6715 6716 EVT VT = Op.getValueType(); 6717 SDLoc DL(Op); 6718 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6719 6720 // TODO: Should this propagate fast-math-flags? 6721 6722 switch (IntrinsicID) { 6723 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6724 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6725 return emitNonHSAIntrinsicError(DAG, DL, VT); 6726 return getPreloadedValue(DAG, *MFI, VT, 6727 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6728 } 6729 case Intrinsic::amdgcn_dispatch_ptr: 6730 case Intrinsic::amdgcn_queue_ptr: { 6731 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6732 DiagnosticInfoUnsupported BadIntrin( 6733 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6734 DL.getDebugLoc()); 6735 DAG.getContext()->diagnose(BadIntrin); 6736 return DAG.getUNDEF(VT); 6737 } 6738 6739 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6740 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6741 return getPreloadedValue(DAG, *MFI, VT, RegID); 6742 } 6743 case Intrinsic::amdgcn_implicitarg_ptr: { 6744 if (MFI->isEntryFunction()) 6745 return getImplicitArgPtr(DAG, DL); 6746 return getPreloadedValue(DAG, *MFI, VT, 6747 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6748 } 6749 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6750 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6751 // This only makes sense to call in a kernel, so just lower to null. 6752 return DAG.getConstant(0, DL, VT); 6753 } 6754 6755 return getPreloadedValue(DAG, *MFI, VT, 6756 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6757 } 6758 case Intrinsic::amdgcn_dispatch_id: { 6759 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6760 } 6761 case Intrinsic::amdgcn_rcp: 6762 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6763 case Intrinsic::amdgcn_rsq: 6764 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6765 case Intrinsic::amdgcn_rsq_legacy: 6766 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6767 return emitRemovedIntrinsicError(DAG, DL, VT); 6768 return SDValue(); 6769 case Intrinsic::amdgcn_rcp_legacy: 6770 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6771 return emitRemovedIntrinsicError(DAG, DL, VT); 6772 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6773 case Intrinsic::amdgcn_rsq_clamp: { 6774 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6775 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6776 6777 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6778 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6779 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6780 6781 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6782 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6783 DAG.getConstantFP(Max, DL, VT)); 6784 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6785 DAG.getConstantFP(Min, DL, VT)); 6786 } 6787 case Intrinsic::r600_read_ngroups_x: 6788 if (Subtarget->isAmdHsaOS()) 6789 return emitNonHSAIntrinsicError(DAG, DL, VT); 6790 6791 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6792 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6793 false); 6794 case Intrinsic::r600_read_ngroups_y: 6795 if (Subtarget->isAmdHsaOS()) 6796 return emitNonHSAIntrinsicError(DAG, DL, VT); 6797 6798 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6799 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6800 false); 6801 case Intrinsic::r600_read_ngroups_z: 6802 if (Subtarget->isAmdHsaOS()) 6803 return emitNonHSAIntrinsicError(DAG, DL, VT); 6804 6805 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6806 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6807 false); 6808 case Intrinsic::r600_read_global_size_x: 6809 if (Subtarget->isAmdHsaOS()) 6810 return emitNonHSAIntrinsicError(DAG, DL, VT); 6811 6812 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6813 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6814 Align(4), false); 6815 case Intrinsic::r600_read_global_size_y: 6816 if (Subtarget->isAmdHsaOS()) 6817 return emitNonHSAIntrinsicError(DAG, DL, VT); 6818 6819 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6820 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6821 Align(4), false); 6822 case Intrinsic::r600_read_global_size_z: 6823 if (Subtarget->isAmdHsaOS()) 6824 return emitNonHSAIntrinsicError(DAG, DL, VT); 6825 6826 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6827 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6828 Align(4), false); 6829 case Intrinsic::r600_read_local_size_x: 6830 if (Subtarget->isAmdHsaOS()) 6831 return emitNonHSAIntrinsicError(DAG, DL, VT); 6832 6833 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6834 SI::KernelInputOffsets::LOCAL_SIZE_X); 6835 case Intrinsic::r600_read_local_size_y: 6836 if (Subtarget->isAmdHsaOS()) 6837 return emitNonHSAIntrinsicError(DAG, DL, VT); 6838 6839 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6840 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6841 case Intrinsic::r600_read_local_size_z: 6842 if (Subtarget->isAmdHsaOS()) 6843 return emitNonHSAIntrinsicError(DAG, DL, VT); 6844 6845 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6846 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6847 case Intrinsic::amdgcn_workgroup_id_x: 6848 return getPreloadedValue(DAG, *MFI, VT, 6849 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6850 case Intrinsic::amdgcn_workgroup_id_y: 6851 return getPreloadedValue(DAG, *MFI, VT, 6852 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6853 case Intrinsic::amdgcn_workgroup_id_z: 6854 return getPreloadedValue(DAG, *MFI, VT, 6855 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6856 case Intrinsic::amdgcn_workitem_id_x: 6857 if (Subtarget->getMaxWorkitemID(MF.getFunction(), 0) == 0) 6858 return DAG.getConstant(0, DL, MVT::i32); 6859 6860 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6861 SDLoc(DAG.getEntryNode()), 6862 MFI->getArgInfo().WorkItemIDX); 6863 case Intrinsic::amdgcn_workitem_id_y: 6864 if (Subtarget->getMaxWorkitemID(MF.getFunction(), 1) == 0) 6865 return DAG.getConstant(0, DL, MVT::i32); 6866 6867 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6868 SDLoc(DAG.getEntryNode()), 6869 MFI->getArgInfo().WorkItemIDY); 6870 case Intrinsic::amdgcn_workitem_id_z: 6871 if (Subtarget->getMaxWorkitemID(MF.getFunction(), 2) == 0) 6872 return DAG.getConstant(0, DL, MVT::i32); 6873 6874 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6875 SDLoc(DAG.getEntryNode()), 6876 MFI->getArgInfo().WorkItemIDZ); 6877 case Intrinsic::amdgcn_wavefrontsize: 6878 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6879 SDLoc(Op), MVT::i32); 6880 case Intrinsic::amdgcn_s_buffer_load: { 6881 unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 6882 if (CPol & ~AMDGPU::CPol::ALL) 6883 return Op; 6884 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6885 DAG); 6886 } 6887 case Intrinsic::amdgcn_fdiv_fast: 6888 return lowerFDIV_FAST(Op, DAG); 6889 case Intrinsic::amdgcn_sin: 6890 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6891 6892 case Intrinsic::amdgcn_cos: 6893 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6894 6895 case Intrinsic::amdgcn_mul_u24: 6896 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6897 case Intrinsic::amdgcn_mul_i24: 6898 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6899 6900 case Intrinsic::amdgcn_log_clamp: { 6901 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6902 return SDValue(); 6903 6904 return emitRemovedIntrinsicError(DAG, DL, VT); 6905 } 6906 case Intrinsic::amdgcn_ldexp: 6907 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6908 Op.getOperand(1), Op.getOperand(2)); 6909 6910 case Intrinsic::amdgcn_fract: 6911 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6912 6913 case Intrinsic::amdgcn_class: 6914 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6915 Op.getOperand(1), Op.getOperand(2)); 6916 case Intrinsic::amdgcn_div_fmas: 6917 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6918 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6919 Op.getOperand(4)); 6920 6921 case Intrinsic::amdgcn_div_fixup: 6922 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6923 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6924 6925 case Intrinsic::amdgcn_div_scale: { 6926 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6927 6928 // Translate to the operands expected by the machine instruction. The 6929 // first parameter must be the same as the first instruction. 6930 SDValue Numerator = Op.getOperand(1); 6931 SDValue Denominator = Op.getOperand(2); 6932 6933 // Note this order is opposite of the machine instruction's operations, 6934 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6935 // intrinsic has the numerator as the first operand to match a normal 6936 // division operation. 6937 6938 SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator; 6939 6940 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6941 Denominator, Numerator); 6942 } 6943 case Intrinsic::amdgcn_icmp: { 6944 // There is a Pat that handles this variant, so return it as-is. 6945 if (Op.getOperand(1).getValueType() == MVT::i1 && 6946 Op.getConstantOperandVal(2) == 0 && 6947 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6948 return Op; 6949 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6950 } 6951 case Intrinsic::amdgcn_fcmp: { 6952 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6953 } 6954 case Intrinsic::amdgcn_ballot: 6955 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6956 case Intrinsic::amdgcn_fmed3: 6957 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6958 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6959 case Intrinsic::amdgcn_fdot2: 6960 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6961 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6962 Op.getOperand(4)); 6963 case Intrinsic::amdgcn_fmul_legacy: 6964 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6965 Op.getOperand(1), Op.getOperand(2)); 6966 case Intrinsic::amdgcn_sffbh: 6967 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6968 case Intrinsic::amdgcn_sbfe: 6969 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6970 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6971 case Intrinsic::amdgcn_ubfe: 6972 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6973 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6974 case Intrinsic::amdgcn_cvt_pkrtz: 6975 case Intrinsic::amdgcn_cvt_pknorm_i16: 6976 case Intrinsic::amdgcn_cvt_pknorm_u16: 6977 case Intrinsic::amdgcn_cvt_pk_i16: 6978 case Intrinsic::amdgcn_cvt_pk_u16: { 6979 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6980 EVT VT = Op.getValueType(); 6981 unsigned Opcode; 6982 6983 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6984 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6985 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6986 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6987 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6988 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6989 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6990 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6991 else 6992 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6993 6994 if (isTypeLegal(VT)) 6995 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6996 6997 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6998 Op.getOperand(1), Op.getOperand(2)); 6999 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 7000 } 7001 case Intrinsic::amdgcn_fmad_ftz: 7002 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 7003 Op.getOperand(2), Op.getOperand(3)); 7004 7005 case Intrinsic::amdgcn_if_break: 7006 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 7007 Op->getOperand(1), Op->getOperand(2)), 0); 7008 7009 case Intrinsic::amdgcn_groupstaticsize: { 7010 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 7011 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 7012 return Op; 7013 7014 const Module *M = MF.getFunction().getParent(); 7015 const GlobalValue *GV = 7016 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 7017 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 7018 SIInstrInfo::MO_ABS32_LO); 7019 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 7020 } 7021 case Intrinsic::amdgcn_is_shared: 7022 case Intrinsic::amdgcn_is_private: { 7023 SDLoc SL(Op); 7024 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 7025 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 7026 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 7027 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 7028 Op.getOperand(1)); 7029 7030 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 7031 DAG.getConstant(1, SL, MVT::i32)); 7032 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 7033 } 7034 case Intrinsic::amdgcn_perm: 7035 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1), 7036 Op.getOperand(2), Op.getOperand(3)); 7037 case Intrinsic::amdgcn_reloc_constant: { 7038 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 7039 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 7040 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 7041 auto RelocSymbol = cast<GlobalVariable>( 7042 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 7043 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 7044 SIInstrInfo::MO_ABS32_LO); 7045 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 7046 } 7047 default: 7048 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7049 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7050 return lowerImage(Op, ImageDimIntr, DAG, false); 7051 7052 return Op; 7053 } 7054 } 7055 7056 /// Update \p MMO based on the offset inputs to an intrinsic. 7057 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset, 7058 SDValue SOffset, SDValue Offset, 7059 SDValue VIndex = SDValue()) { 7060 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 7061 !isa<ConstantSDNode>(Offset)) { 7062 // The combined offset is not known to be constant, so we cannot represent 7063 // it in the MMO. Give up. 7064 MMO->setValue((Value *)nullptr); 7065 return; 7066 } 7067 7068 if (VIndex && (!isa<ConstantSDNode>(VIndex) || 7069 !cast<ConstantSDNode>(VIndex)->isZero())) { 7070 // The strided index component of the address is not known to be zero, so we 7071 // cannot represent it in the MMO. Give up. 7072 MMO->setValue((Value *)nullptr); 7073 return; 7074 } 7075 7076 MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() + 7077 cast<ConstantSDNode>(SOffset)->getSExtValue() + 7078 cast<ConstantSDNode>(Offset)->getSExtValue()); 7079 } 7080 7081 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 7082 SelectionDAG &DAG, 7083 unsigned NewOpcode) const { 7084 SDLoc DL(Op); 7085 7086 SDValue VData = Op.getOperand(2); 7087 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7088 SDValue Ops[] = { 7089 Op.getOperand(0), // Chain 7090 VData, // vdata 7091 Op.getOperand(3), // rsrc 7092 DAG.getConstant(0, DL, MVT::i32), // vindex 7093 Offsets.first, // voffset 7094 Op.getOperand(5), // soffset 7095 Offsets.second, // offset 7096 Op.getOperand(6), // cachepolicy 7097 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7098 }; 7099 7100 auto *M = cast<MemSDNode>(Op); 7101 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 7102 7103 EVT MemVT = VData.getValueType(); 7104 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 7105 M->getMemOperand()); 7106 } 7107 7108 // Return a value to use for the idxen operand by examining the vindex operand. 7109 static unsigned getIdxEn(SDValue VIndex) { 7110 if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex)) 7111 // No need to set idxen if vindex is known to be zero. 7112 return VIndexC->getZExtValue() != 0; 7113 return 1; 7114 } 7115 7116 SDValue 7117 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 7118 unsigned NewOpcode) const { 7119 SDLoc DL(Op); 7120 7121 SDValue VData = Op.getOperand(2); 7122 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7123 SDValue Ops[] = { 7124 Op.getOperand(0), // Chain 7125 VData, // vdata 7126 Op.getOperand(3), // rsrc 7127 Op.getOperand(4), // vindex 7128 Offsets.first, // voffset 7129 Op.getOperand(6), // soffset 7130 Offsets.second, // offset 7131 Op.getOperand(7), // cachepolicy 7132 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7133 }; 7134 7135 auto *M = cast<MemSDNode>(Op); 7136 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7137 7138 EVT MemVT = VData.getValueType(); 7139 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 7140 M->getMemOperand()); 7141 } 7142 7143 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 7144 SelectionDAG &DAG) const { 7145 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7146 SDLoc DL(Op); 7147 7148 switch (IntrID) { 7149 case Intrinsic::amdgcn_ds_ordered_add: 7150 case Intrinsic::amdgcn_ds_ordered_swap: { 7151 MemSDNode *M = cast<MemSDNode>(Op); 7152 SDValue Chain = M->getOperand(0); 7153 SDValue M0 = M->getOperand(2); 7154 SDValue Value = M->getOperand(3); 7155 unsigned IndexOperand = M->getConstantOperandVal(7); 7156 unsigned WaveRelease = M->getConstantOperandVal(8); 7157 unsigned WaveDone = M->getConstantOperandVal(9); 7158 7159 unsigned OrderedCountIndex = IndexOperand & 0x3f; 7160 IndexOperand &= ~0x3f; 7161 unsigned CountDw = 0; 7162 7163 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 7164 CountDw = (IndexOperand >> 24) & 0xf; 7165 IndexOperand &= ~(0xf << 24); 7166 7167 if (CountDw < 1 || CountDw > 4) { 7168 report_fatal_error( 7169 "ds_ordered_count: dword count must be between 1 and 4"); 7170 } 7171 } 7172 7173 if (IndexOperand) 7174 report_fatal_error("ds_ordered_count: bad index operand"); 7175 7176 if (WaveDone && !WaveRelease) 7177 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 7178 7179 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 7180 unsigned ShaderType = 7181 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 7182 unsigned Offset0 = OrderedCountIndex << 2; 7183 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 7184 (Instruction << 4); 7185 7186 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 7187 Offset1 |= (CountDw - 1) << 6; 7188 7189 unsigned Offset = Offset0 | (Offset1 << 8); 7190 7191 SDValue Ops[] = { 7192 Chain, 7193 Value, 7194 DAG.getTargetConstant(Offset, DL, MVT::i16), 7195 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 7196 }; 7197 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 7198 M->getVTList(), Ops, M->getMemoryVT(), 7199 M->getMemOperand()); 7200 } 7201 case Intrinsic::amdgcn_ds_fadd: { 7202 MemSDNode *M = cast<MemSDNode>(Op); 7203 unsigned Opc; 7204 switch (IntrID) { 7205 case Intrinsic::amdgcn_ds_fadd: 7206 Opc = ISD::ATOMIC_LOAD_FADD; 7207 break; 7208 } 7209 7210 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 7211 M->getOperand(0), M->getOperand(2), M->getOperand(3), 7212 M->getMemOperand()); 7213 } 7214 case Intrinsic::amdgcn_atomic_inc: 7215 case Intrinsic::amdgcn_atomic_dec: 7216 case Intrinsic::amdgcn_ds_fmin: 7217 case Intrinsic::amdgcn_ds_fmax: { 7218 MemSDNode *M = cast<MemSDNode>(Op); 7219 unsigned Opc; 7220 switch (IntrID) { 7221 case Intrinsic::amdgcn_atomic_inc: 7222 Opc = AMDGPUISD::ATOMIC_INC; 7223 break; 7224 case Intrinsic::amdgcn_atomic_dec: 7225 Opc = AMDGPUISD::ATOMIC_DEC; 7226 break; 7227 case Intrinsic::amdgcn_ds_fmin: 7228 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 7229 break; 7230 case Intrinsic::amdgcn_ds_fmax: 7231 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 7232 break; 7233 default: 7234 llvm_unreachable("Unknown intrinsic!"); 7235 } 7236 SDValue Ops[] = { 7237 M->getOperand(0), // Chain 7238 M->getOperand(2), // Ptr 7239 M->getOperand(3) // Value 7240 }; 7241 7242 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 7243 M->getMemoryVT(), M->getMemOperand()); 7244 } 7245 case Intrinsic::amdgcn_buffer_load: 7246 case Intrinsic::amdgcn_buffer_load_format: { 7247 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 7248 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7249 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7250 SDValue Ops[] = { 7251 Op.getOperand(0), // Chain 7252 Op.getOperand(2), // rsrc 7253 Op.getOperand(3), // vindex 7254 SDValue(), // voffset -- will be set by setBufferOffsets 7255 SDValue(), // soffset -- will be set by setBufferOffsets 7256 SDValue(), // offset -- will be set by setBufferOffsets 7257 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7258 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7259 }; 7260 setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 7261 7262 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 7263 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 7264 7265 EVT VT = Op.getValueType(); 7266 EVT IntVT = VT.changeTypeToInteger(); 7267 auto *M = cast<MemSDNode>(Op); 7268 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7269 EVT LoadVT = Op.getValueType(); 7270 7271 if (LoadVT.getScalarType() == MVT::f16) 7272 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 7273 M, DAG, Ops); 7274 7275 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 7276 if (LoadVT.getScalarType() == MVT::i8 || 7277 LoadVT.getScalarType() == MVT::i16) 7278 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 7279 7280 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 7281 M->getMemOperand(), DAG); 7282 } 7283 case Intrinsic::amdgcn_raw_buffer_load: 7284 case Intrinsic::amdgcn_raw_buffer_load_format: { 7285 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 7286 7287 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7288 SDValue Ops[] = { 7289 Op.getOperand(0), // Chain 7290 Op.getOperand(2), // rsrc 7291 DAG.getConstant(0, DL, MVT::i32), // vindex 7292 Offsets.first, // voffset 7293 Op.getOperand(4), // soffset 7294 Offsets.second, // offset 7295 Op.getOperand(5), // cachepolicy, swizzled buffer 7296 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7297 }; 7298 7299 auto *M = cast<MemSDNode>(Op); 7300 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]); 7301 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 7302 } 7303 case Intrinsic::amdgcn_struct_buffer_load: 7304 case Intrinsic::amdgcn_struct_buffer_load_format: { 7305 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 7306 7307 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7308 SDValue Ops[] = { 7309 Op.getOperand(0), // Chain 7310 Op.getOperand(2), // rsrc 7311 Op.getOperand(3), // vindex 7312 Offsets.first, // voffset 7313 Op.getOperand(5), // soffset 7314 Offsets.second, // offset 7315 Op.getOperand(6), // cachepolicy, swizzled buffer 7316 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7317 }; 7318 7319 auto *M = cast<MemSDNode>(Op); 7320 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7321 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 7322 } 7323 case Intrinsic::amdgcn_tbuffer_load: { 7324 MemSDNode *M = cast<MemSDNode>(Op); 7325 EVT LoadVT = Op.getValueType(); 7326 7327 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7328 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7329 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7330 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7331 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7332 SDValue Ops[] = { 7333 Op.getOperand(0), // Chain 7334 Op.getOperand(2), // rsrc 7335 Op.getOperand(3), // vindex 7336 Op.getOperand(4), // voffset 7337 Op.getOperand(5), // soffset 7338 Op.getOperand(6), // offset 7339 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7340 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7341 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 7342 }; 7343 7344 if (LoadVT.getScalarType() == MVT::f16) 7345 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7346 M, DAG, Ops); 7347 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7348 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7349 DAG); 7350 } 7351 case Intrinsic::amdgcn_raw_tbuffer_load: { 7352 MemSDNode *M = cast<MemSDNode>(Op); 7353 EVT LoadVT = Op.getValueType(); 7354 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7355 7356 SDValue Ops[] = { 7357 Op.getOperand(0), // Chain 7358 Op.getOperand(2), // rsrc 7359 DAG.getConstant(0, DL, MVT::i32), // vindex 7360 Offsets.first, // voffset 7361 Op.getOperand(4), // soffset 7362 Offsets.second, // offset 7363 Op.getOperand(5), // format 7364 Op.getOperand(6), // cachepolicy, swizzled buffer 7365 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7366 }; 7367 7368 if (LoadVT.getScalarType() == MVT::f16) 7369 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7370 M, DAG, Ops); 7371 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7372 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7373 DAG); 7374 } 7375 case Intrinsic::amdgcn_struct_tbuffer_load: { 7376 MemSDNode *M = cast<MemSDNode>(Op); 7377 EVT LoadVT = Op.getValueType(); 7378 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7379 7380 SDValue Ops[] = { 7381 Op.getOperand(0), // Chain 7382 Op.getOperand(2), // rsrc 7383 Op.getOperand(3), // vindex 7384 Offsets.first, // voffset 7385 Op.getOperand(5), // soffset 7386 Offsets.second, // offset 7387 Op.getOperand(6), // format 7388 Op.getOperand(7), // cachepolicy, swizzled buffer 7389 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7390 }; 7391 7392 if (LoadVT.getScalarType() == MVT::f16) 7393 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7394 M, DAG, Ops); 7395 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7396 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7397 DAG); 7398 } 7399 case Intrinsic::amdgcn_buffer_atomic_swap: 7400 case Intrinsic::amdgcn_buffer_atomic_add: 7401 case Intrinsic::amdgcn_buffer_atomic_sub: 7402 case Intrinsic::amdgcn_buffer_atomic_csub: 7403 case Intrinsic::amdgcn_buffer_atomic_smin: 7404 case Intrinsic::amdgcn_buffer_atomic_umin: 7405 case Intrinsic::amdgcn_buffer_atomic_smax: 7406 case Intrinsic::amdgcn_buffer_atomic_umax: 7407 case Intrinsic::amdgcn_buffer_atomic_and: 7408 case Intrinsic::amdgcn_buffer_atomic_or: 7409 case Intrinsic::amdgcn_buffer_atomic_xor: 7410 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7411 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7412 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7413 SDValue Ops[] = { 7414 Op.getOperand(0), // Chain 7415 Op.getOperand(2), // vdata 7416 Op.getOperand(3), // rsrc 7417 Op.getOperand(4), // vindex 7418 SDValue(), // voffset -- will be set by setBufferOffsets 7419 SDValue(), // soffset -- will be set by setBufferOffsets 7420 SDValue(), // offset -- will be set by setBufferOffsets 7421 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7422 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7423 }; 7424 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7425 7426 EVT VT = Op.getValueType(); 7427 7428 auto *M = cast<MemSDNode>(Op); 7429 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7430 unsigned Opcode = 0; 7431 7432 switch (IntrID) { 7433 case Intrinsic::amdgcn_buffer_atomic_swap: 7434 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7435 break; 7436 case Intrinsic::amdgcn_buffer_atomic_add: 7437 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7438 break; 7439 case Intrinsic::amdgcn_buffer_atomic_sub: 7440 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7441 break; 7442 case Intrinsic::amdgcn_buffer_atomic_csub: 7443 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7444 break; 7445 case Intrinsic::amdgcn_buffer_atomic_smin: 7446 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7447 break; 7448 case Intrinsic::amdgcn_buffer_atomic_umin: 7449 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7450 break; 7451 case Intrinsic::amdgcn_buffer_atomic_smax: 7452 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7453 break; 7454 case Intrinsic::amdgcn_buffer_atomic_umax: 7455 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7456 break; 7457 case Intrinsic::amdgcn_buffer_atomic_and: 7458 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7459 break; 7460 case Intrinsic::amdgcn_buffer_atomic_or: 7461 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7462 break; 7463 case Intrinsic::amdgcn_buffer_atomic_xor: 7464 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7465 break; 7466 case Intrinsic::amdgcn_buffer_atomic_fadd: 7467 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7468 DiagnosticInfoUnsupported 7469 NoFpRet(DAG.getMachineFunction().getFunction(), 7470 "return versions of fp atomics not supported", 7471 DL.getDebugLoc(), DS_Error); 7472 DAG.getContext()->diagnose(NoFpRet); 7473 return SDValue(); 7474 } 7475 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7476 break; 7477 default: 7478 llvm_unreachable("unhandled atomic opcode"); 7479 } 7480 7481 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7482 M->getMemOperand()); 7483 } 7484 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7485 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7486 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7487 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7488 case Intrinsic::amdgcn_raw_buffer_atomic_fmin: 7489 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7490 case Intrinsic::amdgcn_struct_buffer_atomic_fmin: 7491 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7492 case Intrinsic::amdgcn_raw_buffer_atomic_fmax: 7493 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7494 case Intrinsic::amdgcn_struct_buffer_atomic_fmax: 7495 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7496 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7497 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7498 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7499 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7500 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7501 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7502 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7503 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7504 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7505 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7506 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7507 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7508 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7509 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7510 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7511 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7512 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7513 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7514 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7515 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7516 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7517 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7518 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7519 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7520 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7521 return lowerStructBufferAtomicIntrin(Op, DAG, 7522 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7523 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7524 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7525 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7526 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7527 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7528 return lowerStructBufferAtomicIntrin(Op, DAG, 7529 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7530 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7531 return lowerStructBufferAtomicIntrin(Op, DAG, 7532 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7533 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7534 return lowerStructBufferAtomicIntrin(Op, DAG, 7535 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7536 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7537 return lowerStructBufferAtomicIntrin(Op, DAG, 7538 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7539 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7540 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7541 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7542 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7543 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7544 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7545 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7546 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7547 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7548 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7549 7550 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7551 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7552 unsigned IdxEn = getIdxEn(Op.getOperand(5)); 7553 SDValue Ops[] = { 7554 Op.getOperand(0), // Chain 7555 Op.getOperand(2), // src 7556 Op.getOperand(3), // cmp 7557 Op.getOperand(4), // rsrc 7558 Op.getOperand(5), // vindex 7559 SDValue(), // voffset -- will be set by setBufferOffsets 7560 SDValue(), // soffset -- will be set by setBufferOffsets 7561 SDValue(), // offset -- will be set by setBufferOffsets 7562 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7563 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7564 }; 7565 setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7566 7567 EVT VT = Op.getValueType(); 7568 auto *M = cast<MemSDNode>(Op); 7569 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7570 7571 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7572 Op->getVTList(), Ops, VT, M->getMemOperand()); 7573 } 7574 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7575 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7576 SDValue Ops[] = { 7577 Op.getOperand(0), // Chain 7578 Op.getOperand(2), // src 7579 Op.getOperand(3), // cmp 7580 Op.getOperand(4), // rsrc 7581 DAG.getConstant(0, DL, MVT::i32), // vindex 7582 Offsets.first, // voffset 7583 Op.getOperand(6), // soffset 7584 Offsets.second, // offset 7585 Op.getOperand(7), // cachepolicy 7586 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7587 }; 7588 EVT VT = Op.getValueType(); 7589 auto *M = cast<MemSDNode>(Op); 7590 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]); 7591 7592 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7593 Op->getVTList(), Ops, VT, M->getMemOperand()); 7594 } 7595 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7596 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7597 SDValue Ops[] = { 7598 Op.getOperand(0), // Chain 7599 Op.getOperand(2), // src 7600 Op.getOperand(3), // cmp 7601 Op.getOperand(4), // rsrc 7602 Op.getOperand(5), // vindex 7603 Offsets.first, // voffset 7604 Op.getOperand(7), // soffset 7605 Offsets.second, // offset 7606 Op.getOperand(8), // cachepolicy 7607 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7608 }; 7609 EVT VT = Op.getValueType(); 7610 auto *M = cast<MemSDNode>(Op); 7611 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7612 7613 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7614 Op->getVTList(), Ops, VT, M->getMemOperand()); 7615 } 7616 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 7617 MemSDNode *M = cast<MemSDNode>(Op); 7618 SDValue NodePtr = M->getOperand(2); 7619 SDValue RayExtent = M->getOperand(3); 7620 SDValue RayOrigin = M->getOperand(4); 7621 SDValue RayDir = M->getOperand(5); 7622 SDValue RayInvDir = M->getOperand(6); 7623 SDValue TDescr = M->getOperand(7); 7624 7625 assert(NodePtr.getValueType() == MVT::i32 || 7626 NodePtr.getValueType() == MVT::i64); 7627 assert(RayDir.getValueType() == MVT::v3f16 || 7628 RayDir.getValueType() == MVT::v3f32); 7629 7630 if (!Subtarget->hasGFX10_AEncoding()) { 7631 emitRemovedIntrinsicError(DAG, DL, Op.getValueType()); 7632 return SDValue(); 7633 } 7634 7635 const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16; 7636 const bool Is64 = NodePtr.getValueType() == MVT::i64; 7637 const unsigned NumVDataDwords = 4; 7638 const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11); 7639 const bool UseNSA = Subtarget->hasNSAEncoding() && 7640 NumVAddrDwords <= Subtarget->getNSAMaxSize(); 7641 const unsigned BaseOpcodes[2][2] = { 7642 {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16}, 7643 {AMDGPU::IMAGE_BVH64_INTERSECT_RAY, 7644 AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}}; 7645 int Opcode; 7646 if (UseNSA) { 7647 Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16], 7648 AMDGPU::MIMGEncGfx10NSA, NumVDataDwords, 7649 NumVAddrDwords); 7650 } else { 7651 Opcode = AMDGPU::getMIMGOpcode( 7652 BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords, 7653 PowerOf2Ceil(NumVAddrDwords)); 7654 } 7655 assert(Opcode != -1); 7656 7657 SmallVector<SDValue, 16> Ops; 7658 7659 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) { 7660 SmallVector<SDValue, 3> Lanes; 7661 DAG.ExtractVectorElements(Op, Lanes, 0, 3); 7662 if (Lanes[0].getValueSizeInBits() == 32) { 7663 for (unsigned I = 0; I < 3; ++I) 7664 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I])); 7665 } else { 7666 if (IsAligned) { 7667 Ops.push_back( 7668 DAG.getBitcast(MVT::i32, 7669 DAG.getBuildVector(MVT::v2f16, DL, 7670 { Lanes[0], Lanes[1] }))); 7671 Ops.push_back(Lanes[2]); 7672 } else { 7673 SDValue Elt0 = Ops.pop_back_val(); 7674 Ops.push_back( 7675 DAG.getBitcast(MVT::i32, 7676 DAG.getBuildVector(MVT::v2f16, DL, 7677 { Elt0, Lanes[0] }))); 7678 Ops.push_back( 7679 DAG.getBitcast(MVT::i32, 7680 DAG.getBuildVector(MVT::v2f16, DL, 7681 { Lanes[1], Lanes[2] }))); 7682 } 7683 } 7684 }; 7685 7686 if (Is64) 7687 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2); 7688 else 7689 Ops.push_back(NodePtr); 7690 7691 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7692 packLanes(RayOrigin, true); 7693 packLanes(RayDir, true); 7694 packLanes(RayInvDir, false); 7695 7696 if (!UseNSA) { 7697 // Build a single vector containing all the operands so far prepared. 7698 if (NumVAddrDwords > 8) { 7699 SDValue Undef = DAG.getUNDEF(MVT::i32); 7700 Ops.append(16 - Ops.size(), Undef); 7701 } 7702 assert(Ops.size() == 8 || Ops.size() == 16); 7703 SDValue MergedOps = DAG.getBuildVector( 7704 Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops); 7705 Ops.clear(); 7706 Ops.push_back(MergedOps); 7707 } 7708 7709 Ops.push_back(TDescr); 7710 if (IsA16) 7711 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1)); 7712 Ops.push_back(M->getChain()); 7713 7714 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops); 7715 MachineMemOperand *MemRef = M->getMemOperand(); 7716 DAG.setNodeMemRefs(NewNode, {MemRef}); 7717 return SDValue(NewNode, 0); 7718 } 7719 case Intrinsic::amdgcn_global_atomic_fadd: 7720 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7721 DiagnosticInfoUnsupported 7722 NoFpRet(DAG.getMachineFunction().getFunction(), 7723 "return versions of fp atomics not supported", 7724 DL.getDebugLoc(), DS_Error); 7725 DAG.getContext()->diagnose(NoFpRet); 7726 return SDValue(); 7727 } 7728 LLVM_FALLTHROUGH; 7729 case Intrinsic::amdgcn_global_atomic_fmin: 7730 case Intrinsic::amdgcn_global_atomic_fmax: 7731 case Intrinsic::amdgcn_flat_atomic_fadd: 7732 case Intrinsic::amdgcn_flat_atomic_fmin: 7733 case Intrinsic::amdgcn_flat_atomic_fmax: { 7734 MemSDNode *M = cast<MemSDNode>(Op); 7735 SDValue Ops[] = { 7736 M->getOperand(0), // Chain 7737 M->getOperand(2), // Ptr 7738 M->getOperand(3) // Value 7739 }; 7740 unsigned Opcode = 0; 7741 switch (IntrID) { 7742 case Intrinsic::amdgcn_global_atomic_fadd: 7743 case Intrinsic::amdgcn_flat_atomic_fadd: { 7744 EVT VT = Op.getOperand(3).getValueType(); 7745 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7746 DAG.getVTList(VT, MVT::Other), Ops, 7747 M->getMemOperand()); 7748 } 7749 case Intrinsic::amdgcn_global_atomic_fmin: 7750 case Intrinsic::amdgcn_flat_atomic_fmin: { 7751 Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN; 7752 break; 7753 } 7754 case Intrinsic::amdgcn_global_atomic_fmax: 7755 case Intrinsic::amdgcn_flat_atomic_fmax: { 7756 Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX; 7757 break; 7758 } 7759 default: 7760 llvm_unreachable("unhandled atomic opcode"); 7761 } 7762 return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op), 7763 M->getVTList(), Ops, M->getMemoryVT(), 7764 M->getMemOperand()); 7765 } 7766 default: 7767 7768 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7769 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7770 return lowerImage(Op, ImageDimIntr, DAG, true); 7771 7772 return SDValue(); 7773 } 7774 } 7775 7776 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7777 // dwordx4 if on SI. 7778 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7779 SDVTList VTList, 7780 ArrayRef<SDValue> Ops, EVT MemVT, 7781 MachineMemOperand *MMO, 7782 SelectionDAG &DAG) const { 7783 EVT VT = VTList.VTs[0]; 7784 EVT WidenedVT = VT; 7785 EVT WidenedMemVT = MemVT; 7786 if (!Subtarget->hasDwordx3LoadStores() && 7787 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7788 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7789 WidenedVT.getVectorElementType(), 4); 7790 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7791 WidenedMemVT.getVectorElementType(), 4); 7792 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7793 } 7794 7795 assert(VTList.NumVTs == 2); 7796 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7797 7798 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7799 WidenedMemVT, MMO); 7800 if (WidenedVT != VT) { 7801 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7802 DAG.getVectorIdxConstant(0, DL)); 7803 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7804 } 7805 return NewOp; 7806 } 7807 7808 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG, 7809 bool ImageStore) const { 7810 EVT StoreVT = VData.getValueType(); 7811 7812 // No change for f16 and legal vector D16 types. 7813 if (!StoreVT.isVector()) 7814 return VData; 7815 7816 SDLoc DL(VData); 7817 unsigned NumElements = StoreVT.getVectorNumElements(); 7818 7819 if (Subtarget->hasUnpackedD16VMem()) { 7820 // We need to unpack the packed data to store. 7821 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7822 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7823 7824 EVT EquivStoreVT = 7825 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements); 7826 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7827 return DAG.UnrollVectorOp(ZExt.getNode()); 7828 } 7829 7830 // The sq block of gfx8.1 does not estimate register use correctly for d16 7831 // image store instructions. The data operand is computed as if it were not a 7832 // d16 image instruction. 7833 if (ImageStore && Subtarget->hasImageStoreD16Bug()) { 7834 // Bitcast to i16 7835 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7836 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7837 7838 // Decompose into scalars 7839 SmallVector<SDValue, 4> Elts; 7840 DAG.ExtractVectorElements(IntVData, Elts); 7841 7842 // Group pairs of i16 into v2i16 and bitcast to i32 7843 SmallVector<SDValue, 4> PackedElts; 7844 for (unsigned I = 0; I < Elts.size() / 2; I += 1) { 7845 SDValue Pair = 7846 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]}); 7847 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7848 PackedElts.push_back(IntPair); 7849 } 7850 if ((NumElements % 2) == 1) { 7851 // Handle v3i16 7852 unsigned I = Elts.size() / 2; 7853 SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL, 7854 {Elts[I * 2], DAG.getUNDEF(MVT::i16)}); 7855 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7856 PackedElts.push_back(IntPair); 7857 } 7858 7859 // Pad using UNDEF 7860 PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32)); 7861 7862 // Build final vector 7863 EVT VecVT = 7864 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size()); 7865 return DAG.getBuildVector(VecVT, DL, PackedElts); 7866 } 7867 7868 if (NumElements == 3) { 7869 EVT IntStoreVT = 7870 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits()); 7871 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7872 7873 EVT WidenedStoreVT = EVT::getVectorVT( 7874 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1); 7875 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(), 7876 WidenedStoreVT.getStoreSizeInBits()); 7877 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData); 7878 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt); 7879 } 7880 7881 assert(isTypeLegal(StoreVT)); 7882 return VData; 7883 } 7884 7885 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7886 SelectionDAG &DAG) const { 7887 SDLoc DL(Op); 7888 SDValue Chain = Op.getOperand(0); 7889 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7890 MachineFunction &MF = DAG.getMachineFunction(); 7891 7892 switch (IntrinsicID) { 7893 case Intrinsic::amdgcn_exp_compr: { 7894 SDValue Src0 = Op.getOperand(4); 7895 SDValue Src1 = Op.getOperand(5); 7896 // Hack around illegal type on SI by directly selecting it. 7897 if (isTypeLegal(Src0.getValueType())) 7898 return SDValue(); 7899 7900 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7901 SDValue Undef = DAG.getUNDEF(MVT::f32); 7902 const SDValue Ops[] = { 7903 Op.getOperand(2), // tgt 7904 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7905 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7906 Undef, // src2 7907 Undef, // src3 7908 Op.getOperand(7), // vm 7909 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7910 Op.getOperand(3), // en 7911 Op.getOperand(0) // Chain 7912 }; 7913 7914 unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7915 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7916 } 7917 case Intrinsic::amdgcn_s_barrier: { 7918 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7919 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7920 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7921 if (WGSize <= ST.getWavefrontSize()) 7922 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7923 Op.getOperand(0)), 0); 7924 } 7925 return SDValue(); 7926 }; 7927 case Intrinsic::amdgcn_tbuffer_store: { 7928 SDValue VData = Op.getOperand(2); 7929 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7930 if (IsD16) 7931 VData = handleD16VData(VData, DAG); 7932 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7933 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7934 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7935 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7936 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7937 SDValue Ops[] = { 7938 Chain, 7939 VData, // vdata 7940 Op.getOperand(3), // rsrc 7941 Op.getOperand(4), // vindex 7942 Op.getOperand(5), // voffset 7943 Op.getOperand(6), // soffset 7944 Op.getOperand(7), // offset 7945 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7946 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7947 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7948 }; 7949 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7950 AMDGPUISD::TBUFFER_STORE_FORMAT; 7951 MemSDNode *M = cast<MemSDNode>(Op); 7952 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7953 M->getMemoryVT(), M->getMemOperand()); 7954 } 7955 7956 case Intrinsic::amdgcn_struct_tbuffer_store: { 7957 SDValue VData = Op.getOperand(2); 7958 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7959 if (IsD16) 7960 VData = handleD16VData(VData, DAG); 7961 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7962 SDValue Ops[] = { 7963 Chain, 7964 VData, // vdata 7965 Op.getOperand(3), // rsrc 7966 Op.getOperand(4), // vindex 7967 Offsets.first, // voffset 7968 Op.getOperand(6), // soffset 7969 Offsets.second, // offset 7970 Op.getOperand(7), // format 7971 Op.getOperand(8), // cachepolicy, swizzled buffer 7972 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7973 }; 7974 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7975 AMDGPUISD::TBUFFER_STORE_FORMAT; 7976 MemSDNode *M = cast<MemSDNode>(Op); 7977 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7978 M->getMemoryVT(), M->getMemOperand()); 7979 } 7980 7981 case Intrinsic::amdgcn_raw_tbuffer_store: { 7982 SDValue VData = Op.getOperand(2); 7983 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7984 if (IsD16) 7985 VData = handleD16VData(VData, DAG); 7986 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7987 SDValue Ops[] = { 7988 Chain, 7989 VData, // vdata 7990 Op.getOperand(3), // rsrc 7991 DAG.getConstant(0, DL, MVT::i32), // vindex 7992 Offsets.first, // voffset 7993 Op.getOperand(5), // soffset 7994 Offsets.second, // offset 7995 Op.getOperand(6), // format 7996 Op.getOperand(7), // cachepolicy, swizzled buffer 7997 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7998 }; 7999 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 8000 AMDGPUISD::TBUFFER_STORE_FORMAT; 8001 MemSDNode *M = cast<MemSDNode>(Op); 8002 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8003 M->getMemoryVT(), M->getMemOperand()); 8004 } 8005 8006 case Intrinsic::amdgcn_buffer_store: 8007 case Intrinsic::amdgcn_buffer_store_format: { 8008 SDValue VData = Op.getOperand(2); 8009 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 8010 if (IsD16) 8011 VData = handleD16VData(VData, DAG); 8012 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 8013 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 8014 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 8015 SDValue Ops[] = { 8016 Chain, 8017 VData, 8018 Op.getOperand(3), // rsrc 8019 Op.getOperand(4), // vindex 8020 SDValue(), // voffset -- will be set by setBufferOffsets 8021 SDValue(), // soffset -- will be set by setBufferOffsets 8022 SDValue(), // offset -- will be set by setBufferOffsets 8023 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 8024 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 8025 }; 8026 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 8027 8028 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 8029 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 8030 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 8031 MemSDNode *M = cast<MemSDNode>(Op); 8032 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 8033 8034 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 8035 EVT VDataType = VData.getValueType().getScalarType(); 8036 if (VDataType == MVT::i8 || VDataType == MVT::i16) 8037 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 8038 8039 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8040 M->getMemoryVT(), M->getMemOperand()); 8041 } 8042 8043 case Intrinsic::amdgcn_raw_buffer_store: 8044 case Intrinsic::amdgcn_raw_buffer_store_format: { 8045 const bool IsFormat = 8046 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 8047 8048 SDValue VData = Op.getOperand(2); 8049 EVT VDataVT = VData.getValueType(); 8050 EVT EltType = VDataVT.getScalarType(); 8051 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 8052 if (IsD16) { 8053 VData = handleD16VData(VData, DAG); 8054 VDataVT = VData.getValueType(); 8055 } 8056 8057 if (!isTypeLegal(VDataVT)) { 8058 VData = 8059 DAG.getNode(ISD::BITCAST, DL, 8060 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 8061 } 8062 8063 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 8064 SDValue Ops[] = { 8065 Chain, 8066 VData, 8067 Op.getOperand(3), // rsrc 8068 DAG.getConstant(0, DL, MVT::i32), // vindex 8069 Offsets.first, // voffset 8070 Op.getOperand(5), // soffset 8071 Offsets.second, // offset 8072 Op.getOperand(6), // cachepolicy, swizzled buffer 8073 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 8074 }; 8075 unsigned Opc = 8076 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 8077 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 8078 MemSDNode *M = cast<MemSDNode>(Op); 8079 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 8080 8081 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 8082 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 8083 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 8084 8085 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8086 M->getMemoryVT(), M->getMemOperand()); 8087 } 8088 8089 case Intrinsic::amdgcn_struct_buffer_store: 8090 case Intrinsic::amdgcn_struct_buffer_store_format: { 8091 const bool IsFormat = 8092 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 8093 8094 SDValue VData = Op.getOperand(2); 8095 EVT VDataVT = VData.getValueType(); 8096 EVT EltType = VDataVT.getScalarType(); 8097 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 8098 8099 if (IsD16) { 8100 VData = handleD16VData(VData, DAG); 8101 VDataVT = VData.getValueType(); 8102 } 8103 8104 if (!isTypeLegal(VDataVT)) { 8105 VData = 8106 DAG.getNode(ISD::BITCAST, DL, 8107 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 8108 } 8109 8110 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 8111 SDValue Ops[] = { 8112 Chain, 8113 VData, 8114 Op.getOperand(3), // rsrc 8115 Op.getOperand(4), // vindex 8116 Offsets.first, // voffset 8117 Op.getOperand(6), // soffset 8118 Offsets.second, // offset 8119 Op.getOperand(7), // cachepolicy, swizzled buffer 8120 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 8121 }; 8122 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 8123 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 8124 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 8125 MemSDNode *M = cast<MemSDNode>(Op); 8126 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 8127 8128 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 8129 EVT VDataType = VData.getValueType().getScalarType(); 8130 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 8131 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 8132 8133 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8134 M->getMemoryVT(), M->getMemOperand()); 8135 } 8136 case Intrinsic::amdgcn_end_cf: 8137 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 8138 Op->getOperand(2), Chain), 0); 8139 8140 default: { 8141 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 8142 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 8143 return lowerImage(Op, ImageDimIntr, DAG, true); 8144 8145 return Op; 8146 } 8147 } 8148 } 8149 8150 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 8151 // offset (the offset that is included in bounds checking and swizzling, to be 8152 // split between the instruction's voffset and immoffset fields) and soffset 8153 // (the offset that is excluded from bounds checking and swizzling, to go in 8154 // the instruction's soffset field). This function takes the first kind of 8155 // offset and figures out how to split it between voffset and immoffset. 8156 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 8157 SDValue Offset, SelectionDAG &DAG) const { 8158 SDLoc DL(Offset); 8159 const unsigned MaxImm = 4095; 8160 SDValue N0 = Offset; 8161 ConstantSDNode *C1 = nullptr; 8162 8163 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 8164 N0 = SDValue(); 8165 else if (DAG.isBaseWithConstantOffset(N0)) { 8166 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 8167 N0 = N0.getOperand(0); 8168 } 8169 8170 if (C1) { 8171 unsigned ImmOffset = C1->getZExtValue(); 8172 // If the immediate value is too big for the immoffset field, put the value 8173 // and -4096 into the immoffset field so that the value that is copied/added 8174 // for the voffset field is a multiple of 4096, and it stands more chance 8175 // of being CSEd with the copy/add for another similar load/store. 8176 // However, do not do that rounding down to a multiple of 4096 if that is a 8177 // negative number, as it appears to be illegal to have a negative offset 8178 // in the vgpr, even if adding the immediate offset makes it positive. 8179 unsigned Overflow = ImmOffset & ~MaxImm; 8180 ImmOffset -= Overflow; 8181 if ((int32_t)Overflow < 0) { 8182 Overflow += ImmOffset; 8183 ImmOffset = 0; 8184 } 8185 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 8186 if (Overflow) { 8187 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 8188 if (!N0) 8189 N0 = OverflowVal; 8190 else { 8191 SDValue Ops[] = { N0, OverflowVal }; 8192 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 8193 } 8194 } 8195 } 8196 if (!N0) 8197 N0 = DAG.getConstant(0, DL, MVT::i32); 8198 if (!C1) 8199 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 8200 return {N0, SDValue(C1, 0)}; 8201 } 8202 8203 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 8204 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 8205 // pointed to by Offsets. 8206 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 8207 SelectionDAG &DAG, SDValue *Offsets, 8208 Align Alignment) const { 8209 SDLoc DL(CombinedOffset); 8210 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 8211 uint32_t Imm = C->getZExtValue(); 8212 uint32_t SOffset, ImmOffset; 8213 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 8214 Alignment)) { 8215 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 8216 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 8217 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 8218 return; 8219 } 8220 } 8221 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 8222 SDValue N0 = CombinedOffset.getOperand(0); 8223 SDValue N1 = CombinedOffset.getOperand(1); 8224 uint32_t SOffset, ImmOffset; 8225 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 8226 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 8227 Subtarget, Alignment)) { 8228 Offsets[0] = N0; 8229 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 8230 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 8231 return; 8232 } 8233 } 8234 Offsets[0] = CombinedOffset; 8235 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 8236 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 8237 } 8238 8239 // Handle 8 bit and 16 bit buffer loads 8240 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 8241 EVT LoadVT, SDLoc DL, 8242 ArrayRef<SDValue> Ops, 8243 MemSDNode *M) const { 8244 EVT IntVT = LoadVT.changeTypeToInteger(); 8245 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 8246 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 8247 8248 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 8249 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 8250 Ops, IntVT, 8251 M->getMemOperand()); 8252 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 8253 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 8254 8255 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 8256 } 8257 8258 // Handle 8 bit and 16 bit buffer stores 8259 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 8260 EVT VDataType, SDLoc DL, 8261 SDValue Ops[], 8262 MemSDNode *M) const { 8263 if (VDataType == MVT::f16) 8264 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 8265 8266 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 8267 Ops[1] = BufferStoreExt; 8268 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 8269 AMDGPUISD::BUFFER_STORE_SHORT; 8270 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 8271 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 8272 M->getMemOperand()); 8273 } 8274 8275 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 8276 ISD::LoadExtType ExtType, SDValue Op, 8277 const SDLoc &SL, EVT VT) { 8278 if (VT.bitsLT(Op.getValueType())) 8279 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 8280 8281 switch (ExtType) { 8282 case ISD::SEXTLOAD: 8283 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 8284 case ISD::ZEXTLOAD: 8285 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 8286 case ISD::EXTLOAD: 8287 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 8288 case ISD::NON_EXTLOAD: 8289 return Op; 8290 } 8291 8292 llvm_unreachable("invalid ext type"); 8293 } 8294 8295 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 8296 SelectionDAG &DAG = DCI.DAG; 8297 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 8298 return SDValue(); 8299 8300 // FIXME: Constant loads should all be marked invariant. 8301 unsigned AS = Ld->getAddressSpace(); 8302 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 8303 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 8304 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 8305 return SDValue(); 8306 8307 // Don't do this early, since it may interfere with adjacent load merging for 8308 // illegal types. We can avoid losing alignment information for exotic types 8309 // pre-legalize. 8310 EVT MemVT = Ld->getMemoryVT(); 8311 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 8312 MemVT.getSizeInBits() >= 32) 8313 return SDValue(); 8314 8315 SDLoc SL(Ld); 8316 8317 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 8318 "unexpected vector extload"); 8319 8320 // TODO: Drop only high part of range. 8321 SDValue Ptr = Ld->getBasePtr(); 8322 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 8323 MVT::i32, SL, Ld->getChain(), Ptr, 8324 Ld->getOffset(), 8325 Ld->getPointerInfo(), MVT::i32, 8326 Ld->getAlignment(), 8327 Ld->getMemOperand()->getFlags(), 8328 Ld->getAAInfo(), 8329 nullptr); // Drop ranges 8330 8331 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 8332 if (MemVT.isFloatingPoint()) { 8333 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 8334 "unexpected fp extload"); 8335 TruncVT = MemVT.changeTypeToInteger(); 8336 } 8337 8338 SDValue Cvt = NewLoad; 8339 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 8340 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 8341 DAG.getValueType(TruncVT)); 8342 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 8343 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 8344 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 8345 } else { 8346 assert(Ld->getExtensionType() == ISD::EXTLOAD); 8347 } 8348 8349 EVT VT = Ld->getValueType(0); 8350 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 8351 8352 DCI.AddToWorklist(Cvt.getNode()); 8353 8354 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 8355 // the appropriate extension from the 32-bit load. 8356 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 8357 DCI.AddToWorklist(Cvt.getNode()); 8358 8359 // Handle conversion back to floating point if necessary. 8360 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 8361 8362 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 8363 } 8364 8365 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 8366 SDLoc DL(Op); 8367 LoadSDNode *Load = cast<LoadSDNode>(Op); 8368 ISD::LoadExtType ExtType = Load->getExtensionType(); 8369 EVT MemVT = Load->getMemoryVT(); 8370 8371 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 8372 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 8373 return SDValue(); 8374 8375 // FIXME: Copied from PPC 8376 // First, load into 32 bits, then truncate to 1 bit. 8377 8378 SDValue Chain = Load->getChain(); 8379 SDValue BasePtr = Load->getBasePtr(); 8380 MachineMemOperand *MMO = Load->getMemOperand(); 8381 8382 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 8383 8384 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 8385 BasePtr, RealMemVT, MMO); 8386 8387 if (!MemVT.isVector()) { 8388 SDValue Ops[] = { 8389 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 8390 NewLD.getValue(1) 8391 }; 8392 8393 return DAG.getMergeValues(Ops, DL); 8394 } 8395 8396 SmallVector<SDValue, 3> Elts; 8397 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 8398 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 8399 DAG.getConstant(I, DL, MVT::i32)); 8400 8401 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 8402 } 8403 8404 SDValue Ops[] = { 8405 DAG.getBuildVector(MemVT, DL, Elts), 8406 NewLD.getValue(1) 8407 }; 8408 8409 return DAG.getMergeValues(Ops, DL); 8410 } 8411 8412 if (!MemVT.isVector()) 8413 return SDValue(); 8414 8415 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 8416 "Custom lowering for non-i32 vectors hasn't been implemented."); 8417 8418 unsigned Alignment = Load->getAlignment(); 8419 unsigned AS = Load->getAddressSpace(); 8420 if (Subtarget->hasLDSMisalignedBug() && 8421 AS == AMDGPUAS::FLAT_ADDRESS && 8422 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 8423 return SplitVectorLoad(Op, DAG); 8424 } 8425 8426 MachineFunction &MF = DAG.getMachineFunction(); 8427 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8428 // If there is a possibilty that flat instruction access scratch memory 8429 // then we need to use the same legalization rules we use for private. 8430 if (AS == AMDGPUAS::FLAT_ADDRESS && 8431 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8432 AS = MFI->hasFlatScratchInit() ? 8433 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8434 8435 unsigned NumElements = MemVT.getVectorNumElements(); 8436 8437 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8438 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 8439 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 8440 if (MemVT.isPow2VectorType()) 8441 return SDValue(); 8442 return WidenOrSplitVectorLoad(Op, DAG); 8443 } 8444 // Non-uniform loads will be selected to MUBUF instructions, so they 8445 // have the same legalization requirements as global and private 8446 // loads. 8447 // 8448 } 8449 8450 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8451 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8452 AS == AMDGPUAS::GLOBAL_ADDRESS) { 8453 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 8454 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 8455 Alignment >= 4 && NumElements < 32) { 8456 if (MemVT.isPow2VectorType()) 8457 return SDValue(); 8458 return WidenOrSplitVectorLoad(Op, DAG); 8459 } 8460 // Non-uniform loads will be selected to MUBUF instructions, so they 8461 // have the same legalization requirements as global and private 8462 // loads. 8463 // 8464 } 8465 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8466 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8467 AS == AMDGPUAS::GLOBAL_ADDRESS || 8468 AS == AMDGPUAS::FLAT_ADDRESS) { 8469 if (NumElements > 4) 8470 return SplitVectorLoad(Op, DAG); 8471 // v3 loads not supported on SI. 8472 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8473 return WidenOrSplitVectorLoad(Op, DAG); 8474 8475 // v3 and v4 loads are supported for private and global memory. 8476 return SDValue(); 8477 } 8478 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8479 // Depending on the setting of the private_element_size field in the 8480 // resource descriptor, we can only make private accesses up to a certain 8481 // size. 8482 switch (Subtarget->getMaxPrivateElementSize()) { 8483 case 4: { 8484 SDValue Ops[2]; 8485 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 8486 return DAG.getMergeValues(Ops, DL); 8487 } 8488 case 8: 8489 if (NumElements > 2) 8490 return SplitVectorLoad(Op, DAG); 8491 return SDValue(); 8492 case 16: 8493 // Same as global/flat 8494 if (NumElements > 4) 8495 return SplitVectorLoad(Op, DAG); 8496 // v3 loads not supported on SI. 8497 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8498 return WidenOrSplitVectorLoad(Op, DAG); 8499 8500 return SDValue(); 8501 default: 8502 llvm_unreachable("unsupported private_element_size"); 8503 } 8504 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8505 // Use ds_read_b128 or ds_read_b96 when possible. 8506 if (Subtarget->hasDS96AndDS128() && 8507 ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) || 8508 MemVT.getStoreSize() == 12) && 8509 allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 8510 Load->getAlign())) 8511 return SDValue(); 8512 8513 if (NumElements > 2) 8514 return SplitVectorLoad(Op, DAG); 8515 8516 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8517 // address is negative, then the instruction is incorrectly treated as 8518 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8519 // loads here to avoid emitting ds_read2_b32. We may re-combine the 8520 // load later in the SILoadStoreOptimizer. 8521 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 8522 NumElements == 2 && MemVT.getStoreSize() == 8 && 8523 Load->getAlignment() < 8) { 8524 return SplitVectorLoad(Op, DAG); 8525 } 8526 } 8527 8528 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8529 MemVT, *Load->getMemOperand())) { 8530 SDValue Ops[2]; 8531 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 8532 return DAG.getMergeValues(Ops, DL); 8533 } 8534 8535 return SDValue(); 8536 } 8537 8538 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8539 EVT VT = Op.getValueType(); 8540 if (VT.getSizeInBits() == 128) 8541 return splitTernaryVectorOp(Op, DAG); 8542 8543 assert(VT.getSizeInBits() == 64); 8544 8545 SDLoc DL(Op); 8546 SDValue Cond = Op.getOperand(0); 8547 8548 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8549 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8550 8551 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8552 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8553 8554 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8555 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8556 8557 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8558 8559 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8560 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8561 8562 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8563 8564 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8565 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8566 } 8567 8568 // Catch division cases where we can use shortcuts with rcp and rsq 8569 // instructions. 8570 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8571 SelectionDAG &DAG) const { 8572 SDLoc SL(Op); 8573 SDValue LHS = Op.getOperand(0); 8574 SDValue RHS = Op.getOperand(1); 8575 EVT VT = Op.getValueType(); 8576 const SDNodeFlags Flags = Op->getFlags(); 8577 8578 bool AllowInaccurateRcp = Flags.hasApproximateFuncs(); 8579 8580 // Without !fpmath accuracy information, we can't do more because we don't 8581 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8582 if (!AllowInaccurateRcp) 8583 return SDValue(); 8584 8585 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8586 if (CLHS->isExactlyValue(1.0)) { 8587 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8588 // the CI documentation has a worst case error of 1 ulp. 8589 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8590 // use it as long as we aren't trying to use denormals. 8591 // 8592 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8593 8594 // 1.0 / sqrt(x) -> rsq(x) 8595 8596 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8597 // error seems really high at 2^29 ULP. 8598 if (RHS.getOpcode() == ISD::FSQRT) 8599 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8600 8601 // 1.0 / x -> rcp(x) 8602 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8603 } 8604 8605 // Same as for 1.0, but expand the sign out of the constant. 8606 if (CLHS->isExactlyValue(-1.0)) { 8607 // -1.0 / x -> rcp (fneg x) 8608 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8609 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8610 } 8611 } 8612 8613 // Turn into multiply by the reciprocal. 8614 // x / y -> x * (1.0 / y) 8615 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8616 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8617 } 8618 8619 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op, 8620 SelectionDAG &DAG) const { 8621 SDLoc SL(Op); 8622 SDValue X = Op.getOperand(0); 8623 SDValue Y = Op.getOperand(1); 8624 EVT VT = Op.getValueType(); 8625 const SDNodeFlags Flags = Op->getFlags(); 8626 8627 bool AllowInaccurateDiv = Flags.hasApproximateFuncs() || 8628 DAG.getTarget().Options.UnsafeFPMath; 8629 if (!AllowInaccurateDiv) 8630 return SDValue(); 8631 8632 SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y); 8633 SDValue One = DAG.getConstantFP(1.0, SL, VT); 8634 8635 SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y); 8636 SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8637 8638 R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R); 8639 SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8640 R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R); 8641 SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R); 8642 SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X); 8643 return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret); 8644 } 8645 8646 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8647 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8648 SDNodeFlags Flags) { 8649 if (GlueChain->getNumValues() <= 1) { 8650 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8651 } 8652 8653 assert(GlueChain->getNumValues() == 3); 8654 8655 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8656 switch (Opcode) { 8657 default: llvm_unreachable("no chain equivalent for opcode"); 8658 case ISD::FMUL: 8659 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8660 break; 8661 } 8662 8663 return DAG.getNode(Opcode, SL, VTList, 8664 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8665 Flags); 8666 } 8667 8668 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8669 EVT VT, SDValue A, SDValue B, SDValue C, 8670 SDValue GlueChain, SDNodeFlags Flags) { 8671 if (GlueChain->getNumValues() <= 1) { 8672 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8673 } 8674 8675 assert(GlueChain->getNumValues() == 3); 8676 8677 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8678 switch (Opcode) { 8679 default: llvm_unreachable("no chain equivalent for opcode"); 8680 case ISD::FMA: 8681 Opcode = AMDGPUISD::FMA_W_CHAIN; 8682 break; 8683 } 8684 8685 return DAG.getNode(Opcode, SL, VTList, 8686 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8687 Flags); 8688 } 8689 8690 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8691 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8692 return FastLowered; 8693 8694 SDLoc SL(Op); 8695 SDValue Src0 = Op.getOperand(0); 8696 SDValue Src1 = Op.getOperand(1); 8697 8698 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8699 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8700 8701 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8702 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8703 8704 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8705 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8706 8707 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8708 } 8709 8710 // Faster 2.5 ULP division that does not support denormals. 8711 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8712 SDLoc SL(Op); 8713 SDValue LHS = Op.getOperand(1); 8714 SDValue RHS = Op.getOperand(2); 8715 8716 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8717 8718 const APFloat K0Val(BitsToFloat(0x6f800000)); 8719 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8720 8721 const APFloat K1Val(BitsToFloat(0x2f800000)); 8722 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8723 8724 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8725 8726 EVT SetCCVT = 8727 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8728 8729 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8730 8731 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8732 8733 // TODO: Should this propagate fast-math-flags? 8734 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8735 8736 // rcp does not support denormals. 8737 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8738 8739 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8740 8741 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8742 } 8743 8744 // Returns immediate value for setting the F32 denorm mode when using the 8745 // S_DENORM_MODE instruction. 8746 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8747 const SDLoc &SL, const GCNSubtarget *ST) { 8748 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8749 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8750 ? FP_DENORM_FLUSH_NONE 8751 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8752 8753 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8754 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8755 } 8756 8757 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8758 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8759 return FastLowered; 8760 8761 // The selection matcher assumes anything with a chain selecting to a 8762 // mayRaiseFPException machine instruction. Since we're introducing a chain 8763 // here, we need to explicitly report nofpexcept for the regular fdiv 8764 // lowering. 8765 SDNodeFlags Flags = Op->getFlags(); 8766 Flags.setNoFPExcept(true); 8767 8768 SDLoc SL(Op); 8769 SDValue LHS = Op.getOperand(0); 8770 SDValue RHS = Op.getOperand(1); 8771 8772 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8773 8774 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8775 8776 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8777 {RHS, RHS, LHS}, Flags); 8778 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8779 {LHS, RHS, LHS}, Flags); 8780 8781 // Denominator is scaled to not be denormal, so using rcp is ok. 8782 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8783 DenominatorScaled, Flags); 8784 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8785 DenominatorScaled, Flags); 8786 8787 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8788 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8789 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8790 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8791 8792 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8793 8794 if (!HasFP32Denormals) { 8795 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8796 // lowering. The chain dependence is insufficient, and we need glue. We do 8797 // not need the glue variants in a strictfp function. 8798 8799 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8800 8801 SDNode *EnableDenorm; 8802 if (Subtarget->hasDenormModeInst()) { 8803 const SDValue EnableDenormValue = 8804 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8805 8806 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8807 DAG.getEntryNode(), EnableDenormValue).getNode(); 8808 } else { 8809 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8810 SL, MVT::i32); 8811 EnableDenorm = 8812 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8813 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8814 } 8815 8816 SDValue Ops[3] = { 8817 NegDivScale0, 8818 SDValue(EnableDenorm, 0), 8819 SDValue(EnableDenorm, 1) 8820 }; 8821 8822 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8823 } 8824 8825 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8826 ApproxRcp, One, NegDivScale0, Flags); 8827 8828 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8829 ApproxRcp, Fma0, Flags); 8830 8831 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8832 Fma1, Fma1, Flags); 8833 8834 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8835 NumeratorScaled, Mul, Flags); 8836 8837 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8838 Fma2, Fma1, Mul, Fma2, Flags); 8839 8840 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8841 NumeratorScaled, Fma3, Flags); 8842 8843 if (!HasFP32Denormals) { 8844 SDNode *DisableDenorm; 8845 if (Subtarget->hasDenormModeInst()) { 8846 const SDValue DisableDenormValue = 8847 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8848 8849 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8850 Fma4.getValue(1), DisableDenormValue, 8851 Fma4.getValue(2)).getNode(); 8852 } else { 8853 const SDValue DisableDenormValue = 8854 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8855 8856 DisableDenorm = DAG.getMachineNode( 8857 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8858 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8859 } 8860 8861 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8862 SDValue(DisableDenorm, 0), DAG.getRoot()); 8863 DAG.setRoot(OutputChain); 8864 } 8865 8866 SDValue Scale = NumeratorScaled.getValue(1); 8867 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8868 {Fma4, Fma1, Fma3, Scale}, Flags); 8869 8870 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8871 } 8872 8873 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8874 if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG)) 8875 return FastLowered; 8876 8877 SDLoc SL(Op); 8878 SDValue X = Op.getOperand(0); 8879 SDValue Y = Op.getOperand(1); 8880 8881 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8882 8883 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8884 8885 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8886 8887 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8888 8889 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8890 8891 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8892 8893 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8894 8895 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8896 8897 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8898 8899 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8900 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8901 8902 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8903 NegDivScale0, Mul, DivScale1); 8904 8905 SDValue Scale; 8906 8907 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8908 // Workaround a hardware bug on SI where the condition output from div_scale 8909 // is not usable. 8910 8911 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8912 8913 // Figure out if the scale to use for div_fmas. 8914 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8915 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8916 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8917 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8918 8919 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8920 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8921 8922 SDValue Scale0Hi 8923 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8924 SDValue Scale1Hi 8925 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8926 8927 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8928 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8929 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8930 } else { 8931 Scale = DivScale1.getValue(1); 8932 } 8933 8934 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8935 Fma4, Fma3, Mul, Scale); 8936 8937 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8938 } 8939 8940 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8941 EVT VT = Op.getValueType(); 8942 8943 if (VT == MVT::f32) 8944 return LowerFDIV32(Op, DAG); 8945 8946 if (VT == MVT::f64) 8947 return LowerFDIV64(Op, DAG); 8948 8949 if (VT == MVT::f16) 8950 return LowerFDIV16(Op, DAG); 8951 8952 llvm_unreachable("Unexpected type for fdiv"); 8953 } 8954 8955 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8956 SDLoc DL(Op); 8957 StoreSDNode *Store = cast<StoreSDNode>(Op); 8958 EVT VT = Store->getMemoryVT(); 8959 8960 if (VT == MVT::i1) { 8961 return DAG.getTruncStore(Store->getChain(), DL, 8962 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8963 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8964 } 8965 8966 assert(VT.isVector() && 8967 Store->getValue().getValueType().getScalarType() == MVT::i32); 8968 8969 unsigned AS = Store->getAddressSpace(); 8970 if (Subtarget->hasLDSMisalignedBug() && 8971 AS == AMDGPUAS::FLAT_ADDRESS && 8972 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8973 return SplitVectorStore(Op, DAG); 8974 } 8975 8976 MachineFunction &MF = DAG.getMachineFunction(); 8977 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8978 // If there is a possibilty that flat instruction access scratch memory 8979 // then we need to use the same legalization rules we use for private. 8980 if (AS == AMDGPUAS::FLAT_ADDRESS && 8981 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8982 AS = MFI->hasFlatScratchInit() ? 8983 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8984 8985 unsigned NumElements = VT.getVectorNumElements(); 8986 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8987 AS == AMDGPUAS::FLAT_ADDRESS) { 8988 if (NumElements > 4) 8989 return SplitVectorStore(Op, DAG); 8990 // v3 stores not supported on SI. 8991 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8992 return SplitVectorStore(Op, DAG); 8993 8994 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8995 VT, *Store->getMemOperand())) 8996 return expandUnalignedStore(Store, DAG); 8997 8998 return SDValue(); 8999 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 9000 switch (Subtarget->getMaxPrivateElementSize()) { 9001 case 4: 9002 return scalarizeVectorStore(Store, DAG); 9003 case 8: 9004 if (NumElements > 2) 9005 return SplitVectorStore(Op, DAG); 9006 return SDValue(); 9007 case 16: 9008 if (NumElements > 4 || 9009 (NumElements == 3 && !Subtarget->enableFlatScratch())) 9010 return SplitVectorStore(Op, DAG); 9011 return SDValue(); 9012 default: 9013 llvm_unreachable("unsupported private_element_size"); 9014 } 9015 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 9016 // Use ds_write_b128 or ds_write_b96 when possible. 9017 if (Subtarget->hasDS96AndDS128() && 9018 ((Subtarget->useDS128() && VT.getStoreSize() == 16) || 9019 (VT.getStoreSize() == 12)) && 9020 allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 9021 Store->getAlign())) 9022 return SDValue(); 9023 9024 if (NumElements > 2) 9025 return SplitVectorStore(Op, DAG); 9026 9027 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 9028 // address is negative, then the instruction is incorrectly treated as 9029 // out-of-bounds even if base + offsets is in bounds. Split vectorized 9030 // stores here to avoid emitting ds_write2_b32. We may re-combine the 9031 // store later in the SILoadStoreOptimizer. 9032 if (!Subtarget->hasUsableDSOffset() && 9033 NumElements == 2 && VT.getStoreSize() == 8 && 9034 Store->getAlignment() < 8) { 9035 return SplitVectorStore(Op, DAG); 9036 } 9037 9038 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 9039 VT, *Store->getMemOperand())) { 9040 if (VT.isVector()) 9041 return SplitVectorStore(Op, DAG); 9042 return expandUnalignedStore(Store, DAG); 9043 } 9044 9045 return SDValue(); 9046 } else { 9047 llvm_unreachable("unhandled address space"); 9048 } 9049 } 9050 9051 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 9052 SDLoc DL(Op); 9053 EVT VT = Op.getValueType(); 9054 SDValue Arg = Op.getOperand(0); 9055 SDValue TrigVal; 9056 9057 // Propagate fast-math flags so that the multiply we introduce can be folded 9058 // if Arg is already the result of a multiply by constant. 9059 auto Flags = Op->getFlags(); 9060 9061 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 9062 9063 if (Subtarget->hasTrigReducedRange()) { 9064 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 9065 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 9066 } else { 9067 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 9068 } 9069 9070 switch (Op.getOpcode()) { 9071 case ISD::FCOS: 9072 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 9073 case ISD::FSIN: 9074 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 9075 default: 9076 llvm_unreachable("Wrong trig opcode"); 9077 } 9078 } 9079 9080 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 9081 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 9082 assert(AtomicNode->isCompareAndSwap()); 9083 unsigned AS = AtomicNode->getAddressSpace(); 9084 9085 // No custom lowering required for local address space 9086 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 9087 return Op; 9088 9089 // Non-local address space requires custom lowering for atomic compare 9090 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 9091 SDLoc DL(Op); 9092 SDValue ChainIn = Op.getOperand(0); 9093 SDValue Addr = Op.getOperand(1); 9094 SDValue Old = Op.getOperand(2); 9095 SDValue New = Op.getOperand(3); 9096 EVT VT = Op.getValueType(); 9097 MVT SimpleVT = VT.getSimpleVT(); 9098 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 9099 9100 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 9101 SDValue Ops[] = { ChainIn, Addr, NewOld }; 9102 9103 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 9104 Ops, VT, AtomicNode->getMemOperand()); 9105 } 9106 9107 //===----------------------------------------------------------------------===// 9108 // Custom DAG optimizations 9109 //===----------------------------------------------------------------------===// 9110 9111 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 9112 DAGCombinerInfo &DCI) const { 9113 EVT VT = N->getValueType(0); 9114 EVT ScalarVT = VT.getScalarType(); 9115 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 9116 return SDValue(); 9117 9118 SelectionDAG &DAG = DCI.DAG; 9119 SDLoc DL(N); 9120 9121 SDValue Src = N->getOperand(0); 9122 EVT SrcVT = Src.getValueType(); 9123 9124 // TODO: We could try to match extracting the higher bytes, which would be 9125 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 9126 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 9127 // about in practice. 9128 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 9129 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 9130 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 9131 DCI.AddToWorklist(Cvt.getNode()); 9132 9133 // For the f16 case, fold to a cast to f32 and then cast back to f16. 9134 if (ScalarVT != MVT::f32) { 9135 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 9136 DAG.getTargetConstant(0, DL, MVT::i32)); 9137 } 9138 return Cvt; 9139 } 9140 } 9141 9142 return SDValue(); 9143 } 9144 9145 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 9146 9147 // This is a variant of 9148 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 9149 // 9150 // The normal DAG combiner will do this, but only if the add has one use since 9151 // that would increase the number of instructions. 9152 // 9153 // This prevents us from seeing a constant offset that can be folded into a 9154 // memory instruction's addressing mode. If we know the resulting add offset of 9155 // a pointer can be folded into an addressing offset, we can replace the pointer 9156 // operand with the add of new constant offset. This eliminates one of the uses, 9157 // and may allow the remaining use to also be simplified. 9158 // 9159 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 9160 unsigned AddrSpace, 9161 EVT MemVT, 9162 DAGCombinerInfo &DCI) const { 9163 SDValue N0 = N->getOperand(0); 9164 SDValue N1 = N->getOperand(1); 9165 9166 // We only do this to handle cases where it's profitable when there are 9167 // multiple uses of the add, so defer to the standard combine. 9168 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 9169 N0->hasOneUse()) 9170 return SDValue(); 9171 9172 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 9173 if (!CN1) 9174 return SDValue(); 9175 9176 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 9177 if (!CAdd) 9178 return SDValue(); 9179 9180 // If the resulting offset is too large, we can't fold it into the addressing 9181 // mode offset. 9182 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 9183 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 9184 9185 AddrMode AM; 9186 AM.HasBaseReg = true; 9187 AM.BaseOffs = Offset.getSExtValue(); 9188 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 9189 return SDValue(); 9190 9191 SelectionDAG &DAG = DCI.DAG; 9192 SDLoc SL(N); 9193 EVT VT = N->getValueType(0); 9194 9195 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 9196 SDValue COffset = DAG.getConstant(Offset, SL, VT); 9197 9198 SDNodeFlags Flags; 9199 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 9200 (N0.getOpcode() == ISD::OR || 9201 N0->getFlags().hasNoUnsignedWrap())); 9202 9203 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 9204 } 9205 9206 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 9207 /// by the chain and intrinsic ID. Theoretically we would also need to check the 9208 /// specific intrinsic, but they all place the pointer operand first. 9209 static unsigned getBasePtrIndex(const MemSDNode *N) { 9210 switch (N->getOpcode()) { 9211 case ISD::STORE: 9212 case ISD::INTRINSIC_W_CHAIN: 9213 case ISD::INTRINSIC_VOID: 9214 return 2; 9215 default: 9216 return 1; 9217 } 9218 } 9219 9220 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 9221 DAGCombinerInfo &DCI) const { 9222 SelectionDAG &DAG = DCI.DAG; 9223 SDLoc SL(N); 9224 9225 unsigned PtrIdx = getBasePtrIndex(N); 9226 SDValue Ptr = N->getOperand(PtrIdx); 9227 9228 // TODO: We could also do this for multiplies. 9229 if (Ptr.getOpcode() == ISD::SHL) { 9230 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 9231 N->getMemoryVT(), DCI); 9232 if (NewPtr) { 9233 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 9234 9235 NewOps[PtrIdx] = NewPtr; 9236 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 9237 } 9238 } 9239 9240 return SDValue(); 9241 } 9242 9243 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 9244 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 9245 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 9246 (Opc == ISD::XOR && Val == 0); 9247 } 9248 9249 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 9250 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 9251 // integer combine opportunities since most 64-bit operations are decomposed 9252 // this way. TODO: We won't want this for SALU especially if it is an inline 9253 // immediate. 9254 SDValue SITargetLowering::splitBinaryBitConstantOp( 9255 DAGCombinerInfo &DCI, 9256 const SDLoc &SL, 9257 unsigned Opc, SDValue LHS, 9258 const ConstantSDNode *CRHS) const { 9259 uint64_t Val = CRHS->getZExtValue(); 9260 uint32_t ValLo = Lo_32(Val); 9261 uint32_t ValHi = Hi_32(Val); 9262 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9263 9264 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 9265 bitOpWithConstantIsReducible(Opc, ValHi)) || 9266 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 9267 // If we need to materialize a 64-bit immediate, it will be split up later 9268 // anyway. Avoid creating the harder to understand 64-bit immediate 9269 // materialization. 9270 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 9271 } 9272 9273 return SDValue(); 9274 } 9275 9276 // Returns true if argument is a boolean value which is not serialized into 9277 // memory or argument and does not require v_cndmask_b32 to be deserialized. 9278 static bool isBoolSGPR(SDValue V) { 9279 if (V.getValueType() != MVT::i1) 9280 return false; 9281 switch (V.getOpcode()) { 9282 default: 9283 break; 9284 case ISD::SETCC: 9285 case AMDGPUISD::FP_CLASS: 9286 return true; 9287 case ISD::AND: 9288 case ISD::OR: 9289 case ISD::XOR: 9290 return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1)); 9291 } 9292 return false; 9293 } 9294 9295 // If a constant has all zeroes or all ones within each byte return it. 9296 // Otherwise return 0. 9297 static uint32_t getConstantPermuteMask(uint32_t C) { 9298 // 0xff for any zero byte in the mask 9299 uint32_t ZeroByteMask = 0; 9300 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 9301 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 9302 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 9303 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 9304 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 9305 if ((NonZeroByteMask & C) != NonZeroByteMask) 9306 return 0; // Partial bytes selected. 9307 return C; 9308 } 9309 9310 // Check if a node selects whole bytes from its operand 0 starting at a byte 9311 // boundary while masking the rest. Returns select mask as in the v_perm_b32 9312 // or -1 if not succeeded. 9313 // Note byte select encoding: 9314 // value 0-3 selects corresponding source byte; 9315 // value 0xc selects zero; 9316 // value 0xff selects 0xff. 9317 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 9318 assert(V.getValueSizeInBits() == 32); 9319 9320 if (V.getNumOperands() != 2) 9321 return ~0; 9322 9323 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 9324 if (!N1) 9325 return ~0; 9326 9327 uint32_t C = N1->getZExtValue(); 9328 9329 switch (V.getOpcode()) { 9330 default: 9331 break; 9332 case ISD::AND: 9333 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9334 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 9335 } 9336 break; 9337 9338 case ISD::OR: 9339 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9340 return (0x03020100 & ~ConstMask) | ConstMask; 9341 } 9342 break; 9343 9344 case ISD::SHL: 9345 if (C % 8) 9346 return ~0; 9347 9348 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 9349 9350 case ISD::SRL: 9351 if (C % 8) 9352 return ~0; 9353 9354 return uint32_t(0x0c0c0c0c03020100ull >> C); 9355 } 9356 9357 return ~0; 9358 } 9359 9360 SDValue SITargetLowering::performAndCombine(SDNode *N, 9361 DAGCombinerInfo &DCI) const { 9362 if (DCI.isBeforeLegalize()) 9363 return SDValue(); 9364 9365 SelectionDAG &DAG = DCI.DAG; 9366 EVT VT = N->getValueType(0); 9367 SDValue LHS = N->getOperand(0); 9368 SDValue RHS = N->getOperand(1); 9369 9370 9371 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9372 if (VT == MVT::i64 && CRHS) { 9373 if (SDValue Split 9374 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 9375 return Split; 9376 } 9377 9378 if (CRHS && VT == MVT::i32) { 9379 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 9380 // nb = number of trailing zeroes in mask 9381 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 9382 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 9383 uint64_t Mask = CRHS->getZExtValue(); 9384 unsigned Bits = countPopulation(Mask); 9385 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 9386 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 9387 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 9388 unsigned Shift = CShift->getZExtValue(); 9389 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 9390 unsigned Offset = NB + Shift; 9391 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 9392 SDLoc SL(N); 9393 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 9394 LHS->getOperand(0), 9395 DAG.getConstant(Offset, SL, MVT::i32), 9396 DAG.getConstant(Bits, SL, MVT::i32)); 9397 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9398 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 9399 DAG.getValueType(NarrowVT)); 9400 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 9401 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 9402 return Shl; 9403 } 9404 } 9405 } 9406 9407 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9408 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 9409 isa<ConstantSDNode>(LHS.getOperand(2))) { 9410 uint32_t Sel = getConstantPermuteMask(Mask); 9411 if (!Sel) 9412 return SDValue(); 9413 9414 // Select 0xc for all zero bytes 9415 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 9416 SDLoc DL(N); 9417 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9418 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9419 } 9420 } 9421 9422 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 9423 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 9424 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 9425 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9426 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 9427 9428 SDValue X = LHS.getOperand(0); 9429 SDValue Y = RHS.getOperand(0); 9430 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 9431 return SDValue(); 9432 9433 if (LCC == ISD::SETO) { 9434 if (X != LHS.getOperand(1)) 9435 return SDValue(); 9436 9437 if (RCC == ISD::SETUNE) { 9438 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 9439 if (!C1 || !C1->isInfinity() || C1->isNegative()) 9440 return SDValue(); 9441 9442 const uint32_t Mask = SIInstrFlags::N_NORMAL | 9443 SIInstrFlags::N_SUBNORMAL | 9444 SIInstrFlags::N_ZERO | 9445 SIInstrFlags::P_ZERO | 9446 SIInstrFlags::P_SUBNORMAL | 9447 SIInstrFlags::P_NORMAL; 9448 9449 static_assert(((~(SIInstrFlags::S_NAN | 9450 SIInstrFlags::Q_NAN | 9451 SIInstrFlags::N_INFINITY | 9452 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 9453 "mask not equal"); 9454 9455 SDLoc DL(N); 9456 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9457 X, DAG.getConstant(Mask, DL, MVT::i32)); 9458 } 9459 } 9460 } 9461 9462 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 9463 std::swap(LHS, RHS); 9464 9465 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 9466 RHS.hasOneUse()) { 9467 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9468 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 9469 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 9470 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9471 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 9472 (RHS.getOperand(0) == LHS.getOperand(0) && 9473 LHS.getOperand(0) == LHS.getOperand(1))) { 9474 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 9475 unsigned NewMask = LCC == ISD::SETO ? 9476 Mask->getZExtValue() & ~OrdMask : 9477 Mask->getZExtValue() & OrdMask; 9478 9479 SDLoc DL(N); 9480 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 9481 DAG.getConstant(NewMask, DL, MVT::i32)); 9482 } 9483 } 9484 9485 if (VT == MVT::i32 && 9486 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 9487 // and x, (sext cc from i1) => select cc, x, 0 9488 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 9489 std::swap(LHS, RHS); 9490 if (isBoolSGPR(RHS.getOperand(0))) 9491 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 9492 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 9493 } 9494 9495 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9496 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9497 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9498 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9499 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9500 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9501 if (LHSMask != ~0u && RHSMask != ~0u) { 9502 // Canonicalize the expression in an attempt to have fewer unique masks 9503 // and therefore fewer registers used to hold the masks. 9504 if (LHSMask > RHSMask) { 9505 std::swap(LHSMask, RHSMask); 9506 std::swap(LHS, RHS); 9507 } 9508 9509 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9510 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9511 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9512 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9513 9514 // Check of we need to combine values from two sources within a byte. 9515 if (!(LHSUsedLanes & RHSUsedLanes) && 9516 // If we select high and lower word keep it for SDWA. 9517 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9518 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9519 // Each byte in each mask is either selector mask 0-3, or has higher 9520 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 9521 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 9522 // mask which is not 0xff wins. By anding both masks we have a correct 9523 // result except that 0x0c shall be corrected to give 0x0c only. 9524 uint32_t Mask = LHSMask & RHSMask; 9525 for (unsigned I = 0; I < 32; I += 8) { 9526 uint32_t ByteSel = 0xff << I; 9527 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 9528 Mask &= (0x0c << I) & 0xffffffff; 9529 } 9530 9531 // Add 4 to each active LHS lane. It will not affect any existing 0xff 9532 // or 0x0c. 9533 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 9534 SDLoc DL(N); 9535 9536 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9537 LHS.getOperand(0), RHS.getOperand(0), 9538 DAG.getConstant(Sel, DL, MVT::i32)); 9539 } 9540 } 9541 } 9542 9543 return SDValue(); 9544 } 9545 9546 SDValue SITargetLowering::performOrCombine(SDNode *N, 9547 DAGCombinerInfo &DCI) const { 9548 SelectionDAG &DAG = DCI.DAG; 9549 SDValue LHS = N->getOperand(0); 9550 SDValue RHS = N->getOperand(1); 9551 9552 EVT VT = N->getValueType(0); 9553 if (VT == MVT::i1) { 9554 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 9555 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 9556 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 9557 SDValue Src = LHS.getOperand(0); 9558 if (Src != RHS.getOperand(0)) 9559 return SDValue(); 9560 9561 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9562 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9563 if (!CLHS || !CRHS) 9564 return SDValue(); 9565 9566 // Only 10 bits are used. 9567 static const uint32_t MaxMask = 0x3ff; 9568 9569 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 9570 SDLoc DL(N); 9571 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9572 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 9573 } 9574 9575 return SDValue(); 9576 } 9577 9578 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9579 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 9580 LHS.getOpcode() == AMDGPUISD::PERM && 9581 isa<ConstantSDNode>(LHS.getOperand(2))) { 9582 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 9583 if (!Sel) 9584 return SDValue(); 9585 9586 Sel |= LHS.getConstantOperandVal(2); 9587 SDLoc DL(N); 9588 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9589 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9590 } 9591 9592 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9593 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9594 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9595 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9596 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9597 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9598 if (LHSMask != ~0u && RHSMask != ~0u) { 9599 // Canonicalize the expression in an attempt to have fewer unique masks 9600 // and therefore fewer registers used to hold the masks. 9601 if (LHSMask > RHSMask) { 9602 std::swap(LHSMask, RHSMask); 9603 std::swap(LHS, RHS); 9604 } 9605 9606 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9607 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9608 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9609 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9610 9611 // Check of we need to combine values from two sources within a byte. 9612 if (!(LHSUsedLanes & RHSUsedLanes) && 9613 // If we select high and lower word keep it for SDWA. 9614 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9615 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9616 // Kill zero bytes selected by other mask. Zero value is 0xc. 9617 LHSMask &= ~RHSUsedLanes; 9618 RHSMask &= ~LHSUsedLanes; 9619 // Add 4 to each active LHS lane 9620 LHSMask |= LHSUsedLanes & 0x04040404; 9621 // Combine masks 9622 uint32_t Sel = LHSMask | RHSMask; 9623 SDLoc DL(N); 9624 9625 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9626 LHS.getOperand(0), RHS.getOperand(0), 9627 DAG.getConstant(Sel, DL, MVT::i32)); 9628 } 9629 } 9630 } 9631 9632 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9633 return SDValue(); 9634 9635 // TODO: This could be a generic combine with a predicate for extracting the 9636 // high half of an integer being free. 9637 9638 // (or i64:x, (zero_extend i32:y)) -> 9639 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9640 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9641 RHS.getOpcode() != ISD::ZERO_EXTEND) 9642 std::swap(LHS, RHS); 9643 9644 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9645 SDValue ExtSrc = RHS.getOperand(0); 9646 EVT SrcVT = ExtSrc.getValueType(); 9647 if (SrcVT == MVT::i32) { 9648 SDLoc SL(N); 9649 SDValue LowLHS, HiBits; 9650 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9651 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9652 9653 DCI.AddToWorklist(LowOr.getNode()); 9654 DCI.AddToWorklist(HiBits.getNode()); 9655 9656 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9657 LowOr, HiBits); 9658 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9659 } 9660 } 9661 9662 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9663 if (CRHS) { 9664 if (SDValue Split 9665 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, 9666 N->getOperand(0), CRHS)) 9667 return Split; 9668 } 9669 9670 return SDValue(); 9671 } 9672 9673 SDValue SITargetLowering::performXorCombine(SDNode *N, 9674 DAGCombinerInfo &DCI) const { 9675 if (SDValue RV = reassociateScalarOps(N, DCI.DAG)) 9676 return RV; 9677 9678 EVT VT = N->getValueType(0); 9679 if (VT != MVT::i64) 9680 return SDValue(); 9681 9682 SDValue LHS = N->getOperand(0); 9683 SDValue RHS = N->getOperand(1); 9684 9685 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9686 if (CRHS) { 9687 if (SDValue Split 9688 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9689 return Split; 9690 } 9691 9692 return SDValue(); 9693 } 9694 9695 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9696 DAGCombinerInfo &DCI) const { 9697 if (!Subtarget->has16BitInsts() || 9698 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9699 return SDValue(); 9700 9701 EVT VT = N->getValueType(0); 9702 if (VT != MVT::i32) 9703 return SDValue(); 9704 9705 SDValue Src = N->getOperand(0); 9706 if (Src.getValueType() != MVT::i16) 9707 return SDValue(); 9708 9709 return SDValue(); 9710 } 9711 9712 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9713 DAGCombinerInfo &DCI) 9714 const { 9715 SDValue Src = N->getOperand(0); 9716 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9717 9718 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9719 VTSign->getVT() == MVT::i8) || 9720 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9721 VTSign->getVT() == MVT::i16)) && 9722 Src.hasOneUse()) { 9723 auto *M = cast<MemSDNode>(Src); 9724 SDValue Ops[] = { 9725 Src.getOperand(0), // Chain 9726 Src.getOperand(1), // rsrc 9727 Src.getOperand(2), // vindex 9728 Src.getOperand(3), // voffset 9729 Src.getOperand(4), // soffset 9730 Src.getOperand(5), // offset 9731 Src.getOperand(6), 9732 Src.getOperand(7) 9733 }; 9734 // replace with BUFFER_LOAD_BYTE/SHORT 9735 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9736 Src.getOperand(0).getValueType()); 9737 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9738 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9739 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9740 ResList, 9741 Ops, M->getMemoryVT(), 9742 M->getMemOperand()); 9743 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9744 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9745 } 9746 return SDValue(); 9747 } 9748 9749 SDValue SITargetLowering::performClassCombine(SDNode *N, 9750 DAGCombinerInfo &DCI) const { 9751 SelectionDAG &DAG = DCI.DAG; 9752 SDValue Mask = N->getOperand(1); 9753 9754 // fp_class x, 0 -> false 9755 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9756 if (CMask->isZero()) 9757 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9758 } 9759 9760 if (N->getOperand(0).isUndef()) 9761 return DAG.getUNDEF(MVT::i1); 9762 9763 return SDValue(); 9764 } 9765 9766 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9767 DAGCombinerInfo &DCI) const { 9768 EVT VT = N->getValueType(0); 9769 SDValue N0 = N->getOperand(0); 9770 9771 if (N0.isUndef()) 9772 return N0; 9773 9774 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9775 N0.getOpcode() == ISD::SINT_TO_FP)) { 9776 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9777 N->getFlags()); 9778 } 9779 9780 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9781 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9782 N0.getOperand(0), N->getFlags()); 9783 } 9784 9785 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9786 } 9787 9788 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9789 unsigned MaxDepth) const { 9790 unsigned Opcode = Op.getOpcode(); 9791 if (Opcode == ISD::FCANONICALIZE) 9792 return true; 9793 9794 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9795 auto F = CFP->getValueAPF(); 9796 if (F.isNaN() && F.isSignaling()) 9797 return false; 9798 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9799 } 9800 9801 // If source is a result of another standard FP operation it is already in 9802 // canonical form. 9803 if (MaxDepth == 0) 9804 return false; 9805 9806 switch (Opcode) { 9807 // These will flush denorms if required. 9808 case ISD::FADD: 9809 case ISD::FSUB: 9810 case ISD::FMUL: 9811 case ISD::FCEIL: 9812 case ISD::FFLOOR: 9813 case ISD::FMA: 9814 case ISD::FMAD: 9815 case ISD::FSQRT: 9816 case ISD::FDIV: 9817 case ISD::FREM: 9818 case ISD::FP_ROUND: 9819 case ISD::FP_EXTEND: 9820 case AMDGPUISD::FMUL_LEGACY: 9821 case AMDGPUISD::FMAD_FTZ: 9822 case AMDGPUISD::RCP: 9823 case AMDGPUISD::RSQ: 9824 case AMDGPUISD::RSQ_CLAMP: 9825 case AMDGPUISD::RCP_LEGACY: 9826 case AMDGPUISD::RCP_IFLAG: 9827 case AMDGPUISD::DIV_SCALE: 9828 case AMDGPUISD::DIV_FMAS: 9829 case AMDGPUISD::DIV_FIXUP: 9830 case AMDGPUISD::FRACT: 9831 case AMDGPUISD::LDEXP: 9832 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9833 case AMDGPUISD::CVT_F32_UBYTE0: 9834 case AMDGPUISD::CVT_F32_UBYTE1: 9835 case AMDGPUISD::CVT_F32_UBYTE2: 9836 case AMDGPUISD::CVT_F32_UBYTE3: 9837 return true; 9838 9839 // It can/will be lowered or combined as a bit operation. 9840 // Need to check their input recursively to handle. 9841 case ISD::FNEG: 9842 case ISD::FABS: 9843 case ISD::FCOPYSIGN: 9844 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9845 9846 case ISD::FSIN: 9847 case ISD::FCOS: 9848 case ISD::FSINCOS: 9849 return Op.getValueType().getScalarType() != MVT::f16; 9850 9851 case ISD::FMINNUM: 9852 case ISD::FMAXNUM: 9853 case ISD::FMINNUM_IEEE: 9854 case ISD::FMAXNUM_IEEE: 9855 case AMDGPUISD::CLAMP: 9856 case AMDGPUISD::FMED3: 9857 case AMDGPUISD::FMAX3: 9858 case AMDGPUISD::FMIN3: { 9859 // FIXME: Shouldn't treat the generic operations different based these. 9860 // However, we aren't really required to flush the result from 9861 // minnum/maxnum.. 9862 9863 // snans will be quieted, so we only need to worry about denormals. 9864 if (Subtarget->supportsMinMaxDenormModes() || 9865 denormalsEnabledForType(DAG, Op.getValueType())) 9866 return true; 9867 9868 // Flushing may be required. 9869 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9870 // targets need to check their input recursively. 9871 9872 // FIXME: Does this apply with clamp? It's implemented with max. 9873 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9874 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9875 return false; 9876 } 9877 9878 return true; 9879 } 9880 case ISD::SELECT: { 9881 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9882 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9883 } 9884 case ISD::BUILD_VECTOR: { 9885 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9886 SDValue SrcOp = Op.getOperand(i); 9887 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9888 return false; 9889 } 9890 9891 return true; 9892 } 9893 case ISD::EXTRACT_VECTOR_ELT: 9894 case ISD::EXTRACT_SUBVECTOR: { 9895 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9896 } 9897 case ISD::INSERT_VECTOR_ELT: { 9898 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9899 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9900 } 9901 case ISD::UNDEF: 9902 // Could be anything. 9903 return false; 9904 9905 case ISD::BITCAST: 9906 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9907 case ISD::TRUNCATE: { 9908 // Hack round the mess we make when legalizing extract_vector_elt 9909 if (Op.getValueType() == MVT::i16) { 9910 SDValue TruncSrc = Op.getOperand(0); 9911 if (TruncSrc.getValueType() == MVT::i32 && 9912 TruncSrc.getOpcode() == ISD::BITCAST && 9913 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9914 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9915 } 9916 } 9917 return false; 9918 } 9919 case ISD::INTRINSIC_WO_CHAIN: { 9920 unsigned IntrinsicID 9921 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9922 // TODO: Handle more intrinsics 9923 switch (IntrinsicID) { 9924 case Intrinsic::amdgcn_cvt_pkrtz: 9925 case Intrinsic::amdgcn_cubeid: 9926 case Intrinsic::amdgcn_frexp_mant: 9927 case Intrinsic::amdgcn_fdot2: 9928 case Intrinsic::amdgcn_rcp: 9929 case Intrinsic::amdgcn_rsq: 9930 case Intrinsic::amdgcn_rsq_clamp: 9931 case Intrinsic::amdgcn_rcp_legacy: 9932 case Intrinsic::amdgcn_rsq_legacy: 9933 case Intrinsic::amdgcn_trig_preop: 9934 return true; 9935 default: 9936 break; 9937 } 9938 9939 LLVM_FALLTHROUGH; 9940 } 9941 default: 9942 return denormalsEnabledForType(DAG, Op.getValueType()) && 9943 DAG.isKnownNeverSNaN(Op); 9944 } 9945 9946 llvm_unreachable("invalid operation"); 9947 } 9948 9949 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF, 9950 unsigned MaxDepth) const { 9951 MachineRegisterInfo &MRI = MF.getRegInfo(); 9952 MachineInstr *MI = MRI.getVRegDef(Reg); 9953 unsigned Opcode = MI->getOpcode(); 9954 9955 if (Opcode == AMDGPU::G_FCANONICALIZE) 9956 return true; 9957 9958 Optional<FPValueAndVReg> FCR; 9959 // Constant splat (can be padded with undef) or scalar constant. 9960 if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) { 9961 if (FCR->Value.isSignaling()) 9962 return false; 9963 return !FCR->Value.isDenormal() || 9964 denormalsEnabledForType(MRI.getType(FCR->VReg), MF); 9965 } 9966 9967 if (MaxDepth == 0) 9968 return false; 9969 9970 switch (Opcode) { 9971 case AMDGPU::G_FMINNUM_IEEE: 9972 case AMDGPU::G_FMAXNUM_IEEE: { 9973 if (Subtarget->supportsMinMaxDenormModes() || 9974 denormalsEnabledForType(MRI.getType(Reg), MF)) 9975 return true; 9976 for (const MachineOperand &MO : llvm::drop_begin(MI->operands())) 9977 if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1)) 9978 return false; 9979 return true; 9980 } 9981 default: 9982 return denormalsEnabledForType(MRI.getType(Reg), MF) && 9983 isKnownNeverSNaN(Reg, MRI); 9984 } 9985 9986 llvm_unreachable("invalid operation"); 9987 } 9988 9989 // Constant fold canonicalize. 9990 SDValue SITargetLowering::getCanonicalConstantFP( 9991 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9992 // Flush denormals to 0 if not enabled. 9993 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9994 return DAG.getConstantFP(0.0, SL, VT); 9995 9996 if (C.isNaN()) { 9997 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9998 if (C.isSignaling()) { 9999 // Quiet a signaling NaN. 10000 // FIXME: Is this supposed to preserve payload bits? 10001 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 10002 } 10003 10004 // Make sure it is the canonical NaN bitpattern. 10005 // 10006 // TODO: Can we use -1 as the canonical NaN value since it's an inline 10007 // immediate? 10008 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 10009 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 10010 } 10011 10012 // Already canonical. 10013 return DAG.getConstantFP(C, SL, VT); 10014 } 10015 10016 static bool vectorEltWillFoldAway(SDValue Op) { 10017 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 10018 } 10019 10020 SDValue SITargetLowering::performFCanonicalizeCombine( 10021 SDNode *N, 10022 DAGCombinerInfo &DCI) const { 10023 SelectionDAG &DAG = DCI.DAG; 10024 SDValue N0 = N->getOperand(0); 10025 EVT VT = N->getValueType(0); 10026 10027 // fcanonicalize undef -> qnan 10028 if (N0.isUndef()) { 10029 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 10030 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 10031 } 10032 10033 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 10034 EVT VT = N->getValueType(0); 10035 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 10036 } 10037 10038 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 10039 // (fcanonicalize k) 10040 // 10041 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 10042 10043 // TODO: This could be better with wider vectors that will be split to v2f16, 10044 // and to consider uses since there aren't that many packed operations. 10045 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 10046 isTypeLegal(MVT::v2f16)) { 10047 SDLoc SL(N); 10048 SDValue NewElts[2]; 10049 SDValue Lo = N0.getOperand(0); 10050 SDValue Hi = N0.getOperand(1); 10051 EVT EltVT = Lo.getValueType(); 10052 10053 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 10054 for (unsigned I = 0; I != 2; ++I) { 10055 SDValue Op = N0.getOperand(I); 10056 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 10057 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 10058 CFP->getValueAPF()); 10059 } else if (Op.isUndef()) { 10060 // Handled below based on what the other operand is. 10061 NewElts[I] = Op; 10062 } else { 10063 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 10064 } 10065 } 10066 10067 // If one half is undef, and one is constant, perfer a splat vector rather 10068 // than the normal qNaN. If it's a register, prefer 0.0 since that's 10069 // cheaper to use and may be free with a packed operation. 10070 if (NewElts[0].isUndef()) { 10071 if (isa<ConstantFPSDNode>(NewElts[1])) 10072 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 10073 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 10074 } 10075 10076 if (NewElts[1].isUndef()) { 10077 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 10078 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 10079 } 10080 10081 return DAG.getBuildVector(VT, SL, NewElts); 10082 } 10083 } 10084 10085 unsigned SrcOpc = N0.getOpcode(); 10086 10087 // If it's free to do so, push canonicalizes further up the source, which may 10088 // find a canonical source. 10089 // 10090 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 10091 // sNaNs. 10092 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 10093 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 10094 if (CRHS && N0.hasOneUse()) { 10095 SDLoc SL(N); 10096 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 10097 N0.getOperand(0)); 10098 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 10099 DCI.AddToWorklist(Canon0.getNode()); 10100 10101 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 10102 } 10103 } 10104 10105 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 10106 } 10107 10108 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 10109 switch (Opc) { 10110 case ISD::FMAXNUM: 10111 case ISD::FMAXNUM_IEEE: 10112 return AMDGPUISD::FMAX3; 10113 case ISD::SMAX: 10114 return AMDGPUISD::SMAX3; 10115 case ISD::UMAX: 10116 return AMDGPUISD::UMAX3; 10117 case ISD::FMINNUM: 10118 case ISD::FMINNUM_IEEE: 10119 return AMDGPUISD::FMIN3; 10120 case ISD::SMIN: 10121 return AMDGPUISD::SMIN3; 10122 case ISD::UMIN: 10123 return AMDGPUISD::UMIN3; 10124 default: 10125 llvm_unreachable("Not a min/max opcode"); 10126 } 10127 } 10128 10129 SDValue SITargetLowering::performIntMed3ImmCombine( 10130 SelectionDAG &DAG, const SDLoc &SL, 10131 SDValue Op0, SDValue Op1, bool Signed) const { 10132 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 10133 if (!K1) 10134 return SDValue(); 10135 10136 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 10137 if (!K0) 10138 return SDValue(); 10139 10140 if (Signed) { 10141 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 10142 return SDValue(); 10143 } else { 10144 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 10145 return SDValue(); 10146 } 10147 10148 EVT VT = K0->getValueType(0); 10149 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 10150 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 10151 return DAG.getNode(Med3Opc, SL, VT, 10152 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 10153 } 10154 10155 // If there isn't a 16-bit med3 operation, convert to 32-bit. 10156 if (VT == MVT::i16) { 10157 MVT NVT = MVT::i32; 10158 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 10159 10160 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 10161 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 10162 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 10163 10164 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 10165 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 10166 } 10167 10168 return SDValue(); 10169 } 10170 10171 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 10172 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 10173 return C; 10174 10175 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 10176 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 10177 return C; 10178 } 10179 10180 return nullptr; 10181 } 10182 10183 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 10184 const SDLoc &SL, 10185 SDValue Op0, 10186 SDValue Op1) const { 10187 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 10188 if (!K1) 10189 return SDValue(); 10190 10191 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 10192 if (!K0) 10193 return SDValue(); 10194 10195 // Ordered >= (although NaN inputs should have folded away by now). 10196 if (K0->getValueAPF() > K1->getValueAPF()) 10197 return SDValue(); 10198 10199 const MachineFunction &MF = DAG.getMachineFunction(); 10200 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10201 10202 // TODO: Check IEEE bit enabled? 10203 EVT VT = Op0.getValueType(); 10204 if (Info->getMode().DX10Clamp) { 10205 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 10206 // hardware fmed3 behavior converting to a min. 10207 // FIXME: Should this be allowing -0.0? 10208 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 10209 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 10210 } 10211 10212 // med3 for f16 is only available on gfx9+, and not available for v2f16. 10213 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 10214 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 10215 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 10216 // then give the other result, which is different from med3 with a NaN 10217 // input. 10218 SDValue Var = Op0.getOperand(0); 10219 if (!DAG.isKnownNeverSNaN(Var)) 10220 return SDValue(); 10221 10222 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10223 10224 if ((!K0->hasOneUse() || 10225 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 10226 (!K1->hasOneUse() || 10227 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 10228 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 10229 Var, SDValue(K0, 0), SDValue(K1, 0)); 10230 } 10231 } 10232 10233 return SDValue(); 10234 } 10235 10236 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 10237 DAGCombinerInfo &DCI) const { 10238 SelectionDAG &DAG = DCI.DAG; 10239 10240 EVT VT = N->getValueType(0); 10241 unsigned Opc = N->getOpcode(); 10242 SDValue Op0 = N->getOperand(0); 10243 SDValue Op1 = N->getOperand(1); 10244 10245 // Only do this if the inner op has one use since this will just increases 10246 // register pressure for no benefit. 10247 10248 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 10249 !VT.isVector() && 10250 (VT == MVT::i32 || VT == MVT::f32 || 10251 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 10252 // max(max(a, b), c) -> max3(a, b, c) 10253 // min(min(a, b), c) -> min3(a, b, c) 10254 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 10255 SDLoc DL(N); 10256 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10257 DL, 10258 N->getValueType(0), 10259 Op0.getOperand(0), 10260 Op0.getOperand(1), 10261 Op1); 10262 } 10263 10264 // Try commuted. 10265 // max(a, max(b, c)) -> max3(a, b, c) 10266 // min(a, min(b, c)) -> min3(a, b, c) 10267 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 10268 SDLoc DL(N); 10269 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10270 DL, 10271 N->getValueType(0), 10272 Op0, 10273 Op1.getOperand(0), 10274 Op1.getOperand(1)); 10275 } 10276 } 10277 10278 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 10279 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 10280 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 10281 return Med3; 10282 } 10283 10284 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 10285 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 10286 return Med3; 10287 } 10288 10289 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 10290 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 10291 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 10292 (Opc == AMDGPUISD::FMIN_LEGACY && 10293 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 10294 (VT == MVT::f32 || VT == MVT::f64 || 10295 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 10296 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 10297 Op0.hasOneUse()) { 10298 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 10299 return Res; 10300 } 10301 10302 return SDValue(); 10303 } 10304 10305 static bool isClampZeroToOne(SDValue A, SDValue B) { 10306 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 10307 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 10308 // FIXME: Should this be allowing -0.0? 10309 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 10310 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 10311 } 10312 } 10313 10314 return false; 10315 } 10316 10317 // FIXME: Should only worry about snans for version with chain. 10318 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 10319 DAGCombinerInfo &DCI) const { 10320 EVT VT = N->getValueType(0); 10321 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 10322 // NaNs. With a NaN input, the order of the operands may change the result. 10323 10324 SelectionDAG &DAG = DCI.DAG; 10325 SDLoc SL(N); 10326 10327 SDValue Src0 = N->getOperand(0); 10328 SDValue Src1 = N->getOperand(1); 10329 SDValue Src2 = N->getOperand(2); 10330 10331 if (isClampZeroToOne(Src0, Src1)) { 10332 // const_a, const_b, x -> clamp is safe in all cases including signaling 10333 // nans. 10334 // FIXME: Should this be allowing -0.0? 10335 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 10336 } 10337 10338 const MachineFunction &MF = DAG.getMachineFunction(); 10339 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10340 10341 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 10342 // handling no dx10-clamp? 10343 if (Info->getMode().DX10Clamp) { 10344 // If NaNs is clamped to 0, we are free to reorder the inputs. 10345 10346 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10347 std::swap(Src0, Src1); 10348 10349 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 10350 std::swap(Src1, Src2); 10351 10352 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10353 std::swap(Src0, Src1); 10354 10355 if (isClampZeroToOne(Src1, Src2)) 10356 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 10357 } 10358 10359 return SDValue(); 10360 } 10361 10362 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 10363 DAGCombinerInfo &DCI) const { 10364 SDValue Src0 = N->getOperand(0); 10365 SDValue Src1 = N->getOperand(1); 10366 if (Src0.isUndef() && Src1.isUndef()) 10367 return DCI.DAG.getUNDEF(N->getValueType(0)); 10368 return SDValue(); 10369 } 10370 10371 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 10372 // expanded into a set of cmp/select instructions. 10373 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 10374 unsigned NumElem, 10375 bool IsDivergentIdx) { 10376 if (UseDivergentRegisterIndexing) 10377 return false; 10378 10379 unsigned VecSize = EltSize * NumElem; 10380 10381 // Sub-dword vectors of size 2 dword or less have better implementation. 10382 if (VecSize <= 64 && EltSize < 32) 10383 return false; 10384 10385 // Always expand the rest of sub-dword instructions, otherwise it will be 10386 // lowered via memory. 10387 if (EltSize < 32) 10388 return true; 10389 10390 // Always do this if var-idx is divergent, otherwise it will become a loop. 10391 if (IsDivergentIdx) 10392 return true; 10393 10394 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 10395 unsigned NumInsts = NumElem /* Number of compares */ + 10396 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 10397 return NumInsts <= 16; 10398 } 10399 10400 static bool shouldExpandVectorDynExt(SDNode *N) { 10401 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 10402 if (isa<ConstantSDNode>(Idx)) 10403 return false; 10404 10405 SDValue Vec = N->getOperand(0); 10406 EVT VecVT = Vec.getValueType(); 10407 EVT EltVT = VecVT.getVectorElementType(); 10408 unsigned EltSize = EltVT.getSizeInBits(); 10409 unsigned NumElem = VecVT.getVectorNumElements(); 10410 10411 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 10412 Idx->isDivergent()); 10413 } 10414 10415 SDValue SITargetLowering::performExtractVectorEltCombine( 10416 SDNode *N, DAGCombinerInfo &DCI) const { 10417 SDValue Vec = N->getOperand(0); 10418 SelectionDAG &DAG = DCI.DAG; 10419 10420 EVT VecVT = Vec.getValueType(); 10421 EVT EltVT = VecVT.getVectorElementType(); 10422 10423 if ((Vec.getOpcode() == ISD::FNEG || 10424 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 10425 SDLoc SL(N); 10426 EVT EltVT = N->getValueType(0); 10427 SDValue Idx = N->getOperand(1); 10428 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10429 Vec.getOperand(0), Idx); 10430 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 10431 } 10432 10433 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 10434 // => 10435 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 10436 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 10437 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 10438 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 10439 SDLoc SL(N); 10440 EVT EltVT = N->getValueType(0); 10441 SDValue Idx = N->getOperand(1); 10442 unsigned Opc = Vec.getOpcode(); 10443 10444 switch(Opc) { 10445 default: 10446 break; 10447 // TODO: Support other binary operations. 10448 case ISD::FADD: 10449 case ISD::FSUB: 10450 case ISD::FMUL: 10451 case ISD::ADD: 10452 case ISD::UMIN: 10453 case ISD::UMAX: 10454 case ISD::SMIN: 10455 case ISD::SMAX: 10456 case ISD::FMAXNUM: 10457 case ISD::FMINNUM: 10458 case ISD::FMAXNUM_IEEE: 10459 case ISD::FMINNUM_IEEE: { 10460 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10461 Vec.getOperand(0), Idx); 10462 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10463 Vec.getOperand(1), Idx); 10464 10465 DCI.AddToWorklist(Elt0.getNode()); 10466 DCI.AddToWorklist(Elt1.getNode()); 10467 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 10468 } 10469 } 10470 } 10471 10472 unsigned VecSize = VecVT.getSizeInBits(); 10473 unsigned EltSize = EltVT.getSizeInBits(); 10474 10475 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 10476 if (::shouldExpandVectorDynExt(N)) { 10477 SDLoc SL(N); 10478 SDValue Idx = N->getOperand(1); 10479 SDValue V; 10480 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10481 SDValue IC = DAG.getVectorIdxConstant(I, SL); 10482 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10483 if (I == 0) 10484 V = Elt; 10485 else 10486 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 10487 } 10488 return V; 10489 } 10490 10491 if (!DCI.isBeforeLegalize()) 10492 return SDValue(); 10493 10494 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 10495 // elements. This exposes more load reduction opportunities by replacing 10496 // multiple small extract_vector_elements with a single 32-bit extract. 10497 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10498 if (isa<MemSDNode>(Vec) && 10499 EltSize <= 16 && 10500 EltVT.isByteSized() && 10501 VecSize > 32 && 10502 VecSize % 32 == 0 && 10503 Idx) { 10504 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 10505 10506 unsigned BitIndex = Idx->getZExtValue() * EltSize; 10507 unsigned EltIdx = BitIndex / 32; 10508 unsigned LeftoverBitIdx = BitIndex % 32; 10509 SDLoc SL(N); 10510 10511 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 10512 DCI.AddToWorklist(Cast.getNode()); 10513 10514 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 10515 DAG.getConstant(EltIdx, SL, MVT::i32)); 10516 DCI.AddToWorklist(Elt.getNode()); 10517 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 10518 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 10519 DCI.AddToWorklist(Srl.getNode()); 10520 10521 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 10522 DCI.AddToWorklist(Trunc.getNode()); 10523 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 10524 } 10525 10526 return SDValue(); 10527 } 10528 10529 SDValue 10530 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 10531 DAGCombinerInfo &DCI) const { 10532 SDValue Vec = N->getOperand(0); 10533 SDValue Idx = N->getOperand(2); 10534 EVT VecVT = Vec.getValueType(); 10535 EVT EltVT = VecVT.getVectorElementType(); 10536 10537 // INSERT_VECTOR_ELT (<n x e>, var-idx) 10538 // => BUILD_VECTOR n x select (e, const-idx) 10539 if (!::shouldExpandVectorDynExt(N)) 10540 return SDValue(); 10541 10542 SelectionDAG &DAG = DCI.DAG; 10543 SDLoc SL(N); 10544 SDValue Ins = N->getOperand(1); 10545 EVT IdxVT = Idx.getValueType(); 10546 10547 SmallVector<SDValue, 16> Ops; 10548 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10549 SDValue IC = DAG.getConstant(I, SL, IdxVT); 10550 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10551 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 10552 Ops.push_back(V); 10553 } 10554 10555 return DAG.getBuildVector(VecVT, SL, Ops); 10556 } 10557 10558 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 10559 const SDNode *N0, 10560 const SDNode *N1) const { 10561 EVT VT = N0->getValueType(0); 10562 10563 // Only do this if we are not trying to support denormals. v_mad_f32 does not 10564 // support denormals ever. 10565 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 10566 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 10567 getSubtarget()->hasMadF16())) && 10568 isOperationLegal(ISD::FMAD, VT)) 10569 return ISD::FMAD; 10570 10571 const TargetOptions &Options = DAG.getTarget().Options; 10572 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10573 (N0->getFlags().hasAllowContract() && 10574 N1->getFlags().hasAllowContract())) && 10575 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10576 return ISD::FMA; 10577 } 10578 10579 return 0; 10580 } 10581 10582 // For a reassociatable opcode perform: 10583 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10584 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10585 SelectionDAG &DAG) const { 10586 EVT VT = N->getValueType(0); 10587 if (VT != MVT::i32 && VT != MVT::i64) 10588 return SDValue(); 10589 10590 if (DAG.isBaseWithConstantOffset(SDValue(N, 0))) 10591 return SDValue(); 10592 10593 unsigned Opc = N->getOpcode(); 10594 SDValue Op0 = N->getOperand(0); 10595 SDValue Op1 = N->getOperand(1); 10596 10597 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10598 return SDValue(); 10599 10600 if (Op0->isDivergent()) 10601 std::swap(Op0, Op1); 10602 10603 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10604 return SDValue(); 10605 10606 SDValue Op2 = Op1.getOperand(1); 10607 Op1 = Op1.getOperand(0); 10608 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10609 return SDValue(); 10610 10611 if (Op1->isDivergent()) 10612 std::swap(Op1, Op2); 10613 10614 SDLoc SL(N); 10615 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10616 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10617 } 10618 10619 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10620 EVT VT, 10621 SDValue N0, SDValue N1, SDValue N2, 10622 bool Signed) { 10623 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10624 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10625 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10626 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10627 } 10628 10629 SDValue SITargetLowering::performAddCombine(SDNode *N, 10630 DAGCombinerInfo &DCI) const { 10631 SelectionDAG &DAG = DCI.DAG; 10632 EVT VT = N->getValueType(0); 10633 SDLoc SL(N); 10634 SDValue LHS = N->getOperand(0); 10635 SDValue RHS = N->getOperand(1); 10636 10637 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10638 && Subtarget->hasMad64_32() && 10639 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10640 VT.getScalarSizeInBits() <= 64) { 10641 if (LHS.getOpcode() != ISD::MUL) 10642 std::swap(LHS, RHS); 10643 10644 SDValue MulLHS = LHS.getOperand(0); 10645 SDValue MulRHS = LHS.getOperand(1); 10646 SDValue AddRHS = RHS; 10647 10648 // TODO: Maybe restrict if SGPR inputs. 10649 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10650 numBitsUnsigned(MulRHS, DAG) <= 32) { 10651 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10652 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10653 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10654 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10655 } 10656 10657 if (numBitsSigned(MulLHS, DAG) <= 32 && numBitsSigned(MulRHS, DAG) <= 32) { 10658 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10659 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10660 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10661 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10662 } 10663 10664 return SDValue(); 10665 } 10666 10667 if (SDValue V = reassociateScalarOps(N, DAG)) { 10668 return V; 10669 } 10670 10671 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10672 return SDValue(); 10673 10674 // add x, zext (setcc) => addcarry x, 0, setcc 10675 // add x, sext (setcc) => subcarry x, 0, setcc 10676 unsigned Opc = LHS.getOpcode(); 10677 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10678 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10679 std::swap(RHS, LHS); 10680 10681 Opc = RHS.getOpcode(); 10682 switch (Opc) { 10683 default: break; 10684 case ISD::ZERO_EXTEND: 10685 case ISD::SIGN_EXTEND: 10686 case ISD::ANY_EXTEND: { 10687 auto Cond = RHS.getOperand(0); 10688 // If this won't be a real VOPC output, we would still need to insert an 10689 // extra instruction anyway. 10690 if (!isBoolSGPR(Cond)) 10691 break; 10692 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10693 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10694 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10695 return DAG.getNode(Opc, SL, VTList, Args); 10696 } 10697 case ISD::ADDCARRY: { 10698 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10699 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10700 if (!C || C->getZExtValue() != 0) break; 10701 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10702 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10703 } 10704 } 10705 return SDValue(); 10706 } 10707 10708 SDValue SITargetLowering::performSubCombine(SDNode *N, 10709 DAGCombinerInfo &DCI) const { 10710 SelectionDAG &DAG = DCI.DAG; 10711 EVT VT = N->getValueType(0); 10712 10713 if (VT != MVT::i32) 10714 return SDValue(); 10715 10716 SDLoc SL(N); 10717 SDValue LHS = N->getOperand(0); 10718 SDValue RHS = N->getOperand(1); 10719 10720 // sub x, zext (setcc) => subcarry x, 0, setcc 10721 // sub x, sext (setcc) => addcarry x, 0, setcc 10722 unsigned Opc = RHS.getOpcode(); 10723 switch (Opc) { 10724 default: break; 10725 case ISD::ZERO_EXTEND: 10726 case ISD::SIGN_EXTEND: 10727 case ISD::ANY_EXTEND: { 10728 auto Cond = RHS.getOperand(0); 10729 // If this won't be a real VOPC output, we would still need to insert an 10730 // extra instruction anyway. 10731 if (!isBoolSGPR(Cond)) 10732 break; 10733 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10734 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10735 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10736 return DAG.getNode(Opc, SL, VTList, Args); 10737 } 10738 } 10739 10740 if (LHS.getOpcode() == ISD::SUBCARRY) { 10741 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10742 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10743 if (!C || !C->isZero()) 10744 return SDValue(); 10745 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10746 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10747 } 10748 return SDValue(); 10749 } 10750 10751 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10752 DAGCombinerInfo &DCI) const { 10753 10754 if (N->getValueType(0) != MVT::i32) 10755 return SDValue(); 10756 10757 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10758 if (!C || C->getZExtValue() != 0) 10759 return SDValue(); 10760 10761 SelectionDAG &DAG = DCI.DAG; 10762 SDValue LHS = N->getOperand(0); 10763 10764 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10765 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10766 unsigned LHSOpc = LHS.getOpcode(); 10767 unsigned Opc = N->getOpcode(); 10768 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10769 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10770 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10771 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10772 } 10773 return SDValue(); 10774 } 10775 10776 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10777 DAGCombinerInfo &DCI) const { 10778 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10779 return SDValue(); 10780 10781 SelectionDAG &DAG = DCI.DAG; 10782 EVT VT = N->getValueType(0); 10783 10784 SDLoc SL(N); 10785 SDValue LHS = N->getOperand(0); 10786 SDValue RHS = N->getOperand(1); 10787 10788 // These should really be instruction patterns, but writing patterns with 10789 // source modiifiers is a pain. 10790 10791 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10792 if (LHS.getOpcode() == ISD::FADD) { 10793 SDValue A = LHS.getOperand(0); 10794 if (A == LHS.getOperand(1)) { 10795 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10796 if (FusedOp != 0) { 10797 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10798 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10799 } 10800 } 10801 } 10802 10803 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10804 if (RHS.getOpcode() == ISD::FADD) { 10805 SDValue A = RHS.getOperand(0); 10806 if (A == RHS.getOperand(1)) { 10807 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10808 if (FusedOp != 0) { 10809 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10810 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10811 } 10812 } 10813 } 10814 10815 return SDValue(); 10816 } 10817 10818 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10819 DAGCombinerInfo &DCI) const { 10820 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10821 return SDValue(); 10822 10823 SelectionDAG &DAG = DCI.DAG; 10824 SDLoc SL(N); 10825 EVT VT = N->getValueType(0); 10826 assert(!VT.isVector()); 10827 10828 // Try to get the fneg to fold into the source modifier. This undoes generic 10829 // DAG combines and folds them into the mad. 10830 // 10831 // Only do this if we are not trying to support denormals. v_mad_f32 does 10832 // not support denormals ever. 10833 SDValue LHS = N->getOperand(0); 10834 SDValue RHS = N->getOperand(1); 10835 if (LHS.getOpcode() == ISD::FADD) { 10836 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10837 SDValue A = LHS.getOperand(0); 10838 if (A == LHS.getOperand(1)) { 10839 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10840 if (FusedOp != 0){ 10841 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10842 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10843 10844 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10845 } 10846 } 10847 } 10848 10849 if (RHS.getOpcode() == ISD::FADD) { 10850 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10851 10852 SDValue A = RHS.getOperand(0); 10853 if (A == RHS.getOperand(1)) { 10854 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10855 if (FusedOp != 0){ 10856 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10857 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10858 } 10859 } 10860 } 10861 10862 return SDValue(); 10863 } 10864 10865 SDValue SITargetLowering::performFMACombine(SDNode *N, 10866 DAGCombinerInfo &DCI) const { 10867 SelectionDAG &DAG = DCI.DAG; 10868 EVT VT = N->getValueType(0); 10869 SDLoc SL(N); 10870 10871 if (!Subtarget->hasDot7Insts() || VT != MVT::f32) 10872 return SDValue(); 10873 10874 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10875 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10876 SDValue Op1 = N->getOperand(0); 10877 SDValue Op2 = N->getOperand(1); 10878 SDValue FMA = N->getOperand(2); 10879 10880 if (FMA.getOpcode() != ISD::FMA || 10881 Op1.getOpcode() != ISD::FP_EXTEND || 10882 Op2.getOpcode() != ISD::FP_EXTEND) 10883 return SDValue(); 10884 10885 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10886 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10887 // is sufficient to allow generaing fdot2. 10888 const TargetOptions &Options = DAG.getTarget().Options; 10889 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10890 (N->getFlags().hasAllowContract() && 10891 FMA->getFlags().hasAllowContract())) { 10892 Op1 = Op1.getOperand(0); 10893 Op2 = Op2.getOperand(0); 10894 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10895 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10896 return SDValue(); 10897 10898 SDValue Vec1 = Op1.getOperand(0); 10899 SDValue Idx1 = Op1.getOperand(1); 10900 SDValue Vec2 = Op2.getOperand(0); 10901 10902 SDValue FMAOp1 = FMA.getOperand(0); 10903 SDValue FMAOp2 = FMA.getOperand(1); 10904 SDValue FMAAcc = FMA.getOperand(2); 10905 10906 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10907 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10908 return SDValue(); 10909 10910 FMAOp1 = FMAOp1.getOperand(0); 10911 FMAOp2 = FMAOp2.getOperand(0); 10912 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10913 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10914 return SDValue(); 10915 10916 SDValue Vec3 = FMAOp1.getOperand(0); 10917 SDValue Vec4 = FMAOp2.getOperand(0); 10918 SDValue Idx2 = FMAOp1.getOperand(1); 10919 10920 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10921 // Idx1 and Idx2 cannot be the same. 10922 Idx1 == Idx2) 10923 return SDValue(); 10924 10925 if (Vec1 == Vec2 || Vec3 == Vec4) 10926 return SDValue(); 10927 10928 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10929 return SDValue(); 10930 10931 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10932 (Vec1 == Vec4 && Vec2 == Vec3)) { 10933 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10934 DAG.getTargetConstant(0, SL, MVT::i1)); 10935 } 10936 } 10937 return SDValue(); 10938 } 10939 10940 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10941 DAGCombinerInfo &DCI) const { 10942 SelectionDAG &DAG = DCI.DAG; 10943 SDLoc SL(N); 10944 10945 SDValue LHS = N->getOperand(0); 10946 SDValue RHS = N->getOperand(1); 10947 EVT VT = LHS.getValueType(); 10948 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10949 10950 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10951 if (!CRHS) { 10952 CRHS = dyn_cast<ConstantSDNode>(LHS); 10953 if (CRHS) { 10954 std::swap(LHS, RHS); 10955 CC = getSetCCSwappedOperands(CC); 10956 } 10957 } 10958 10959 if (CRHS) { 10960 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10961 isBoolSGPR(LHS.getOperand(0))) { 10962 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10963 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10964 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10965 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10966 if ((CRHS->isAllOnes() && 10967 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10968 (CRHS->isZero() && 10969 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10970 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10971 DAG.getConstant(-1, SL, MVT::i1)); 10972 if ((CRHS->isAllOnes() && 10973 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10974 (CRHS->isZero() && 10975 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10976 return LHS.getOperand(0); 10977 } 10978 10979 const APInt &CRHSVal = CRHS->getAPIntValue(); 10980 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10981 LHS.getOpcode() == ISD::SELECT && 10982 isa<ConstantSDNode>(LHS.getOperand(1)) && 10983 isa<ConstantSDNode>(LHS.getOperand(2)) && 10984 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10985 isBoolSGPR(LHS.getOperand(0))) { 10986 // Given CT != FT: 10987 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10988 // setcc (select cc, CT, CF), CF, ne => cc 10989 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10990 // setcc (select cc, CT, CF), CT, eq => cc 10991 const APInt &CT = LHS.getConstantOperandAPInt(1); 10992 const APInt &CF = LHS.getConstantOperandAPInt(2); 10993 10994 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10995 (CT == CRHSVal && CC == ISD::SETNE)) 10996 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10997 DAG.getConstant(-1, SL, MVT::i1)); 10998 if ((CF == CRHSVal && CC == ISD::SETNE) || 10999 (CT == CRHSVal && CC == ISD::SETEQ)) 11000 return LHS.getOperand(0); 11001 } 11002 } 11003 11004 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 11005 VT != MVT::f16)) 11006 return SDValue(); 11007 11008 // Match isinf/isfinite pattern 11009 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 11010 // (fcmp one (fabs x), inf) -> (fp_class x, 11011 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 11012 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 11013 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 11014 if (!CRHS) 11015 return SDValue(); 11016 11017 const APFloat &APF = CRHS->getValueAPF(); 11018 if (APF.isInfinity() && !APF.isNegative()) { 11019 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 11020 SIInstrFlags::N_INFINITY; 11021 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 11022 SIInstrFlags::P_ZERO | 11023 SIInstrFlags::N_NORMAL | 11024 SIInstrFlags::P_NORMAL | 11025 SIInstrFlags::N_SUBNORMAL | 11026 SIInstrFlags::P_SUBNORMAL; 11027 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 11028 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 11029 DAG.getConstant(Mask, SL, MVT::i32)); 11030 } 11031 } 11032 11033 return SDValue(); 11034 } 11035 11036 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 11037 DAGCombinerInfo &DCI) const { 11038 SelectionDAG &DAG = DCI.DAG; 11039 SDLoc SL(N); 11040 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 11041 11042 SDValue Src = N->getOperand(0); 11043 SDValue Shift = N->getOperand(0); 11044 11045 // TODO: Extend type shouldn't matter (assuming legal types). 11046 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 11047 Shift = Shift.getOperand(0); 11048 11049 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 11050 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 11051 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 11052 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 11053 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 11054 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 11055 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 11056 SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0), 11057 SDLoc(Shift.getOperand(0)), MVT::i32); 11058 11059 unsigned ShiftOffset = 8 * Offset; 11060 if (Shift.getOpcode() == ISD::SHL) 11061 ShiftOffset -= C->getZExtValue(); 11062 else 11063 ShiftOffset += C->getZExtValue(); 11064 11065 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 11066 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 11067 MVT::f32, Shifted); 11068 } 11069 } 11070 } 11071 11072 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11073 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 11074 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 11075 // We simplified Src. If this node is not dead, visit it again so it is 11076 // folded properly. 11077 if (N->getOpcode() != ISD::DELETED_NODE) 11078 DCI.AddToWorklist(N); 11079 return SDValue(N, 0); 11080 } 11081 11082 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 11083 if (SDValue DemandedSrc = 11084 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 11085 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 11086 11087 return SDValue(); 11088 } 11089 11090 SDValue SITargetLowering::performClampCombine(SDNode *N, 11091 DAGCombinerInfo &DCI) const { 11092 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 11093 if (!CSrc) 11094 return SDValue(); 11095 11096 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 11097 const APFloat &F = CSrc->getValueAPF(); 11098 APFloat Zero = APFloat::getZero(F.getSemantics()); 11099 if (F < Zero || 11100 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 11101 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 11102 } 11103 11104 APFloat One(F.getSemantics(), "1.0"); 11105 if (F > One) 11106 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 11107 11108 return SDValue(CSrc, 0); 11109 } 11110 11111 11112 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 11113 DAGCombinerInfo &DCI) const { 11114 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 11115 return SDValue(); 11116 switch (N->getOpcode()) { 11117 case ISD::ADD: 11118 return performAddCombine(N, DCI); 11119 case ISD::SUB: 11120 return performSubCombine(N, DCI); 11121 case ISD::ADDCARRY: 11122 case ISD::SUBCARRY: 11123 return performAddCarrySubCarryCombine(N, DCI); 11124 case ISD::FADD: 11125 return performFAddCombine(N, DCI); 11126 case ISD::FSUB: 11127 return performFSubCombine(N, DCI); 11128 case ISD::SETCC: 11129 return performSetCCCombine(N, DCI); 11130 case ISD::FMAXNUM: 11131 case ISD::FMINNUM: 11132 case ISD::FMAXNUM_IEEE: 11133 case ISD::FMINNUM_IEEE: 11134 case ISD::SMAX: 11135 case ISD::SMIN: 11136 case ISD::UMAX: 11137 case ISD::UMIN: 11138 case AMDGPUISD::FMIN_LEGACY: 11139 case AMDGPUISD::FMAX_LEGACY: 11140 return performMinMaxCombine(N, DCI); 11141 case ISD::FMA: 11142 return performFMACombine(N, DCI); 11143 case ISD::AND: 11144 return performAndCombine(N, DCI); 11145 case ISD::OR: 11146 return performOrCombine(N, DCI); 11147 case ISD::XOR: 11148 return performXorCombine(N, DCI); 11149 case ISD::ZERO_EXTEND: 11150 return performZeroExtendCombine(N, DCI); 11151 case ISD::SIGN_EXTEND_INREG: 11152 return performSignExtendInRegCombine(N , DCI); 11153 case AMDGPUISD::FP_CLASS: 11154 return performClassCombine(N, DCI); 11155 case ISD::FCANONICALIZE: 11156 return performFCanonicalizeCombine(N, DCI); 11157 case AMDGPUISD::RCP: 11158 return performRcpCombine(N, DCI); 11159 case AMDGPUISD::FRACT: 11160 case AMDGPUISD::RSQ: 11161 case AMDGPUISD::RCP_LEGACY: 11162 case AMDGPUISD::RCP_IFLAG: 11163 case AMDGPUISD::RSQ_CLAMP: 11164 case AMDGPUISD::LDEXP: { 11165 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 11166 SDValue Src = N->getOperand(0); 11167 if (Src.isUndef()) 11168 return Src; 11169 break; 11170 } 11171 case ISD::SINT_TO_FP: 11172 case ISD::UINT_TO_FP: 11173 return performUCharToFloatCombine(N, DCI); 11174 case AMDGPUISD::CVT_F32_UBYTE0: 11175 case AMDGPUISD::CVT_F32_UBYTE1: 11176 case AMDGPUISD::CVT_F32_UBYTE2: 11177 case AMDGPUISD::CVT_F32_UBYTE3: 11178 return performCvtF32UByteNCombine(N, DCI); 11179 case AMDGPUISD::FMED3: 11180 return performFMed3Combine(N, DCI); 11181 case AMDGPUISD::CVT_PKRTZ_F16_F32: 11182 return performCvtPkRTZCombine(N, DCI); 11183 case AMDGPUISD::CLAMP: 11184 return performClampCombine(N, DCI); 11185 case ISD::SCALAR_TO_VECTOR: { 11186 SelectionDAG &DAG = DCI.DAG; 11187 EVT VT = N->getValueType(0); 11188 11189 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 11190 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 11191 SDLoc SL(N); 11192 SDValue Src = N->getOperand(0); 11193 EVT EltVT = Src.getValueType(); 11194 if (EltVT == MVT::f16) 11195 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 11196 11197 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 11198 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 11199 } 11200 11201 break; 11202 } 11203 case ISD::EXTRACT_VECTOR_ELT: 11204 return performExtractVectorEltCombine(N, DCI); 11205 case ISD::INSERT_VECTOR_ELT: 11206 return performInsertVectorEltCombine(N, DCI); 11207 case ISD::LOAD: { 11208 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 11209 return Widended; 11210 LLVM_FALLTHROUGH; 11211 } 11212 default: { 11213 if (!DCI.isBeforeLegalize()) { 11214 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 11215 return performMemSDNodeCombine(MemNode, DCI); 11216 } 11217 11218 break; 11219 } 11220 } 11221 11222 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 11223 } 11224 11225 /// Helper function for adjustWritemask 11226 static unsigned SubIdx2Lane(unsigned Idx) { 11227 switch (Idx) { 11228 default: return ~0u; 11229 case AMDGPU::sub0: return 0; 11230 case AMDGPU::sub1: return 1; 11231 case AMDGPU::sub2: return 2; 11232 case AMDGPU::sub3: return 3; 11233 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 11234 } 11235 } 11236 11237 /// Adjust the writemask of MIMG instructions 11238 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 11239 SelectionDAG &DAG) const { 11240 unsigned Opcode = Node->getMachineOpcode(); 11241 11242 // Subtract 1 because the vdata output is not a MachineSDNode operand. 11243 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 11244 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 11245 return Node; // not implemented for D16 11246 11247 SDNode *Users[5] = { nullptr }; 11248 unsigned Lane = 0; 11249 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 11250 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 11251 unsigned NewDmask = 0; 11252 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 11253 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 11254 bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) || 11255 Node->getConstantOperandVal(LWEIdx)) 11256 ? true 11257 : false; 11258 unsigned TFCLane = 0; 11259 bool HasChain = Node->getNumValues() > 1; 11260 11261 if (OldDmask == 0) { 11262 // These are folded out, but on the chance it happens don't assert. 11263 return Node; 11264 } 11265 11266 unsigned OldBitsSet = countPopulation(OldDmask); 11267 // Work out which is the TFE/LWE lane if that is enabled. 11268 if (UsesTFC) { 11269 TFCLane = OldBitsSet; 11270 } 11271 11272 // Try to figure out the used register components 11273 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 11274 I != E; ++I) { 11275 11276 // Don't look at users of the chain. 11277 if (I.getUse().getResNo() != 0) 11278 continue; 11279 11280 // Abort if we can't understand the usage 11281 if (!I->isMachineOpcode() || 11282 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 11283 return Node; 11284 11285 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 11286 // Note that subregs are packed, i.e. Lane==0 is the first bit set 11287 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 11288 // set, etc. 11289 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 11290 if (Lane == ~0u) 11291 return Node; 11292 11293 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 11294 if (UsesTFC && Lane == TFCLane) { 11295 Users[Lane] = *I; 11296 } else { 11297 // Set which texture component corresponds to the lane. 11298 unsigned Comp; 11299 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 11300 Comp = countTrailingZeros(Dmask); 11301 Dmask &= ~(1 << Comp); 11302 } 11303 11304 // Abort if we have more than one user per component. 11305 if (Users[Lane]) 11306 return Node; 11307 11308 Users[Lane] = *I; 11309 NewDmask |= 1 << Comp; 11310 } 11311 } 11312 11313 // Don't allow 0 dmask, as hardware assumes one channel enabled. 11314 bool NoChannels = !NewDmask; 11315 if (NoChannels) { 11316 if (!UsesTFC) { 11317 // No uses of the result and not using TFC. Then do nothing. 11318 return Node; 11319 } 11320 // If the original dmask has one channel - then nothing to do 11321 if (OldBitsSet == 1) 11322 return Node; 11323 // Use an arbitrary dmask - required for the instruction to work 11324 NewDmask = 1; 11325 } 11326 // Abort if there's no change 11327 if (NewDmask == OldDmask) 11328 return Node; 11329 11330 unsigned BitsSet = countPopulation(NewDmask); 11331 11332 // Check for TFE or LWE - increase the number of channels by one to account 11333 // for the extra return value 11334 // This will need adjustment for D16 if this is also included in 11335 // adjustWriteMask (this function) but at present D16 are excluded. 11336 unsigned NewChannels = BitsSet + UsesTFC; 11337 11338 int NewOpcode = 11339 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 11340 assert(NewOpcode != -1 && 11341 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 11342 "failed to find equivalent MIMG op"); 11343 11344 // Adjust the writemask in the node 11345 SmallVector<SDValue, 12> Ops; 11346 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 11347 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 11348 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 11349 11350 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 11351 11352 MVT ResultVT = NewChannels == 1 ? 11353 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 11354 NewChannels == 5 ? 8 : NewChannels); 11355 SDVTList NewVTList = HasChain ? 11356 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 11357 11358 11359 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 11360 NewVTList, Ops); 11361 11362 if (HasChain) { 11363 // Update chain. 11364 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 11365 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 11366 } 11367 11368 if (NewChannels == 1) { 11369 assert(Node->hasNUsesOfValue(1, 0)); 11370 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 11371 SDLoc(Node), Users[Lane]->getValueType(0), 11372 SDValue(NewNode, 0)); 11373 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 11374 return nullptr; 11375 } 11376 11377 // Update the users of the node with the new indices 11378 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 11379 SDNode *User = Users[i]; 11380 if (!User) { 11381 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 11382 // Users[0] is still nullptr because channel 0 doesn't really have a use. 11383 if (i || !NoChannels) 11384 continue; 11385 } else { 11386 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 11387 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 11388 } 11389 11390 switch (Idx) { 11391 default: break; 11392 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 11393 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 11394 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 11395 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 11396 } 11397 } 11398 11399 DAG.RemoveDeadNode(Node); 11400 return nullptr; 11401 } 11402 11403 static bool isFrameIndexOp(SDValue Op) { 11404 if (Op.getOpcode() == ISD::AssertZext) 11405 Op = Op.getOperand(0); 11406 11407 return isa<FrameIndexSDNode>(Op); 11408 } 11409 11410 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 11411 /// with frame index operands. 11412 /// LLVM assumes that inputs are to these instructions are registers. 11413 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 11414 SelectionDAG &DAG) const { 11415 if (Node->getOpcode() == ISD::CopyToReg) { 11416 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 11417 SDValue SrcVal = Node->getOperand(2); 11418 11419 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 11420 // to try understanding copies to physical registers. 11421 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 11422 SDLoc SL(Node); 11423 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11424 SDValue VReg = DAG.getRegister( 11425 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 11426 11427 SDNode *Glued = Node->getGluedNode(); 11428 SDValue ToVReg 11429 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 11430 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 11431 SDValue ToResultReg 11432 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 11433 VReg, ToVReg.getValue(1)); 11434 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 11435 DAG.RemoveDeadNode(Node); 11436 return ToResultReg.getNode(); 11437 } 11438 } 11439 11440 SmallVector<SDValue, 8> Ops; 11441 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 11442 if (!isFrameIndexOp(Node->getOperand(i))) { 11443 Ops.push_back(Node->getOperand(i)); 11444 continue; 11445 } 11446 11447 SDLoc DL(Node); 11448 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 11449 Node->getOperand(i).getValueType(), 11450 Node->getOperand(i)), 0)); 11451 } 11452 11453 return DAG.UpdateNodeOperands(Node, Ops); 11454 } 11455 11456 /// Fold the instructions after selecting them. 11457 /// Returns null if users were already updated. 11458 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 11459 SelectionDAG &DAG) const { 11460 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11461 unsigned Opcode = Node->getMachineOpcode(); 11462 11463 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 11464 !TII->isGather4(Opcode) && 11465 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) { 11466 return adjustWritemask(Node, DAG); 11467 } 11468 11469 if (Opcode == AMDGPU::INSERT_SUBREG || 11470 Opcode == AMDGPU::REG_SEQUENCE) { 11471 legalizeTargetIndependentNode(Node, DAG); 11472 return Node; 11473 } 11474 11475 switch (Opcode) { 11476 case AMDGPU::V_DIV_SCALE_F32_e64: 11477 case AMDGPU::V_DIV_SCALE_F64_e64: { 11478 // Satisfy the operand register constraint when one of the inputs is 11479 // undefined. Ordinarily each undef value will have its own implicit_def of 11480 // a vreg, so force these to use a single register. 11481 SDValue Src0 = Node->getOperand(1); 11482 SDValue Src1 = Node->getOperand(3); 11483 SDValue Src2 = Node->getOperand(5); 11484 11485 if ((Src0.isMachineOpcode() && 11486 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 11487 (Src0 == Src1 || Src0 == Src2)) 11488 break; 11489 11490 MVT VT = Src0.getValueType().getSimpleVT(); 11491 const TargetRegisterClass *RC = 11492 getRegClassFor(VT, Src0.getNode()->isDivergent()); 11493 11494 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11495 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 11496 11497 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 11498 UndefReg, Src0, SDValue()); 11499 11500 // src0 must be the same register as src1 or src2, even if the value is 11501 // undefined, so make sure we don't violate this constraint. 11502 if (Src0.isMachineOpcode() && 11503 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 11504 if (Src1.isMachineOpcode() && 11505 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11506 Src0 = Src1; 11507 else if (Src2.isMachineOpcode() && 11508 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11509 Src0 = Src2; 11510 else { 11511 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 11512 Src0 = UndefReg; 11513 Src1 = UndefReg; 11514 } 11515 } else 11516 break; 11517 11518 SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end()); 11519 Ops[1] = Src0; 11520 Ops[3] = Src1; 11521 Ops[5] = Src2; 11522 Ops.push_back(ImpDef.getValue(1)); 11523 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 11524 } 11525 default: 11526 break; 11527 } 11528 11529 return Node; 11530 } 11531 11532 // Any MIMG instructions that use tfe or lwe require an initialization of the 11533 // result register that will be written in the case of a memory access failure. 11534 // The required code is also added to tie this init code to the result of the 11535 // img instruction. 11536 void SITargetLowering::AddIMGInit(MachineInstr &MI) const { 11537 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11538 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 11539 MachineRegisterInfo &MRI = MI.getMF()->getRegInfo(); 11540 MachineBasicBlock &MBB = *MI.getParent(); 11541 11542 MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe); 11543 MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe); 11544 MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16); 11545 11546 if (!TFE && !LWE) // intersect_ray 11547 return; 11548 11549 unsigned TFEVal = TFE ? TFE->getImm() : 0; 11550 unsigned LWEVal = LWE->getImm(); 11551 unsigned D16Val = D16 ? D16->getImm() : 0; 11552 11553 if (!TFEVal && !LWEVal) 11554 return; 11555 11556 // At least one of TFE or LWE are non-zero 11557 // We have to insert a suitable initialization of the result value and 11558 // tie this to the dest of the image instruction. 11559 11560 const DebugLoc &DL = MI.getDebugLoc(); 11561 11562 int DstIdx = 11563 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata); 11564 11565 // Calculate which dword we have to initialize to 0. 11566 MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask); 11567 11568 // check that dmask operand is found. 11569 assert(MO_Dmask && "Expected dmask operand in instruction"); 11570 11571 unsigned dmask = MO_Dmask->getImm(); 11572 // Determine the number of active lanes taking into account the 11573 // Gather4 special case 11574 unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask); 11575 11576 bool Packed = !Subtarget->hasUnpackedD16VMem(); 11577 11578 unsigned InitIdx = 11579 D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1; 11580 11581 // Abandon attempt if the dst size isn't large enough 11582 // - this is in fact an error but this is picked up elsewhere and 11583 // reported correctly. 11584 uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32; 11585 if (DstSize < InitIdx) 11586 return; 11587 11588 // Create a register for the intialization value. 11589 Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11590 unsigned NewDst = 0; // Final initialized value will be in here 11591 11592 // If PRTStrictNull feature is enabled (the default) then initialize 11593 // all the result registers to 0, otherwise just the error indication 11594 // register (VGPRn+1) 11595 unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1; 11596 unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1); 11597 11598 BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst); 11599 for (; SizeLeft; SizeLeft--, CurrIdx++) { 11600 NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11601 // Initialize dword 11602 Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 11603 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg) 11604 .addImm(0); 11605 // Insert into the super-reg 11606 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst) 11607 .addReg(PrevDst) 11608 .addReg(SubReg) 11609 .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx)); 11610 11611 PrevDst = NewDst; 11612 } 11613 11614 // Add as an implicit operand 11615 MI.addOperand(MachineOperand::CreateReg(NewDst, false, true)); 11616 11617 // Tie the just added implicit operand to the dst 11618 MI.tieOperands(DstIdx, MI.getNumOperands() - 1); 11619 } 11620 11621 /// Assign the register class depending on the number of 11622 /// bits set in the writemask 11623 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11624 SDNode *Node) const { 11625 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11626 11627 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 11628 11629 if (TII->isVOP3(MI.getOpcode())) { 11630 // Make sure constant bus requirements are respected. 11631 TII->legalizeOperandsVOP3(MRI, MI); 11632 11633 // Prefer VGPRs over AGPRs in mAI instructions where possible. 11634 // This saves a chain-copy of registers and better ballance register 11635 // use between vgpr and agpr as agpr tuples tend to be big. 11636 if (MI.getDesc().OpInfo) { 11637 unsigned Opc = MI.getOpcode(); 11638 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11639 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 11640 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 11641 if (I == -1) 11642 break; 11643 MachineOperand &Op = MI.getOperand(I); 11644 if (!Op.isReg() || !Op.getReg().isVirtual()) 11645 continue; 11646 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11647 if (!TRI->hasAGPRs(RC)) 11648 continue; 11649 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11650 if (!Src || !Src->isCopy() || 11651 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11652 continue; 11653 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11654 // All uses of agpr64 and agpr32 can also accept vgpr except for 11655 // v_accvgpr_read, but we do not produce agpr reads during selection, 11656 // so no use checks are needed. 11657 MRI.setRegClass(Op.getReg(), NewRC); 11658 } 11659 } 11660 11661 return; 11662 } 11663 11664 // Replace unused atomics with the no return version. 11665 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 11666 if (NoRetAtomicOp != -1) { 11667 if (!Node->hasAnyUseOfValue(0)) { 11668 int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), 11669 AMDGPU::OpName::cpol); 11670 if (CPolIdx != -1) { 11671 MachineOperand &CPol = MI.getOperand(CPolIdx); 11672 CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC); 11673 } 11674 MI.RemoveOperand(0); 11675 MI.setDesc(TII->get(NoRetAtomicOp)); 11676 return; 11677 } 11678 11679 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 11680 // instruction, because the return type of these instructions is a vec2 of 11681 // the memory type, so it can be tied to the input operand. 11682 // This means these instructions always have a use, so we need to add a 11683 // special case to check if the atomic has only one extract_subreg use, 11684 // which itself has no uses. 11685 if ((Node->hasNUsesOfValue(1, 0) && 11686 Node->use_begin()->isMachineOpcode() && 11687 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 11688 !Node->use_begin()->hasAnyUseOfValue(0))) { 11689 Register Def = MI.getOperand(0).getReg(); 11690 11691 // Change this into a noret atomic. 11692 MI.setDesc(TII->get(NoRetAtomicOp)); 11693 MI.RemoveOperand(0); 11694 11695 // If we only remove the def operand from the atomic instruction, the 11696 // extract_subreg will be left with a use of a vreg without a def. 11697 // So we need to insert an implicit_def to avoid machine verifier 11698 // errors. 11699 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 11700 TII->get(AMDGPU::IMPLICIT_DEF), Def); 11701 } 11702 return; 11703 } 11704 11705 if (TII->isMIMG(MI) && !MI.mayStore()) 11706 AddIMGInit(MI); 11707 } 11708 11709 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11710 uint64_t Val) { 11711 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11712 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11713 } 11714 11715 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11716 const SDLoc &DL, 11717 SDValue Ptr) const { 11718 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11719 11720 // Build the half of the subregister with the constants before building the 11721 // full 128-bit register. If we are building multiple resource descriptors, 11722 // this will allow CSEing of the 2-component register. 11723 const SDValue Ops0[] = { 11724 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11725 buildSMovImm32(DAG, DL, 0), 11726 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11727 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11728 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11729 }; 11730 11731 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11732 MVT::v2i32, Ops0), 0); 11733 11734 // Combine the constants and the pointer. 11735 const SDValue Ops1[] = { 11736 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11737 Ptr, 11738 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11739 SubRegHi, 11740 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11741 }; 11742 11743 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11744 } 11745 11746 /// Return a resource descriptor with the 'Add TID' bit enabled 11747 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11748 /// of the resource descriptor) to create an offset, which is added to 11749 /// the resource pointer. 11750 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11751 SDValue Ptr, uint32_t RsrcDword1, 11752 uint64_t RsrcDword2And3) const { 11753 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11754 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11755 if (RsrcDword1) { 11756 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11757 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11758 0); 11759 } 11760 11761 SDValue DataLo = buildSMovImm32(DAG, DL, 11762 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11763 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11764 11765 const SDValue Ops[] = { 11766 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11767 PtrLo, 11768 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11769 PtrHi, 11770 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11771 DataLo, 11772 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11773 DataHi, 11774 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11775 }; 11776 11777 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11778 } 11779 11780 //===----------------------------------------------------------------------===// 11781 // SI Inline Assembly Support 11782 //===----------------------------------------------------------------------===// 11783 11784 std::pair<unsigned, const TargetRegisterClass *> 11785 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_, 11786 StringRef Constraint, 11787 MVT VT) const { 11788 const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_); 11789 11790 const TargetRegisterClass *RC = nullptr; 11791 if (Constraint.size() == 1) { 11792 const unsigned BitWidth = VT.getSizeInBits(); 11793 switch (Constraint[0]) { 11794 default: 11795 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11796 case 's': 11797 case 'r': 11798 switch (BitWidth) { 11799 case 16: 11800 RC = &AMDGPU::SReg_32RegClass; 11801 break; 11802 case 64: 11803 RC = &AMDGPU::SGPR_64RegClass; 11804 break; 11805 default: 11806 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11807 if (!RC) 11808 return std::make_pair(0U, nullptr); 11809 break; 11810 } 11811 break; 11812 case 'v': 11813 switch (BitWidth) { 11814 case 16: 11815 RC = &AMDGPU::VGPR_32RegClass; 11816 break; 11817 default: 11818 RC = TRI->getVGPRClassForBitWidth(BitWidth); 11819 if (!RC) 11820 return std::make_pair(0U, nullptr); 11821 break; 11822 } 11823 break; 11824 case 'a': 11825 if (!Subtarget->hasMAIInsts()) 11826 break; 11827 switch (BitWidth) { 11828 case 16: 11829 RC = &AMDGPU::AGPR_32RegClass; 11830 break; 11831 default: 11832 RC = TRI->getAGPRClassForBitWidth(BitWidth); 11833 if (!RC) 11834 return std::make_pair(0U, nullptr); 11835 break; 11836 } 11837 break; 11838 } 11839 // We actually support i128, i16 and f16 as inline parameters 11840 // even if they are not reported as legal 11841 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11842 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11843 return std::make_pair(0U, RC); 11844 } 11845 11846 if (Constraint.startswith("{") && Constraint.endswith("}")) { 11847 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2); 11848 if (RegName.consume_front("v")) { 11849 RC = &AMDGPU::VGPR_32RegClass; 11850 } else if (RegName.consume_front("s")) { 11851 RC = &AMDGPU::SGPR_32RegClass; 11852 } else if (RegName.consume_front("a")) { 11853 RC = &AMDGPU::AGPR_32RegClass; 11854 } 11855 11856 if (RC) { 11857 uint32_t Idx; 11858 if (RegName.consume_front("[")) { 11859 uint32_t End; 11860 bool Failed = RegName.consumeInteger(10, Idx); 11861 Failed |= !RegName.consume_front(":"); 11862 Failed |= RegName.consumeInteger(10, End); 11863 Failed |= !RegName.consume_back("]"); 11864 if (!Failed) { 11865 uint32_t Width = (End - Idx + 1) * 32; 11866 MCRegister Reg = RC->getRegister(Idx); 11867 if (SIRegisterInfo::isVGPRClass(RC)) 11868 RC = TRI->getVGPRClassForBitWidth(Width); 11869 else if (SIRegisterInfo::isSGPRClass(RC)) 11870 RC = TRI->getSGPRClassForBitWidth(Width); 11871 else if (SIRegisterInfo::isAGPRClass(RC)) 11872 RC = TRI->getAGPRClassForBitWidth(Width); 11873 if (RC) { 11874 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC); 11875 return std::make_pair(Reg, RC); 11876 } 11877 } 11878 } else { 11879 bool Failed = RegName.getAsInteger(10, Idx); 11880 if (!Failed && Idx < RC->getNumRegs()) 11881 return std::make_pair(RC->getRegister(Idx), RC); 11882 } 11883 } 11884 } 11885 11886 auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11887 if (Ret.first) 11888 Ret.second = TRI->getPhysRegClass(Ret.first); 11889 11890 return Ret; 11891 } 11892 11893 static bool isImmConstraint(StringRef Constraint) { 11894 if (Constraint.size() == 1) { 11895 switch (Constraint[0]) { 11896 default: break; 11897 case 'I': 11898 case 'J': 11899 case 'A': 11900 case 'B': 11901 case 'C': 11902 return true; 11903 } 11904 } else if (Constraint == "DA" || 11905 Constraint == "DB") { 11906 return true; 11907 } 11908 return false; 11909 } 11910 11911 SITargetLowering::ConstraintType 11912 SITargetLowering::getConstraintType(StringRef Constraint) const { 11913 if (Constraint.size() == 1) { 11914 switch (Constraint[0]) { 11915 default: break; 11916 case 's': 11917 case 'v': 11918 case 'a': 11919 return C_RegisterClass; 11920 } 11921 } 11922 if (isImmConstraint(Constraint)) { 11923 return C_Other; 11924 } 11925 return TargetLowering::getConstraintType(Constraint); 11926 } 11927 11928 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11929 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11930 Val = Val & maskTrailingOnes<uint64_t>(Size); 11931 } 11932 return Val; 11933 } 11934 11935 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11936 std::string &Constraint, 11937 std::vector<SDValue> &Ops, 11938 SelectionDAG &DAG) const { 11939 if (isImmConstraint(Constraint)) { 11940 uint64_t Val; 11941 if (getAsmOperandConstVal(Op, Val) && 11942 checkAsmConstraintVal(Op, Constraint, Val)) { 11943 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11944 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11945 } 11946 } else { 11947 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11948 } 11949 } 11950 11951 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11952 unsigned Size = Op.getScalarValueSizeInBits(); 11953 if (Size > 64) 11954 return false; 11955 11956 if (Size == 16 && !Subtarget->has16BitInsts()) 11957 return false; 11958 11959 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11960 Val = C->getSExtValue(); 11961 return true; 11962 } 11963 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11964 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11965 return true; 11966 } 11967 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11968 if (Size != 16 || Op.getNumOperands() != 2) 11969 return false; 11970 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11971 return false; 11972 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11973 Val = C->getSExtValue(); 11974 return true; 11975 } 11976 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11977 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11978 return true; 11979 } 11980 } 11981 11982 return false; 11983 } 11984 11985 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 11986 const std::string &Constraint, 11987 uint64_t Val) const { 11988 if (Constraint.size() == 1) { 11989 switch (Constraint[0]) { 11990 case 'I': 11991 return AMDGPU::isInlinableIntLiteral(Val); 11992 case 'J': 11993 return isInt<16>(Val); 11994 case 'A': 11995 return checkAsmConstraintValA(Op, Val); 11996 case 'B': 11997 return isInt<32>(Val); 11998 case 'C': 11999 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 12000 AMDGPU::isInlinableIntLiteral(Val); 12001 default: 12002 break; 12003 } 12004 } else if (Constraint.size() == 2) { 12005 if (Constraint == "DA") { 12006 int64_t HiBits = static_cast<int32_t>(Val >> 32); 12007 int64_t LoBits = static_cast<int32_t>(Val); 12008 return checkAsmConstraintValA(Op, HiBits, 32) && 12009 checkAsmConstraintValA(Op, LoBits, 32); 12010 } 12011 if (Constraint == "DB") { 12012 return true; 12013 } 12014 } 12015 llvm_unreachable("Invalid asm constraint"); 12016 } 12017 12018 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 12019 uint64_t Val, 12020 unsigned MaxSize) const { 12021 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 12022 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 12023 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 12024 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 12025 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 12026 return true; 12027 } 12028 return false; 12029 } 12030 12031 static int getAlignedAGPRClassID(unsigned UnalignedClassID) { 12032 switch (UnalignedClassID) { 12033 case AMDGPU::VReg_64RegClassID: 12034 return AMDGPU::VReg_64_Align2RegClassID; 12035 case AMDGPU::VReg_96RegClassID: 12036 return AMDGPU::VReg_96_Align2RegClassID; 12037 case AMDGPU::VReg_128RegClassID: 12038 return AMDGPU::VReg_128_Align2RegClassID; 12039 case AMDGPU::VReg_160RegClassID: 12040 return AMDGPU::VReg_160_Align2RegClassID; 12041 case AMDGPU::VReg_192RegClassID: 12042 return AMDGPU::VReg_192_Align2RegClassID; 12043 case AMDGPU::VReg_224RegClassID: 12044 return AMDGPU::VReg_224_Align2RegClassID; 12045 case AMDGPU::VReg_256RegClassID: 12046 return AMDGPU::VReg_256_Align2RegClassID; 12047 case AMDGPU::VReg_512RegClassID: 12048 return AMDGPU::VReg_512_Align2RegClassID; 12049 case AMDGPU::VReg_1024RegClassID: 12050 return AMDGPU::VReg_1024_Align2RegClassID; 12051 case AMDGPU::AReg_64RegClassID: 12052 return AMDGPU::AReg_64_Align2RegClassID; 12053 case AMDGPU::AReg_96RegClassID: 12054 return AMDGPU::AReg_96_Align2RegClassID; 12055 case AMDGPU::AReg_128RegClassID: 12056 return AMDGPU::AReg_128_Align2RegClassID; 12057 case AMDGPU::AReg_160RegClassID: 12058 return AMDGPU::AReg_160_Align2RegClassID; 12059 case AMDGPU::AReg_192RegClassID: 12060 return AMDGPU::AReg_192_Align2RegClassID; 12061 case AMDGPU::AReg_256RegClassID: 12062 return AMDGPU::AReg_256_Align2RegClassID; 12063 case AMDGPU::AReg_512RegClassID: 12064 return AMDGPU::AReg_512_Align2RegClassID; 12065 case AMDGPU::AReg_1024RegClassID: 12066 return AMDGPU::AReg_1024_Align2RegClassID; 12067 default: 12068 return -1; 12069 } 12070 } 12071 12072 // Figure out which registers should be reserved for stack access. Only after 12073 // the function is legalized do we know all of the non-spill stack objects or if 12074 // calls are present. 12075 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 12076 MachineRegisterInfo &MRI = MF.getRegInfo(); 12077 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 12078 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 12079 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12080 const SIInstrInfo *TII = ST.getInstrInfo(); 12081 12082 if (Info->isEntryFunction()) { 12083 // Callable functions have fixed registers used for stack access. 12084 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 12085 } 12086 12087 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 12088 Info->getStackPtrOffsetReg())); 12089 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 12090 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 12091 12092 // We need to worry about replacing the default register with itself in case 12093 // of MIR testcases missing the MFI. 12094 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 12095 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 12096 12097 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 12098 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 12099 12100 Info->limitOccupancy(MF); 12101 12102 if (ST.isWave32() && !MF.empty()) { 12103 for (auto &MBB : MF) { 12104 for (auto &MI : MBB) { 12105 TII->fixImplicitOperands(MI); 12106 } 12107 } 12108 } 12109 12110 // FIXME: This is a hack to fixup AGPR classes to use the properly aligned 12111 // classes if required. Ideally the register class constraints would differ 12112 // per-subtarget, but there's no easy way to achieve that right now. This is 12113 // not a problem for VGPRs because the correctly aligned VGPR class is implied 12114 // from using them as the register class for legal types. 12115 if (ST.needsAlignedVGPRs()) { 12116 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) { 12117 const Register Reg = Register::index2VirtReg(I); 12118 const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg); 12119 if (!RC) 12120 continue; 12121 int NewClassID = getAlignedAGPRClassID(RC->getID()); 12122 if (NewClassID != -1) 12123 MRI.setRegClass(Reg, TRI->getRegClass(NewClassID)); 12124 } 12125 } 12126 12127 TargetLoweringBase::finalizeLowering(MF); 12128 } 12129 12130 void SITargetLowering::computeKnownBitsForFrameIndex( 12131 const int FI, KnownBits &Known, const MachineFunction &MF) const { 12132 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 12133 12134 // Set the high bits to zero based on the maximum allowed scratch size per 12135 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 12136 // calculation won't overflow, so assume the sign bit is never set. 12137 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 12138 } 12139 12140 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 12141 KnownBits &Known, unsigned Dim) { 12142 unsigned MaxValue = 12143 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 12144 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 12145 } 12146 12147 void SITargetLowering::computeKnownBitsForTargetInstr( 12148 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 12149 const MachineRegisterInfo &MRI, unsigned Depth) const { 12150 const MachineInstr *MI = MRI.getVRegDef(R); 12151 switch (MI->getOpcode()) { 12152 case AMDGPU::G_INTRINSIC: { 12153 switch (MI->getIntrinsicID()) { 12154 case Intrinsic::amdgcn_workitem_id_x: 12155 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 12156 break; 12157 case Intrinsic::amdgcn_workitem_id_y: 12158 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 12159 break; 12160 case Intrinsic::amdgcn_workitem_id_z: 12161 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 12162 break; 12163 case Intrinsic::amdgcn_mbcnt_lo: 12164 case Intrinsic::amdgcn_mbcnt_hi: { 12165 // These return at most the wavefront size - 1. 12166 unsigned Size = MRI.getType(R).getSizeInBits(); 12167 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 12168 break; 12169 } 12170 case Intrinsic::amdgcn_groupstaticsize: { 12171 // We can report everything over the maximum size as 0. We can't report 12172 // based on the actual size because we don't know if it's accurate or not 12173 // at any given point. 12174 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 12175 break; 12176 } 12177 } 12178 break; 12179 } 12180 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE: 12181 Known.Zero.setHighBits(24); 12182 break; 12183 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT: 12184 Known.Zero.setHighBits(16); 12185 break; 12186 } 12187 } 12188 12189 Align SITargetLowering::computeKnownAlignForTargetInstr( 12190 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 12191 unsigned Depth) const { 12192 const MachineInstr *MI = MRI.getVRegDef(R); 12193 switch (MI->getOpcode()) { 12194 case AMDGPU::G_INTRINSIC: 12195 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 12196 // FIXME: Can this move to generic code? What about the case where the call 12197 // site specifies a lower alignment? 12198 Intrinsic::ID IID = MI->getIntrinsicID(); 12199 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 12200 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 12201 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 12202 return *RetAlign; 12203 return Align(1); 12204 } 12205 default: 12206 return Align(1); 12207 } 12208 } 12209 12210 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 12211 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 12212 const Align CacheLineAlign = Align(64); 12213 12214 // Pre-GFX10 target did not benefit from loop alignment 12215 if (!ML || DisableLoopAlignment || 12216 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 12217 getSubtarget()->hasInstFwdPrefetchBug()) 12218 return PrefAlign; 12219 12220 // On GFX10 I$ is 4 x 64 bytes cache lines. 12221 // By default prefetcher keeps one cache line behind and reads two ahead. 12222 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 12223 // behind and one ahead. 12224 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 12225 // If loop fits 64 bytes it always spans no more than two cache lines and 12226 // does not need an alignment. 12227 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 12228 // Else if loop is less or equal 192 bytes we need two lines behind. 12229 12230 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 12231 const MachineBasicBlock *Header = ML->getHeader(); 12232 if (Header->getAlignment() != PrefAlign) 12233 return Header->getAlignment(); // Already processed. 12234 12235 unsigned LoopSize = 0; 12236 for (const MachineBasicBlock *MBB : ML->blocks()) { 12237 // If inner loop block is aligned assume in average half of the alignment 12238 // size to be added as nops. 12239 if (MBB != Header) 12240 LoopSize += MBB->getAlignment().value() / 2; 12241 12242 for (const MachineInstr &MI : *MBB) { 12243 LoopSize += TII->getInstSizeInBytes(MI); 12244 if (LoopSize > 192) 12245 return PrefAlign; 12246 } 12247 } 12248 12249 if (LoopSize <= 64) 12250 return PrefAlign; 12251 12252 if (LoopSize <= 128) 12253 return CacheLineAlign; 12254 12255 // If any of parent loops is surrounded by prefetch instructions do not 12256 // insert new for inner loop, which would reset parent's settings. 12257 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 12258 if (MachineBasicBlock *Exit = P->getExitBlock()) { 12259 auto I = Exit->getFirstNonDebugInstr(); 12260 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 12261 return CacheLineAlign; 12262 } 12263 } 12264 12265 MachineBasicBlock *Pre = ML->getLoopPreheader(); 12266 MachineBasicBlock *Exit = ML->getExitBlock(); 12267 12268 if (Pre && Exit) { 12269 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 12270 TII->get(AMDGPU::S_INST_PREFETCH)) 12271 .addImm(1); // prefetch 2 lines behind PC 12272 12273 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 12274 TII->get(AMDGPU::S_INST_PREFETCH)) 12275 .addImm(2); // prefetch 1 line behind PC 12276 } 12277 12278 return CacheLineAlign; 12279 } 12280 12281 LLVM_ATTRIBUTE_UNUSED 12282 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 12283 assert(N->getOpcode() == ISD::CopyFromReg); 12284 do { 12285 // Follow the chain until we find an INLINEASM node. 12286 N = N->getOperand(0).getNode(); 12287 if (N->getOpcode() == ISD::INLINEASM || 12288 N->getOpcode() == ISD::INLINEASM_BR) 12289 return true; 12290 } while (N->getOpcode() == ISD::CopyFromReg); 12291 return false; 12292 } 12293 12294 bool SITargetLowering::isSDNodeSourceOfDivergence( 12295 const SDNode *N, FunctionLoweringInfo *FLI, 12296 LegacyDivergenceAnalysis *KDA) const { 12297 switch (N->getOpcode()) { 12298 case ISD::CopyFromReg: { 12299 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 12300 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 12301 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12302 Register Reg = R->getReg(); 12303 12304 // FIXME: Why does this need to consider isLiveIn? 12305 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 12306 return !TRI->isSGPRReg(MRI, Reg); 12307 12308 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 12309 return KDA->isDivergent(V); 12310 12311 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 12312 return !TRI->isSGPRReg(MRI, Reg); 12313 } 12314 case ISD::LOAD: { 12315 const LoadSDNode *L = cast<LoadSDNode>(N); 12316 unsigned AS = L->getAddressSpace(); 12317 // A flat load may access private memory. 12318 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 12319 } 12320 case ISD::CALLSEQ_END: 12321 return true; 12322 case ISD::INTRINSIC_WO_CHAIN: 12323 return AMDGPU::isIntrinsicSourceOfDivergence( 12324 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 12325 case ISD::INTRINSIC_W_CHAIN: 12326 return AMDGPU::isIntrinsicSourceOfDivergence( 12327 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 12328 case AMDGPUISD::ATOMIC_CMP_SWAP: 12329 case AMDGPUISD::ATOMIC_INC: 12330 case AMDGPUISD::ATOMIC_DEC: 12331 case AMDGPUISD::ATOMIC_LOAD_FMIN: 12332 case AMDGPUISD::ATOMIC_LOAD_FMAX: 12333 case AMDGPUISD::BUFFER_ATOMIC_SWAP: 12334 case AMDGPUISD::BUFFER_ATOMIC_ADD: 12335 case AMDGPUISD::BUFFER_ATOMIC_SUB: 12336 case AMDGPUISD::BUFFER_ATOMIC_SMIN: 12337 case AMDGPUISD::BUFFER_ATOMIC_UMIN: 12338 case AMDGPUISD::BUFFER_ATOMIC_SMAX: 12339 case AMDGPUISD::BUFFER_ATOMIC_UMAX: 12340 case AMDGPUISD::BUFFER_ATOMIC_AND: 12341 case AMDGPUISD::BUFFER_ATOMIC_OR: 12342 case AMDGPUISD::BUFFER_ATOMIC_XOR: 12343 case AMDGPUISD::BUFFER_ATOMIC_INC: 12344 case AMDGPUISD::BUFFER_ATOMIC_DEC: 12345 case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP: 12346 case AMDGPUISD::BUFFER_ATOMIC_CSUB: 12347 case AMDGPUISD::BUFFER_ATOMIC_FADD: 12348 case AMDGPUISD::BUFFER_ATOMIC_FMIN: 12349 case AMDGPUISD::BUFFER_ATOMIC_FMAX: 12350 // Target-specific read-modify-write atomics are sources of divergence. 12351 return true; 12352 default: 12353 if (auto *A = dyn_cast<AtomicSDNode>(N)) { 12354 // Generic read-modify-write atomics are sources of divergence. 12355 return A->readMem() && A->writeMem(); 12356 } 12357 return false; 12358 } 12359 } 12360 12361 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 12362 EVT VT) const { 12363 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 12364 case MVT::f32: 12365 return hasFP32Denormals(DAG.getMachineFunction()); 12366 case MVT::f64: 12367 case MVT::f16: 12368 return hasFP64FP16Denormals(DAG.getMachineFunction()); 12369 default: 12370 return false; 12371 } 12372 } 12373 12374 bool SITargetLowering::denormalsEnabledForType(LLT Ty, 12375 MachineFunction &MF) const { 12376 switch (Ty.getScalarSizeInBits()) { 12377 case 32: 12378 return hasFP32Denormals(MF); 12379 case 64: 12380 case 16: 12381 return hasFP64FP16Denormals(MF); 12382 default: 12383 return false; 12384 } 12385 } 12386 12387 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 12388 const SelectionDAG &DAG, 12389 bool SNaN, 12390 unsigned Depth) const { 12391 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 12392 const MachineFunction &MF = DAG.getMachineFunction(); 12393 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 12394 12395 if (Info->getMode().DX10Clamp) 12396 return true; // Clamped to 0. 12397 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 12398 } 12399 12400 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 12401 SNaN, Depth); 12402 } 12403 12404 // Global FP atomic instructions have a hardcoded FP mode and do not support 12405 // FP32 denormals, and only support v2f16 denormals. 12406 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) { 12407 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics(); 12408 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt); 12409 if (&Flt == &APFloat::IEEEsingle()) 12410 return DenormMode == DenormalMode::getPreserveSign(); 12411 return DenormMode == DenormalMode::getIEEE(); 12412 } 12413 12414 TargetLowering::AtomicExpansionKind 12415 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 12416 12417 auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) { 12418 OptimizationRemarkEmitter ORE(RMW->getFunction()); 12419 LLVMContext &Ctx = RMW->getFunction()->getContext(); 12420 SmallVector<StringRef> SSNs; 12421 Ctx.getSyncScopeNames(SSNs); 12422 auto MemScope = SSNs[RMW->getSyncScopeID()].empty() 12423 ? "system" 12424 : SSNs[RMW->getSyncScopeID()]; 12425 ORE.emit([&]() { 12426 return OptimizationRemark(DEBUG_TYPE, "Passed", RMW) 12427 << "Hardware instruction generated for atomic " 12428 << RMW->getOperationName(RMW->getOperation()) 12429 << " operation at memory scope " << MemScope 12430 << " due to an unsafe request."; 12431 }); 12432 return Kind; 12433 }; 12434 12435 switch (RMW->getOperation()) { 12436 case AtomicRMWInst::FAdd: { 12437 Type *Ty = RMW->getType(); 12438 12439 // We don't have a way to support 16-bit atomics now, so just leave them 12440 // as-is. 12441 if (Ty->isHalfTy()) 12442 return AtomicExpansionKind::None; 12443 12444 if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy())) 12445 return AtomicExpansionKind::CmpXChg; 12446 12447 unsigned AS = RMW->getPointerAddressSpace(); 12448 12449 if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) && 12450 Subtarget->hasAtomicFaddInsts()) { 12451 // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe 12452 // floating point atomic instructions. May generate more efficient code, 12453 // but may not respect rounding and denormal modes, and may give incorrect 12454 // results for certain memory destinations. 12455 if (RMW->getFunction() 12456 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12457 .getValueAsString() != "true") 12458 return AtomicExpansionKind::CmpXChg; 12459 12460 if (Subtarget->hasGFX90AInsts()) { 12461 if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS) 12462 return AtomicExpansionKind::CmpXChg; 12463 12464 auto SSID = RMW->getSyncScopeID(); 12465 if (SSID == SyncScope::System || 12466 SSID == RMW->getContext().getOrInsertSyncScopeID("one-as")) 12467 return AtomicExpansionKind::CmpXChg; 12468 12469 return ReportUnsafeHWInst(AtomicExpansionKind::None); 12470 } 12471 12472 if (AS == AMDGPUAS::FLAT_ADDRESS) 12473 return AtomicExpansionKind::CmpXChg; 12474 12475 return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None) 12476 : AtomicExpansionKind::CmpXChg; 12477 } 12478 12479 // DS FP atomics do repect the denormal mode, but the rounding mode is fixed 12480 // to round-to-nearest-even. 12481 // The only exception is DS_ADD_F64 which never flushes regardless of mode. 12482 if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) { 12483 if (!Ty->isDoubleTy()) 12484 return AtomicExpansionKind::None; 12485 12486 if (fpModeMatchesGlobalFPAtomicMode(RMW)) 12487 return AtomicExpansionKind::None; 12488 12489 return RMW->getFunction() 12490 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12491 .getValueAsString() == "true" 12492 ? ReportUnsafeHWInst(AtomicExpansionKind::None) 12493 : AtomicExpansionKind::CmpXChg; 12494 } 12495 12496 return AtomicExpansionKind::CmpXChg; 12497 } 12498 default: 12499 break; 12500 } 12501 12502 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 12503 } 12504 12505 const TargetRegisterClass * 12506 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 12507 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 12508 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12509 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 12510 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 12511 : &AMDGPU::SReg_32RegClass; 12512 if (!TRI->isSGPRClass(RC) && !isDivergent) 12513 return TRI->getEquivalentSGPRClass(RC); 12514 else if (TRI->isSGPRClass(RC) && isDivergent) 12515 return TRI->getEquivalentVGPRClass(RC); 12516 12517 return RC; 12518 } 12519 12520 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 12521 // uniform values (as produced by the mask results of control flow intrinsics) 12522 // used outside of divergent blocks. The phi users need to also be treated as 12523 // always uniform. 12524 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 12525 unsigned WaveSize) { 12526 // FIXME: We asssume we never cast the mask results of a control flow 12527 // intrinsic. 12528 // Early exit if the type won't be consistent as a compile time hack. 12529 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 12530 if (!IT || IT->getBitWidth() != WaveSize) 12531 return false; 12532 12533 if (!isa<Instruction>(V)) 12534 return false; 12535 if (!Visited.insert(V).second) 12536 return false; 12537 bool Result = false; 12538 for (auto U : V->users()) { 12539 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 12540 if (V == U->getOperand(1)) { 12541 switch (Intrinsic->getIntrinsicID()) { 12542 default: 12543 Result = false; 12544 break; 12545 case Intrinsic::amdgcn_if_break: 12546 case Intrinsic::amdgcn_if: 12547 case Intrinsic::amdgcn_else: 12548 Result = true; 12549 break; 12550 } 12551 } 12552 if (V == U->getOperand(0)) { 12553 switch (Intrinsic->getIntrinsicID()) { 12554 default: 12555 Result = false; 12556 break; 12557 case Intrinsic::amdgcn_end_cf: 12558 case Intrinsic::amdgcn_loop: 12559 Result = true; 12560 break; 12561 } 12562 } 12563 } else { 12564 Result = hasCFUser(U, Visited, WaveSize); 12565 } 12566 if (Result) 12567 break; 12568 } 12569 return Result; 12570 } 12571 12572 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 12573 const Value *V) const { 12574 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 12575 if (CI->isInlineAsm()) { 12576 // FIXME: This cannot give a correct answer. This should only trigger in 12577 // the case where inline asm returns mixed SGPR and VGPR results, used 12578 // outside the defining block. We don't have a specific result to 12579 // consider, so this assumes if any value is SGPR, the overall register 12580 // also needs to be SGPR. 12581 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 12582 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 12583 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 12584 for (auto &TC : TargetConstraints) { 12585 if (TC.Type == InlineAsm::isOutput) { 12586 ComputeConstraintToUse(TC, SDValue()); 12587 const TargetRegisterClass *RC = getRegForInlineAsmConstraint( 12588 SIRI, TC.ConstraintCode, TC.ConstraintVT).second; 12589 if (RC && SIRI->isSGPRClass(RC)) 12590 return true; 12591 } 12592 } 12593 } 12594 } 12595 SmallPtrSet<const Value *, 16> Visited; 12596 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 12597 } 12598 12599 std::pair<InstructionCost, MVT> 12600 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 12601 Type *Ty) const { 12602 std::pair<InstructionCost, MVT> Cost = 12603 TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 12604 auto Size = DL.getTypeSizeInBits(Ty); 12605 // Maximum load or store can handle 8 dwords for scalar and 4 for 12606 // vector ALU. Let's assume anything above 8 dwords is expensive 12607 // even if legal. 12608 if (Size <= 256) 12609 return Cost; 12610 12611 Cost.first += (Size + 255) / 256; 12612 return Cost; 12613 } 12614 12615 bool SITargetLowering::hasMemSDNodeUser(SDNode *N) const { 12616 SDNode::use_iterator I = N->use_begin(), E = N->use_end(); 12617 for (; I != E; ++I) { 12618 if (MemSDNode *M = dyn_cast<MemSDNode>(*I)) { 12619 if (getBasePtrIndex(M) == I.getOperandNo()) 12620 return true; 12621 } 12622 } 12623 return false; 12624 } 12625 12626 bool SITargetLowering::isReassocProfitable(SelectionDAG &DAG, SDValue N0, 12627 SDValue N1) const { 12628 if (!N0.hasOneUse()) 12629 return false; 12630 // Take care of the oportunity to keep N0 uniform 12631 if (N0->isDivergent() || !N1->isDivergent()) 12632 return true; 12633 // Check if we have a good chance to form the memory access pattern with the 12634 // base and offset 12635 return (DAG.isBaseWithConstantOffset(N0) && 12636 hasMemSDNodeUser(*N0->use_begin())); 12637 } 12638 12639 MachineMemOperand::Flags 12640 SITargetLowering::getTargetMMOFlags(const Instruction &I) const { 12641 // Propagate metadata set by AMDGPUAnnotateUniformValues to the MMO of a load. 12642 if (I.getMetadata("amdgpu.noclobber")) 12643 return MONoClobber; 12644 return MachineMemOperand::MONone; 12645 } 12646