1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 /// \file 10 /// Custom DAG lowering for SI 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "SIISelLowering.h" 15 #include "AMDGPU.h" 16 #include "AMDGPUInstrInfo.h" 17 #include "AMDGPUTargetMachine.h" 18 #include "SIMachineFunctionInfo.h" 19 #include "SIRegisterInfo.h" 20 #include "llvm/ADT/FloatingPointMode.h" 21 #include "llvm/ADT/Statistic.h" 22 #include "llvm/Analysis/LegacyDivergenceAnalysis.h" 23 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 24 #include "llvm/BinaryFormat/ELF.h" 25 #include "llvm/CodeGen/Analysis.h" 26 #include "llvm/CodeGen/FunctionLoweringInfo.h" 27 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h" 28 #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h" 29 #include "llvm/CodeGen/MachineFrameInfo.h" 30 #include "llvm/CodeGen/MachineFunction.h" 31 #include "llvm/CodeGen/MachineLoopInfo.h" 32 #include "llvm/IR/DiagnosticInfo.h" 33 #include "llvm/IR/IntrinsicInst.h" 34 #include "llvm/IR/IntrinsicsAMDGPU.h" 35 #include "llvm/IR/IntrinsicsR600.h" 36 #include "llvm/Support/CommandLine.h" 37 #include "llvm/Support/KnownBits.h" 38 39 using namespace llvm; 40 41 #define DEBUG_TYPE "si-lower" 42 43 STATISTIC(NumTailCalls, "Number of tail calls"); 44 45 static cl::opt<bool> DisableLoopAlignment( 46 "amdgpu-disable-loop-alignment", 47 cl::desc("Do not align and prefetch loops"), 48 cl::init(false)); 49 50 static cl::opt<bool> UseDivergentRegisterIndexing( 51 "amdgpu-use-divergent-register-indexing", 52 cl::Hidden, 53 cl::desc("Use indirect register addressing for divergent indexes"), 54 cl::init(false)); 55 56 static bool hasFP32Denormals(const MachineFunction &MF) { 57 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 58 return Info->getMode().allFP32Denormals(); 59 } 60 61 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 62 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 63 return Info->getMode().allFP64FP16Denormals(); 64 } 65 66 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 67 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 68 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 69 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 70 return AMDGPU::SGPR0 + Reg; 71 } 72 } 73 llvm_unreachable("Cannot allocate sgpr"); 74 } 75 76 SITargetLowering::SITargetLowering(const TargetMachine &TM, 77 const GCNSubtarget &STI) 78 : AMDGPUTargetLowering(TM, STI), 79 Subtarget(&STI) { 80 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 81 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 82 83 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 84 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 85 86 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 87 88 const SIRegisterInfo *TRI = STI.getRegisterInfo(); 89 const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class(); 90 91 addRegisterClass(MVT::f64, V64RegClass); 92 addRegisterClass(MVT::v2f32, V64RegClass); 93 94 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 95 addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96)); 96 97 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 98 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 99 100 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 101 addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128)); 102 103 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 104 addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160)); 105 106 addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass); 107 addRegisterClass(MVT::v6f32, TRI->getVGPRClassForBitWidth(192)); 108 109 addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass); 110 addRegisterClass(MVT::v3f64, TRI->getVGPRClassForBitWidth(192)); 111 112 addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass); 113 addRegisterClass(MVT::v7f32, TRI->getVGPRClassForBitWidth(224)); 114 115 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass); 116 addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256)); 117 118 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass); 119 addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256)); 120 121 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass); 122 addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512)); 123 124 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass); 125 addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512)); 126 127 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass); 128 addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024)); 129 130 if (Subtarget->has16BitInsts()) { 131 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 132 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 133 134 // Unless there are also VOP3P operations, not operations are really legal. 135 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 136 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 137 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 138 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 139 addRegisterClass(MVT::v8i16, &AMDGPU::SGPR_128RegClass); 140 addRegisterClass(MVT::v8f16, &AMDGPU::SGPR_128RegClass); 141 } 142 143 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 144 addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024)); 145 146 computeRegisterProperties(Subtarget->getRegisterInfo()); 147 148 // The boolean content concept here is too inflexible. Compares only ever 149 // really produce a 1-bit result. Any copy/extend from these will turn into a 150 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 151 // it's what most targets use. 152 setBooleanContents(ZeroOrOneBooleanContent); 153 setBooleanVectorContents(ZeroOrOneBooleanContent); 154 155 // We need to custom lower vector stores from local memory 156 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 157 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 158 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 159 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 160 setOperationAction(ISD::LOAD, MVT::v6i32, Custom); 161 setOperationAction(ISD::LOAD, MVT::v7i32, Custom); 162 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 163 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 164 setOperationAction(ISD::LOAD, MVT::i1, Custom); 165 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 166 167 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 168 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 169 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 170 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 171 setOperationAction(ISD::STORE, MVT::v6i32, Custom); 172 setOperationAction(ISD::STORE, MVT::v7i32, Custom); 173 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 174 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 175 setOperationAction(ISD::STORE, MVT::i1, Custom); 176 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 177 178 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 179 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 180 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 181 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 182 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 183 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 184 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 185 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 186 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 187 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 188 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 189 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand); 190 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand); 191 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand); 192 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand); 193 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand); 194 195 setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand); 196 setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand); 197 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand); 198 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand); 199 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand); 200 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand); 201 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand); 202 203 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 204 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 205 206 setOperationAction(ISD::SELECT, MVT::i1, Promote); 207 setOperationAction(ISD::SELECT, MVT::i64, Custom); 208 setOperationAction(ISD::SELECT, MVT::f64, Promote); 209 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 210 211 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 212 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 213 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 214 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 215 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 216 217 setOperationAction(ISD::SETCC, MVT::i1, Promote); 218 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 219 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 220 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 221 222 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 223 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 224 setOperationAction(ISD::TRUNCATE, MVT::v3i32, Expand); 225 setOperationAction(ISD::FP_ROUND, MVT::v3f32, Expand); 226 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand); 227 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand); 228 setOperationAction(ISD::TRUNCATE, MVT::v5i32, Expand); 229 setOperationAction(ISD::FP_ROUND, MVT::v5f32, Expand); 230 setOperationAction(ISD::TRUNCATE, MVT::v6i32, Expand); 231 setOperationAction(ISD::FP_ROUND, MVT::v6f32, Expand); 232 setOperationAction(ISD::TRUNCATE, MVT::v7i32, Expand); 233 setOperationAction(ISD::FP_ROUND, MVT::v7f32, Expand); 234 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand); 235 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand); 236 setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand); 237 setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand); 238 239 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 240 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 241 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 242 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 243 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 244 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 245 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 246 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 247 248 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 249 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 250 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 251 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 252 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 253 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 254 255 setOperationAction(ISD::UADDO, MVT::i32, Legal); 256 setOperationAction(ISD::USUBO, MVT::i32, Legal); 257 258 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 259 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 260 261 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 262 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 263 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 264 265 #if 0 266 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 267 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 268 #endif 269 270 // We only support LOAD/STORE and vector manipulation ops for vectors 271 // with > 4 elements. 272 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 273 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 274 MVT::v3i64, MVT::v3f64, MVT::v6i32, MVT::v6f32, 275 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, 276 MVT::v8i16, MVT::v8f16, MVT::v16i64, MVT::v16f64, 277 MVT::v32i32, MVT::v32f32 }) { 278 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 279 switch (Op) { 280 case ISD::LOAD: 281 case ISD::STORE: 282 case ISD::BUILD_VECTOR: 283 case ISD::BITCAST: 284 case ISD::EXTRACT_VECTOR_ELT: 285 case ISD::INSERT_VECTOR_ELT: 286 case ISD::EXTRACT_SUBVECTOR: 287 case ISD::SCALAR_TO_VECTOR: 288 break; 289 case ISD::INSERT_SUBVECTOR: 290 case ISD::CONCAT_VECTORS: 291 setOperationAction(Op, VT, Custom); 292 break; 293 default: 294 setOperationAction(Op, VT, Expand); 295 break; 296 } 297 } 298 } 299 300 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 301 302 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 303 // is expanded to avoid having two separate loops in case the index is a VGPR. 304 305 // Most operations are naturally 32-bit vector operations. We only support 306 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 307 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 308 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 309 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 310 311 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 312 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 313 314 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 315 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 316 317 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 318 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 319 } 320 321 for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) { 322 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 323 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32); 324 325 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 326 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32); 327 328 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 329 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32); 330 331 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 332 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32); 333 } 334 335 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) { 336 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 337 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32); 338 339 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 340 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32); 341 342 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 343 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32); 344 345 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 346 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32); 347 } 348 349 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) { 350 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 351 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32); 352 353 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 354 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32); 355 356 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 357 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32); 358 359 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 360 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32); 361 } 362 363 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) { 364 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 365 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32); 366 367 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 368 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32); 369 370 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 371 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32); 372 373 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 374 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32); 375 } 376 377 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 378 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 379 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 380 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 381 382 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 383 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 384 385 // Avoid stack access for these. 386 // TODO: Generalize to more vector types. 387 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 388 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 389 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 390 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 391 392 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 393 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 394 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 395 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 396 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 397 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 398 399 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 400 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 401 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 402 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 403 404 // Deal with vec3 vector operations when widened to vec4. 405 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 406 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 407 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 408 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 409 410 // Deal with vec5/6/7 vector operations when widened to vec8. 411 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 412 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 413 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6i32, Custom); 414 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6f32, Custom); 415 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7i32, Custom); 416 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7f32, Custom); 417 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 418 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 419 420 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 421 // and output demarshalling 422 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 423 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 424 425 // We can't return success/failure, only the old value, 426 // let LLVM add the comparison 427 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 428 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 429 430 if (Subtarget->hasFlatAddressSpace()) { 431 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 432 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 433 } 434 435 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 436 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 437 438 // FIXME: This should be narrowed to i32, but that only happens if i64 is 439 // illegal. 440 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 441 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 442 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 443 444 // On SI this is s_memtime and s_memrealtime on VI. 445 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 446 setOperationAction(ISD::TRAP, MVT::Other, Custom); 447 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 448 449 if (Subtarget->has16BitInsts()) { 450 setOperationAction(ISD::FPOW, MVT::f16, Promote); 451 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 452 setOperationAction(ISD::FLOG, MVT::f16, Custom); 453 setOperationAction(ISD::FEXP, MVT::f16, Custom); 454 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 455 } 456 457 if (Subtarget->hasMadMacF32Insts()) 458 setOperationAction(ISD::FMAD, MVT::f32, Legal); 459 460 if (!Subtarget->hasBFI()) { 461 // fcopysign can be done in a single instruction with BFI. 462 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 463 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 464 } 465 466 if (!Subtarget->hasBCNT(32)) 467 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 468 469 if (!Subtarget->hasBCNT(64)) 470 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 471 472 if (Subtarget->hasFFBH()) { 473 setOperationAction(ISD::CTLZ, MVT::i32, Custom); 474 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 475 } 476 477 if (Subtarget->hasFFBL()) { 478 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 479 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 480 } 481 482 // We only really have 32-bit BFE instructions (and 16-bit on VI). 483 // 484 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 485 // effort to match them now. We want this to be false for i64 cases when the 486 // extraction isn't restricted to the upper or lower half. Ideally we would 487 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 488 // span the midpoint are probably relatively rare, so don't worry about them 489 // for now. 490 if (Subtarget->hasBFE()) 491 setHasExtractBitsInsn(true); 492 493 // Clamp modifier on add/sub 494 if (Subtarget->hasIntClamp()) { 495 setOperationAction(ISD::UADDSAT, MVT::i32, Legal); 496 setOperationAction(ISD::USUBSAT, MVT::i32, Legal); 497 } 498 499 if (Subtarget->hasAddNoCarry()) { 500 setOperationAction(ISD::SADDSAT, MVT::i16, Legal); 501 setOperationAction(ISD::SSUBSAT, MVT::i16, Legal); 502 setOperationAction(ISD::SADDSAT, MVT::i32, Legal); 503 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal); 504 } 505 506 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 507 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 508 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 509 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 510 511 512 // These are really only legal for ieee_mode functions. We should be avoiding 513 // them for functions that don't have ieee_mode enabled, so just say they are 514 // legal. 515 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 516 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 517 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 518 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 519 520 521 if (Subtarget->haveRoundOpsF64()) { 522 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 523 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 524 setOperationAction(ISD::FRINT, MVT::f64, Legal); 525 } else { 526 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 527 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 528 setOperationAction(ISD::FRINT, MVT::f64, Custom); 529 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 530 } 531 532 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 533 534 setOperationAction(ISD::FSIN, MVT::f32, Custom); 535 setOperationAction(ISD::FCOS, MVT::f32, Custom); 536 setOperationAction(ISD::FDIV, MVT::f32, Custom); 537 setOperationAction(ISD::FDIV, MVT::f64, Custom); 538 539 if (Subtarget->has16BitInsts()) { 540 setOperationAction(ISD::Constant, MVT::i16, Legal); 541 542 setOperationAction(ISD::SMIN, MVT::i16, Legal); 543 setOperationAction(ISD::SMAX, MVT::i16, Legal); 544 545 setOperationAction(ISD::UMIN, MVT::i16, Legal); 546 setOperationAction(ISD::UMAX, MVT::i16, Legal); 547 548 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 549 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 550 551 setOperationAction(ISD::ROTR, MVT::i16, Expand); 552 setOperationAction(ISD::ROTL, MVT::i16, Expand); 553 554 setOperationAction(ISD::SDIV, MVT::i16, Promote); 555 setOperationAction(ISD::UDIV, MVT::i16, Promote); 556 setOperationAction(ISD::SREM, MVT::i16, Promote); 557 setOperationAction(ISD::UREM, MVT::i16, Promote); 558 setOperationAction(ISD::UADDSAT, MVT::i16, Legal); 559 setOperationAction(ISD::USUBSAT, MVT::i16, Legal); 560 561 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 562 563 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 564 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 565 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 566 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 567 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 568 569 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 570 571 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 572 573 setOperationAction(ISD::LOAD, MVT::i16, Custom); 574 575 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 576 577 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 578 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 579 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 580 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 581 582 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Custom); 583 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Custom); 584 585 // F16 - Constant Actions. 586 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 587 588 // F16 - Load/Store Actions. 589 setOperationAction(ISD::LOAD, MVT::f16, Promote); 590 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 591 setOperationAction(ISD::STORE, MVT::f16, Promote); 592 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 593 594 // F16 - VOP1 Actions. 595 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 596 setOperationAction(ISD::FCOS, MVT::f16, Custom); 597 setOperationAction(ISD::FSIN, MVT::f16, Custom); 598 599 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 600 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 601 602 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 603 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 604 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 605 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 606 setOperationAction(ISD::FROUND, MVT::f16, Custom); 607 setOperationAction(ISD::FPTRUNC_ROUND, MVT::f16, Custom); 608 609 // F16 - VOP2 Actions. 610 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 611 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 612 613 setOperationAction(ISD::FDIV, MVT::f16, Custom); 614 615 // F16 - VOP3 Actions. 616 setOperationAction(ISD::FMA, MVT::f16, Legal); 617 if (STI.hasMadF16()) 618 setOperationAction(ISD::FMAD, MVT::f16, Legal); 619 620 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16, MVT::v8i16, 621 MVT::v8f16}) { 622 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 623 switch (Op) { 624 case ISD::LOAD: 625 case ISD::STORE: 626 case ISD::BUILD_VECTOR: 627 case ISD::BITCAST: 628 case ISD::EXTRACT_VECTOR_ELT: 629 case ISD::INSERT_VECTOR_ELT: 630 case ISD::INSERT_SUBVECTOR: 631 case ISD::EXTRACT_SUBVECTOR: 632 case ISD::SCALAR_TO_VECTOR: 633 break; 634 case ISD::CONCAT_VECTORS: 635 setOperationAction(Op, VT, Custom); 636 break; 637 default: 638 setOperationAction(Op, VT, Expand); 639 break; 640 } 641 } 642 } 643 644 // v_perm_b32 can handle either of these. 645 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 646 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 647 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 648 649 // XXX - Do these do anything? Vector constants turn into build_vector. 650 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 651 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 652 653 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 654 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 655 656 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 657 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 658 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 659 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 660 661 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 662 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 663 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 664 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 665 666 setOperationAction(ISD::AND, MVT::v2i16, Promote); 667 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 668 setOperationAction(ISD::OR, MVT::v2i16, Promote); 669 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 670 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 671 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 672 673 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 674 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 675 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 676 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 677 678 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 679 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 680 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 681 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 682 683 setOperationAction(ISD::LOAD, MVT::v8i16, Promote); 684 AddPromotedToType(ISD::LOAD, MVT::v8i16, MVT::v4i32); 685 setOperationAction(ISD::LOAD, MVT::v8f16, Promote); 686 AddPromotedToType(ISD::LOAD, MVT::v8f16, MVT::v4i32); 687 688 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 689 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 690 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 691 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 692 693 setOperationAction(ISD::STORE, MVT::v8i16, Promote); 694 AddPromotedToType(ISD::STORE, MVT::v8i16, MVT::v4i32); 695 setOperationAction(ISD::STORE, MVT::v8f16, Promote); 696 AddPromotedToType(ISD::STORE, MVT::v8f16, MVT::v4i32); 697 698 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 699 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 700 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 701 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 702 703 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 704 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 705 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 706 707 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Expand); 708 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Expand); 709 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Expand); 710 711 if (!Subtarget->hasVOP3PInsts()) { 712 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 713 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 714 } 715 716 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 717 // This isn't really legal, but this avoids the legalizer unrolling it (and 718 // allows matching fneg (fabs x) patterns) 719 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 720 721 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 722 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 723 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 724 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 725 726 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 727 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 728 setOperationAction(ISD::FMINNUM_IEEE, MVT::v8f16, Custom); 729 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v8f16, Custom); 730 731 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 732 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 733 setOperationAction(ISD::FMINNUM, MVT::v8f16, Expand); 734 setOperationAction(ISD::FMAXNUM, MVT::v8f16, Expand); 735 736 for (MVT Vec16 : { MVT::v8i16, MVT::v8f16 }) { 737 setOperationAction(ISD::BUILD_VECTOR, Vec16, Custom); 738 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec16, Custom); 739 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec16, Expand); 740 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec16, Custom); 741 } 742 } 743 744 if (Subtarget->hasVOP3PInsts()) { 745 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 746 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 747 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 748 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 749 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 750 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 751 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 752 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 753 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 754 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 755 756 setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal); 757 setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal); 758 setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal); 759 setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal); 760 761 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 762 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 763 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 764 765 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 766 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 767 768 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 769 770 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 771 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 772 773 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 774 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 775 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f16, Custom); 776 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i16, Custom); 777 778 for (MVT VT : { MVT::v4i16, MVT::v8i16 }) { 779 // Split vector operations. 780 setOperationAction(ISD::SHL, VT, Custom); 781 setOperationAction(ISD::SRA, VT, Custom); 782 setOperationAction(ISD::SRL, VT, Custom); 783 setOperationAction(ISD::ADD, VT, Custom); 784 setOperationAction(ISD::SUB, VT, Custom); 785 setOperationAction(ISD::MUL, VT, Custom); 786 787 setOperationAction(ISD::SMIN, VT, Custom); 788 setOperationAction(ISD::SMAX, VT, Custom); 789 setOperationAction(ISD::UMIN, VT, Custom); 790 setOperationAction(ISD::UMAX, VT, Custom); 791 792 setOperationAction(ISD::UADDSAT, VT, Custom); 793 setOperationAction(ISD::SADDSAT, VT, Custom); 794 setOperationAction(ISD::USUBSAT, VT, Custom); 795 setOperationAction(ISD::SSUBSAT, VT, Custom); 796 } 797 798 for (MVT VT : { MVT::v4f16, MVT::v8f16 }) { 799 // Split vector operations. 800 setOperationAction(ISD::FADD, VT, Custom); 801 setOperationAction(ISD::FMUL, VT, Custom); 802 setOperationAction(ISD::FMA, VT, Custom); 803 setOperationAction(ISD::FCANONICALIZE, VT, Custom); 804 } 805 806 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 807 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 808 809 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 810 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 811 812 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 813 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 814 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 815 816 if (Subtarget->hasPackedFP32Ops()) { 817 setOperationAction(ISD::FADD, MVT::v2f32, Legal); 818 setOperationAction(ISD::FMUL, MVT::v2f32, Legal); 819 setOperationAction(ISD::FMA, MVT::v2f32, Legal); 820 setOperationAction(ISD::FNEG, MVT::v2f32, Legal); 821 822 for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) { 823 setOperationAction(ISD::FADD, VT, Custom); 824 setOperationAction(ISD::FMUL, VT, Custom); 825 setOperationAction(ISD::FMA, VT, Custom); 826 } 827 } 828 } 829 830 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 831 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 832 833 if (Subtarget->has16BitInsts()) { 834 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 835 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 836 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 837 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 838 } else { 839 // Legalization hack. 840 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 841 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 842 843 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 844 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 845 } 846 847 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8, 848 MVT::v8i16, MVT::v8f16 }) { 849 setOperationAction(ISD::SELECT, VT, Custom); 850 } 851 852 setOperationAction(ISD::SMULO, MVT::i64, Custom); 853 setOperationAction(ISD::UMULO, MVT::i64, Custom); 854 855 if (Subtarget->hasMad64_32()) { 856 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom); 857 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom); 858 } 859 860 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 861 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 862 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 863 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 864 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 865 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 866 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 867 868 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 869 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 870 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom); 871 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom); 872 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 873 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 874 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 875 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 876 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 877 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 878 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 879 880 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 881 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 882 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 883 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom); 884 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom); 885 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 886 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 887 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 888 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 889 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 890 891 setTargetDAGCombine({ISD::ADD, 892 ISD::ADDCARRY, 893 ISD::SUB, 894 ISD::SUBCARRY, 895 ISD::FADD, 896 ISD::FSUB, 897 ISD::FMINNUM, 898 ISD::FMAXNUM, 899 ISD::FMINNUM_IEEE, 900 ISD::FMAXNUM_IEEE, 901 ISD::FMA, 902 ISD::SMIN, 903 ISD::SMAX, 904 ISD::UMIN, 905 ISD::UMAX, 906 ISD::SETCC, 907 ISD::AND, 908 ISD::OR, 909 ISD::XOR, 910 ISD::SINT_TO_FP, 911 ISD::UINT_TO_FP, 912 ISD::FCANONICALIZE, 913 ISD::SCALAR_TO_VECTOR, 914 ISD::ZERO_EXTEND, 915 ISD::SIGN_EXTEND_INREG, 916 ISD::EXTRACT_VECTOR_ELT, 917 ISD::INSERT_VECTOR_ELT}); 918 919 // All memory operations. Some folding on the pointer operand is done to help 920 // matching the constant offsets in the addressing modes. 921 setTargetDAGCombine({ISD::LOAD, 922 ISD::STORE, 923 ISD::ATOMIC_LOAD, 924 ISD::ATOMIC_STORE, 925 ISD::ATOMIC_CMP_SWAP, 926 ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 927 ISD::ATOMIC_SWAP, 928 ISD::ATOMIC_LOAD_ADD, 929 ISD::ATOMIC_LOAD_SUB, 930 ISD::ATOMIC_LOAD_AND, 931 ISD::ATOMIC_LOAD_OR, 932 ISD::ATOMIC_LOAD_XOR, 933 ISD::ATOMIC_LOAD_NAND, 934 ISD::ATOMIC_LOAD_MIN, 935 ISD::ATOMIC_LOAD_MAX, 936 ISD::ATOMIC_LOAD_UMIN, 937 ISD::ATOMIC_LOAD_UMAX, 938 ISD::ATOMIC_LOAD_FADD, 939 ISD::INTRINSIC_VOID, 940 ISD::INTRINSIC_W_CHAIN}); 941 942 // FIXME: In other contexts we pretend this is a per-function property. 943 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 944 945 setSchedulingPreference(Sched::RegPressure); 946 } 947 948 const GCNSubtarget *SITargetLowering::getSubtarget() const { 949 return Subtarget; 950 } 951 952 //===----------------------------------------------------------------------===// 953 // TargetLowering queries 954 //===----------------------------------------------------------------------===// 955 956 // v_mad_mix* support a conversion from f16 to f32. 957 // 958 // There is only one special case when denormals are enabled we don't currently, 959 // where this is OK to use. 960 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 961 EVT DestVT, EVT SrcVT) const { 962 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 963 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 964 DestVT.getScalarType() == MVT::f32 && 965 SrcVT.getScalarType() == MVT::f16 && 966 // TODO: This probably only requires no input flushing? 967 !hasFP32Denormals(DAG.getMachineFunction()); 968 } 969 970 bool SITargetLowering::isFPExtFoldable(const MachineInstr &MI, unsigned Opcode, 971 LLT DestTy, LLT SrcTy) const { 972 return ((Opcode == TargetOpcode::G_FMAD && Subtarget->hasMadMixInsts()) || 973 (Opcode == TargetOpcode::G_FMA && Subtarget->hasFmaMixInsts())) && 974 DestTy.getScalarSizeInBits() == 32 && 975 SrcTy.getScalarSizeInBits() == 16 && 976 // TODO: This probably only requires no input flushing? 977 !hasFP32Denormals(*MI.getMF()); 978 } 979 980 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 981 // SI has some legal vector types, but no legal vector operations. Say no 982 // shuffles are legal in order to prefer scalarizing some vector operations. 983 return false; 984 } 985 986 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 987 CallingConv::ID CC, 988 EVT VT) const { 989 if (CC == CallingConv::AMDGPU_KERNEL) 990 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 991 992 if (VT.isVector()) { 993 EVT ScalarVT = VT.getScalarType(); 994 unsigned Size = ScalarVT.getSizeInBits(); 995 if (Size == 16) { 996 if (Subtarget->has16BitInsts()) 997 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 998 return VT.isInteger() ? MVT::i32 : MVT::f32; 999 } 1000 1001 if (Size < 16) 1002 return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32; 1003 return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32; 1004 } 1005 1006 if (VT.getSizeInBits() > 32) 1007 return MVT::i32; 1008 1009 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1010 } 1011 1012 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1013 CallingConv::ID CC, 1014 EVT VT) const { 1015 if (CC == CallingConv::AMDGPU_KERNEL) 1016 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1017 1018 if (VT.isVector()) { 1019 unsigned NumElts = VT.getVectorNumElements(); 1020 EVT ScalarVT = VT.getScalarType(); 1021 unsigned Size = ScalarVT.getSizeInBits(); 1022 1023 // FIXME: Should probably promote 8-bit vectors to i16. 1024 if (Size == 16 && Subtarget->has16BitInsts()) 1025 return (NumElts + 1) / 2; 1026 1027 if (Size <= 32) 1028 return NumElts; 1029 1030 if (Size > 32) 1031 return NumElts * ((Size + 31) / 32); 1032 } else if (VT.getSizeInBits() > 32) 1033 return (VT.getSizeInBits() + 31) / 32; 1034 1035 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1036 } 1037 1038 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 1039 LLVMContext &Context, CallingConv::ID CC, 1040 EVT VT, EVT &IntermediateVT, 1041 unsigned &NumIntermediates, MVT &RegisterVT) const { 1042 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 1043 unsigned NumElts = VT.getVectorNumElements(); 1044 EVT ScalarVT = VT.getScalarType(); 1045 unsigned Size = ScalarVT.getSizeInBits(); 1046 // FIXME: We should fix the ABI to be the same on targets without 16-bit 1047 // support, but unless we can properly handle 3-vectors, it will be still be 1048 // inconsistent. 1049 if (Size == 16 && Subtarget->has16BitInsts()) { 1050 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 1051 IntermediateVT = RegisterVT; 1052 NumIntermediates = (NumElts + 1) / 2; 1053 return NumIntermediates; 1054 } 1055 1056 if (Size == 32) { 1057 RegisterVT = ScalarVT.getSimpleVT(); 1058 IntermediateVT = RegisterVT; 1059 NumIntermediates = NumElts; 1060 return NumIntermediates; 1061 } 1062 1063 if (Size < 16 && Subtarget->has16BitInsts()) { 1064 // FIXME: Should probably form v2i16 pieces 1065 RegisterVT = MVT::i16; 1066 IntermediateVT = ScalarVT; 1067 NumIntermediates = NumElts; 1068 return NumIntermediates; 1069 } 1070 1071 1072 if (Size != 16 && Size <= 32) { 1073 RegisterVT = MVT::i32; 1074 IntermediateVT = ScalarVT; 1075 NumIntermediates = NumElts; 1076 return NumIntermediates; 1077 } 1078 1079 if (Size > 32) { 1080 RegisterVT = MVT::i32; 1081 IntermediateVT = RegisterVT; 1082 NumIntermediates = NumElts * ((Size + 31) / 32); 1083 return NumIntermediates; 1084 } 1085 } 1086 1087 return TargetLowering::getVectorTypeBreakdownForCallingConv( 1088 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 1089 } 1090 1091 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 1092 assert(DMaskLanes != 0); 1093 1094 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 1095 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 1096 return EVT::getVectorVT(Ty->getContext(), 1097 EVT::getEVT(VT->getElementType()), 1098 NumElts); 1099 } 1100 1101 return EVT::getEVT(Ty); 1102 } 1103 1104 // Peek through TFE struct returns to only use the data size. 1105 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 1106 auto *ST = dyn_cast<StructType>(Ty); 1107 if (!ST) 1108 return memVTFromImageData(Ty, DMaskLanes); 1109 1110 // Some intrinsics return an aggregate type - special case to work out the 1111 // correct memVT. 1112 // 1113 // Only limited forms of aggregate type currently expected. 1114 if (ST->getNumContainedTypes() != 2 || 1115 !ST->getContainedType(1)->isIntegerTy(32)) 1116 return EVT(); 1117 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 1118 } 1119 1120 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1121 const CallInst &CI, 1122 MachineFunction &MF, 1123 unsigned IntrID) const { 1124 Info.flags = MachineMemOperand::MONone; 1125 if (CI.hasMetadata(LLVMContext::MD_invariant_load)) 1126 Info.flags |= MachineMemOperand::MOInvariant; 1127 1128 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 1129 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 1130 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 1131 (Intrinsic::ID)IntrID); 1132 if (Attr.hasFnAttr(Attribute::ReadNone)) 1133 return false; 1134 1135 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1136 1137 if (RsrcIntr->IsImage) { 1138 Info.ptrVal = 1139 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1140 Info.align.reset(); 1141 } else { 1142 Info.ptrVal = 1143 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1144 } 1145 1146 Info.flags |= MachineMemOperand::MODereferenceable; 1147 if (Attr.hasFnAttr(Attribute::ReadOnly)) { 1148 unsigned DMaskLanes = 4; 1149 1150 if (RsrcIntr->IsImage) { 1151 const AMDGPU::ImageDimIntrinsicInfo *Intr 1152 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 1153 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1154 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1155 1156 if (!BaseOpcode->Gather4) { 1157 // If this isn't a gather, we may have excess loaded elements in the 1158 // IR type. Check the dmask for the real number of elements loaded. 1159 unsigned DMask 1160 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1161 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1162 } 1163 1164 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1165 } else 1166 Info.memVT = EVT::getEVT(CI.getType()); 1167 1168 // FIXME: What does alignment mean for an image? 1169 Info.opc = ISD::INTRINSIC_W_CHAIN; 1170 Info.flags |= MachineMemOperand::MOLoad; 1171 } else if (Attr.hasFnAttr(Attribute::WriteOnly)) { 1172 Info.opc = ISD::INTRINSIC_VOID; 1173 1174 Type *DataTy = CI.getArgOperand(0)->getType(); 1175 if (RsrcIntr->IsImage) { 1176 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1177 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1178 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1179 } else 1180 Info.memVT = EVT::getEVT(DataTy); 1181 1182 Info.flags |= MachineMemOperand::MOStore; 1183 } else { 1184 // Atomic 1185 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID : 1186 ISD::INTRINSIC_W_CHAIN; 1187 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 1188 Info.flags |= MachineMemOperand::MOLoad | 1189 MachineMemOperand::MOStore | 1190 MachineMemOperand::MODereferenceable; 1191 1192 // XXX - Should this be volatile without known ordering? 1193 Info.flags |= MachineMemOperand::MOVolatile; 1194 1195 switch (IntrID) { 1196 default: 1197 break; 1198 case Intrinsic::amdgcn_raw_buffer_load_lds: 1199 case Intrinsic::amdgcn_struct_buffer_load_lds: { 1200 unsigned Width = cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue(); 1201 Info.memVT = EVT::getIntegerVT(CI.getContext(), Width * 8); 1202 return true; 1203 } 1204 } 1205 } 1206 return true; 1207 } 1208 1209 switch (IntrID) { 1210 case Intrinsic::amdgcn_atomic_inc: 1211 case Intrinsic::amdgcn_atomic_dec: 1212 case Intrinsic::amdgcn_ds_ordered_add: 1213 case Intrinsic::amdgcn_ds_ordered_swap: 1214 case Intrinsic::amdgcn_ds_fadd: 1215 case Intrinsic::amdgcn_ds_fmin: 1216 case Intrinsic::amdgcn_ds_fmax: { 1217 Info.opc = ISD::INTRINSIC_W_CHAIN; 1218 Info.memVT = MVT::getVT(CI.getType()); 1219 Info.ptrVal = CI.getOperand(0); 1220 Info.align.reset(); 1221 Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1222 1223 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1224 if (!Vol->isZero()) 1225 Info.flags |= MachineMemOperand::MOVolatile; 1226 1227 return true; 1228 } 1229 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1230 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1231 1232 Info.opc = ISD::INTRINSIC_W_CHAIN; 1233 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1234 Info.ptrVal = 1235 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1236 Info.align.reset(); 1237 Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1238 1239 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1240 if (!Vol || !Vol->isZero()) 1241 Info.flags |= MachineMemOperand::MOVolatile; 1242 1243 return true; 1244 } 1245 case Intrinsic::amdgcn_ds_append: 1246 case Intrinsic::amdgcn_ds_consume: { 1247 Info.opc = ISD::INTRINSIC_W_CHAIN; 1248 Info.memVT = MVT::getVT(CI.getType()); 1249 Info.ptrVal = CI.getOperand(0); 1250 Info.align.reset(); 1251 Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1252 1253 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1254 if (!Vol->isZero()) 1255 Info.flags |= MachineMemOperand::MOVolatile; 1256 1257 return true; 1258 } 1259 case Intrinsic::amdgcn_global_atomic_csub: { 1260 Info.opc = ISD::INTRINSIC_W_CHAIN; 1261 Info.memVT = MVT::getVT(CI.getType()); 1262 Info.ptrVal = CI.getOperand(0); 1263 Info.align.reset(); 1264 Info.flags |= MachineMemOperand::MOLoad | 1265 MachineMemOperand::MOStore | 1266 MachineMemOperand::MOVolatile; 1267 return true; 1268 } 1269 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 1270 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1271 Info.opc = ISD::INTRINSIC_W_CHAIN; 1272 Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT? 1273 Info.ptrVal = 1274 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1275 Info.align.reset(); 1276 Info.flags |= MachineMemOperand::MOLoad | 1277 MachineMemOperand::MODereferenceable; 1278 return true; 1279 } 1280 case Intrinsic::amdgcn_global_atomic_fadd: 1281 case Intrinsic::amdgcn_global_atomic_fmin: 1282 case Intrinsic::amdgcn_global_atomic_fmax: 1283 case Intrinsic::amdgcn_flat_atomic_fadd: 1284 case Intrinsic::amdgcn_flat_atomic_fmin: 1285 case Intrinsic::amdgcn_flat_atomic_fmax: 1286 case Intrinsic::amdgcn_global_atomic_fadd_v2bf16: 1287 case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16: { 1288 Info.opc = ISD::INTRINSIC_W_CHAIN; 1289 Info.memVT = MVT::getVT(CI.getType()); 1290 Info.ptrVal = CI.getOperand(0); 1291 Info.align.reset(); 1292 Info.flags |= MachineMemOperand::MOLoad | 1293 MachineMemOperand::MOStore | 1294 MachineMemOperand::MODereferenceable | 1295 MachineMemOperand::MOVolatile; 1296 return true; 1297 } 1298 case Intrinsic::amdgcn_ds_gws_init: 1299 case Intrinsic::amdgcn_ds_gws_barrier: 1300 case Intrinsic::amdgcn_ds_gws_sema_v: 1301 case Intrinsic::amdgcn_ds_gws_sema_br: 1302 case Intrinsic::amdgcn_ds_gws_sema_p: 1303 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1304 Info.opc = ISD::INTRINSIC_VOID; 1305 1306 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1307 Info.ptrVal = 1308 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1309 1310 // This is an abstract access, but we need to specify a type and size. 1311 Info.memVT = MVT::i32; 1312 Info.size = 4; 1313 Info.align = Align(4); 1314 1315 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1316 Info.flags |= MachineMemOperand::MOLoad; 1317 else 1318 Info.flags |= MachineMemOperand::MOStore; 1319 return true; 1320 } 1321 case Intrinsic::amdgcn_global_load_lds: { 1322 Info.opc = ISD::INTRINSIC_VOID; 1323 unsigned Width = cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue(); 1324 Info.memVT = EVT::getIntegerVT(CI.getContext(), Width * 8); 1325 Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 1326 MachineMemOperand::MOVolatile; 1327 return true; 1328 } 1329 default: 1330 return false; 1331 } 1332 } 1333 1334 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1335 SmallVectorImpl<Value*> &Ops, 1336 Type *&AccessTy) const { 1337 switch (II->getIntrinsicID()) { 1338 case Intrinsic::amdgcn_atomic_inc: 1339 case Intrinsic::amdgcn_atomic_dec: 1340 case Intrinsic::amdgcn_ds_ordered_add: 1341 case Intrinsic::amdgcn_ds_ordered_swap: 1342 case Intrinsic::amdgcn_ds_append: 1343 case Intrinsic::amdgcn_ds_consume: 1344 case Intrinsic::amdgcn_ds_fadd: 1345 case Intrinsic::amdgcn_ds_fmin: 1346 case Intrinsic::amdgcn_ds_fmax: 1347 case Intrinsic::amdgcn_global_atomic_fadd: 1348 case Intrinsic::amdgcn_flat_atomic_fadd: 1349 case Intrinsic::amdgcn_flat_atomic_fmin: 1350 case Intrinsic::amdgcn_flat_atomic_fmax: 1351 case Intrinsic::amdgcn_global_atomic_fadd_v2bf16: 1352 case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16: 1353 case Intrinsic::amdgcn_global_atomic_csub: { 1354 Value *Ptr = II->getArgOperand(0); 1355 AccessTy = II->getType(); 1356 Ops.push_back(Ptr); 1357 return true; 1358 } 1359 default: 1360 return false; 1361 } 1362 } 1363 1364 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1365 if (!Subtarget->hasFlatInstOffsets()) { 1366 // Flat instructions do not have offsets, and only have the register 1367 // address. 1368 return AM.BaseOffs == 0 && AM.Scale == 0; 1369 } 1370 1371 return AM.Scale == 0 && 1372 (AM.BaseOffs == 0 || 1373 Subtarget->getInstrInfo()->isLegalFLATOffset( 1374 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT)); 1375 } 1376 1377 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1378 if (Subtarget->hasFlatGlobalInsts()) 1379 return AM.Scale == 0 && 1380 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1381 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1382 SIInstrFlags::FlatGlobal)); 1383 1384 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1385 // Assume the we will use FLAT for all global memory accesses 1386 // on VI. 1387 // FIXME: This assumption is currently wrong. On VI we still use 1388 // MUBUF instructions for the r + i addressing mode. As currently 1389 // implemented, the MUBUF instructions only work on buffer < 4GB. 1390 // It may be possible to support > 4GB buffers with MUBUF instructions, 1391 // by setting the stride value in the resource descriptor which would 1392 // increase the size limit to (stride * 4GB). However, this is risky, 1393 // because it has never been validated. 1394 return isLegalFlatAddressingMode(AM); 1395 } 1396 1397 return isLegalMUBUFAddressingMode(AM); 1398 } 1399 1400 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1401 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1402 // additionally can do r + r + i with addr64. 32-bit has more addressing 1403 // mode options. Depending on the resource constant, it can also do 1404 // (i64 r0) + (i32 r1) * (i14 i). 1405 // 1406 // Private arrays end up using a scratch buffer most of the time, so also 1407 // assume those use MUBUF instructions. Scratch loads / stores are currently 1408 // implemented as mubuf instructions with offen bit set, so slightly 1409 // different than the normal addr64. 1410 if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs)) 1411 return false; 1412 1413 // FIXME: Since we can split immediate into soffset and immediate offset, 1414 // would it make sense to allow any immediate? 1415 1416 switch (AM.Scale) { 1417 case 0: // r + i or just i, depending on HasBaseReg. 1418 return true; 1419 case 1: 1420 return true; // We have r + r or r + i. 1421 case 2: 1422 if (AM.HasBaseReg) { 1423 // Reject 2 * r + r. 1424 return false; 1425 } 1426 1427 // Allow 2 * r as r + r 1428 // Or 2 * r + i is allowed as r + r + i. 1429 return true; 1430 default: // Don't allow n * r 1431 return false; 1432 } 1433 } 1434 1435 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1436 const AddrMode &AM, Type *Ty, 1437 unsigned AS, Instruction *I) const { 1438 // No global is ever allowed as a base. 1439 if (AM.BaseGV) 1440 return false; 1441 1442 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1443 return isLegalGlobalAddressingMode(AM); 1444 1445 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1446 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1447 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1448 // If the offset isn't a multiple of 4, it probably isn't going to be 1449 // correctly aligned. 1450 // FIXME: Can we get the real alignment here? 1451 if (AM.BaseOffs % 4 != 0) 1452 return isLegalMUBUFAddressingMode(AM); 1453 1454 // There are no SMRD extloads, so if we have to do a small type access we 1455 // will use a MUBUF load. 1456 // FIXME?: We also need to do this if unaligned, but we don't know the 1457 // alignment here. 1458 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1459 return isLegalGlobalAddressingMode(AM); 1460 1461 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1462 // SMRD instructions have an 8-bit, dword offset on SI. 1463 if (!isUInt<8>(AM.BaseOffs / 4)) 1464 return false; 1465 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1466 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1467 // in 8-bits, it can use a smaller encoding. 1468 if (!isUInt<32>(AM.BaseOffs / 4)) 1469 return false; 1470 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1471 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1472 if (!isUInt<20>(AM.BaseOffs)) 1473 return false; 1474 } else 1475 llvm_unreachable("unhandled generation"); 1476 1477 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1478 return true; 1479 1480 if (AM.Scale == 1 && AM.HasBaseReg) 1481 return true; 1482 1483 return false; 1484 1485 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1486 return isLegalMUBUFAddressingMode(AM); 1487 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1488 AS == AMDGPUAS::REGION_ADDRESS) { 1489 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1490 // field. 1491 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1492 // an 8-bit dword offset but we don't know the alignment here. 1493 if (!isUInt<16>(AM.BaseOffs)) 1494 return false; 1495 1496 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1497 return true; 1498 1499 if (AM.Scale == 1 && AM.HasBaseReg) 1500 return true; 1501 1502 return false; 1503 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1504 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1505 // For an unknown address space, this usually means that this is for some 1506 // reason being used for pure arithmetic, and not based on some addressing 1507 // computation. We don't have instructions that compute pointers with any 1508 // addressing modes, so treat them as having no offset like flat 1509 // instructions. 1510 return isLegalFlatAddressingMode(AM); 1511 } 1512 1513 // Assume a user alias of global for unknown address spaces. 1514 return isLegalGlobalAddressingMode(AM); 1515 } 1516 1517 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1518 const MachineFunction &MF) const { 1519 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1520 return (MemVT.getSizeInBits() <= 4 * 32); 1521 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1522 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1523 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1524 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1525 return (MemVT.getSizeInBits() <= 2 * 32); 1526 } 1527 return true; 1528 } 1529 1530 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1531 unsigned Size, unsigned AddrSpace, Align Alignment, 1532 MachineMemOperand::Flags Flags, bool *IsFast) const { 1533 if (IsFast) 1534 *IsFast = false; 1535 1536 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1537 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1538 // Check if alignment requirements for ds_read/write instructions are 1539 // disabled. 1540 if (!Subtarget->hasUnalignedDSAccessEnabled() && Alignment < Align(4)) 1541 return false; 1542 1543 Align RequiredAlignment(PowerOf2Ceil(Size/8)); // Natural alignment. 1544 if (Subtarget->hasLDSMisalignedBug() && Size > 32 && 1545 Alignment < RequiredAlignment) 1546 return false; 1547 1548 // Either, the alignment requirements are "enabled", or there is an 1549 // unaligned LDS access related hardware bug though alignment requirements 1550 // are "disabled". In either case, we need to check for proper alignment 1551 // requirements. 1552 // 1553 switch (Size) { 1554 case 64: 1555 // SI has a hardware bug in the LDS / GDS bounds checking: if the base 1556 // address is negative, then the instruction is incorrectly treated as 1557 // out-of-bounds even if base + offsets is in bounds. Split vectorized 1558 // loads here to avoid emitting ds_read2_b32. We may re-combine the 1559 // load later in the SILoadStoreOptimizer. 1560 if (!Subtarget->hasUsableDSOffset() && Alignment < Align(8)) 1561 return false; 1562 1563 // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we 1564 // can do a 4 byte aligned, 8 byte access in a single operation using 1565 // ds_read2/write2_b32 with adjacent offsets. 1566 RequiredAlignment = Align(4); 1567 1568 if (Subtarget->hasUnalignedDSAccessEnabled()) { 1569 // We will either select ds_read_b64/ds_write_b64 or ds_read2_b32/ 1570 // ds_write2_b32 depending on the alignment. In either case with either 1571 // alignment there is no faster way of doing this. 1572 if (IsFast) 1573 *IsFast = true; 1574 return true; 1575 } 1576 1577 break; 1578 case 96: 1579 if (!Subtarget->hasDS96AndDS128()) 1580 return false; 1581 1582 // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on 1583 // gfx8 and older. 1584 1585 if (Subtarget->hasUnalignedDSAccessEnabled()) { 1586 // Naturally aligned access is fastest. However, also report it is Fast 1587 // if memory is aligned less than DWORD. A narrow load or store will be 1588 // be equally slow as a single ds_read_b96/ds_write_b96, but there will 1589 // be more of them, so overall we will pay less penalty issuing a single 1590 // instruction. 1591 if (IsFast) 1592 *IsFast = Alignment >= RequiredAlignment || Alignment < Align(4); 1593 return true; 1594 } 1595 1596 break; 1597 case 128: 1598 if (!Subtarget->hasDS96AndDS128() || !Subtarget->useDS128()) 1599 return false; 1600 1601 // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on 1602 // gfx8 and older, but we can do a 8 byte aligned, 16 byte access in a 1603 // single operation using ds_read2/write2_b64. 1604 RequiredAlignment = Align(8); 1605 1606 if (Subtarget->hasUnalignedDSAccessEnabled()) { 1607 // Naturally aligned access is fastest. However, also report it is Fast 1608 // if memory is aligned less than DWORD. A narrow load or store will be 1609 // be equally slow as a single ds_read_b128/ds_write_b128, but there 1610 // will be more of them, so overall we will pay less penalty issuing a 1611 // single instruction. 1612 if (IsFast) 1613 *IsFast = Alignment >= RequiredAlignment || Alignment < Align(4); 1614 return true; 1615 } 1616 1617 break; 1618 default: 1619 if (Size > 32) 1620 return false; 1621 1622 break; 1623 } 1624 1625 if (IsFast) 1626 *IsFast = Alignment >= RequiredAlignment; 1627 1628 return Alignment >= RequiredAlignment || 1629 Subtarget->hasUnalignedDSAccessEnabled(); 1630 } 1631 1632 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) { 1633 bool AlignedBy4 = Alignment >= Align(4); 1634 if (IsFast) 1635 *IsFast = AlignedBy4; 1636 1637 return AlignedBy4 || 1638 Subtarget->enableFlatScratch() || 1639 Subtarget->hasUnalignedScratchAccess(); 1640 } 1641 1642 // FIXME: We have to be conservative here and assume that flat operations 1643 // will access scratch. If we had access to the IR function, then we 1644 // could determine if any private memory was used in the function. 1645 if (AddrSpace == AMDGPUAS::FLAT_ADDRESS && 1646 !Subtarget->hasUnalignedScratchAccess()) { 1647 bool AlignedBy4 = Alignment >= Align(4); 1648 if (IsFast) 1649 *IsFast = AlignedBy4; 1650 1651 return AlignedBy4; 1652 } 1653 1654 if (Subtarget->hasUnalignedBufferAccessEnabled()) { 1655 // If we have a uniform constant load, it still requires using a slow 1656 // buffer instruction if unaligned. 1657 if (IsFast) { 1658 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1659 // 2-byte alignment is worse than 1 unless doing a 2-byte access. 1660 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1661 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1662 Alignment >= Align(4) : Alignment != Align(2); 1663 } 1664 1665 return true; 1666 } 1667 1668 // Smaller than dword value must be aligned. 1669 if (Size < 32) 1670 return false; 1671 1672 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1673 // byte-address are ignored, thus forcing Dword alignment. 1674 // This applies to private, global, and constant memory. 1675 if (IsFast) 1676 *IsFast = true; 1677 1678 return Size >= 32 && Alignment >= Align(4); 1679 } 1680 1681 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1682 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 1683 bool *IsFast) const { 1684 bool Allow = allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1685 Alignment, Flags, IsFast); 1686 1687 if (Allow && IsFast && Subtarget->hasUnalignedDSAccessEnabled() && 1688 (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1689 AddrSpace == AMDGPUAS::REGION_ADDRESS)) { 1690 // Lie it is fast if +unaligned-access-mode is passed so that DS accesses 1691 // get vectorized. We could use ds_read2_b*/ds_write2_b* instructions on a 1692 // misaligned data which is faster than a pair of ds_read_b*/ds_write_b* 1693 // which would be equally misaligned. 1694 // This is only used by the common passes, selection always calls the 1695 // allowsMisalignedMemoryAccessesImpl version. 1696 *IsFast = true; 1697 } 1698 1699 return Allow; 1700 } 1701 1702 EVT SITargetLowering::getOptimalMemOpType( 1703 const MemOp &Op, const AttributeList &FuncAttributes) const { 1704 // FIXME: Should account for address space here. 1705 1706 // The default fallback uses the private pointer size as a guess for a type to 1707 // use. Make sure we switch these to 64-bit accesses. 1708 1709 if (Op.size() >= 16 && 1710 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1711 return MVT::v4i32; 1712 1713 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1714 return MVT::v2i32; 1715 1716 // Use the default. 1717 return MVT::Other; 1718 } 1719 1720 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1721 const MemSDNode *MemNode = cast<MemSDNode>(N); 1722 return MemNode->getMemOperand()->getFlags() & MONoClobber; 1723 } 1724 1725 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) { 1726 return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS || 1727 AS == AMDGPUAS::PRIVATE_ADDRESS; 1728 } 1729 1730 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1731 unsigned DestAS) const { 1732 // Flat -> private/local is a simple truncate. 1733 // Flat -> global is no-op 1734 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1735 return true; 1736 1737 const GCNTargetMachine &TM = 1738 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1739 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 1740 } 1741 1742 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1743 const MemSDNode *MemNode = cast<MemSDNode>(N); 1744 1745 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1746 } 1747 1748 TargetLoweringBase::LegalizeTypeAction 1749 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1750 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 && 1751 VT.getScalarType().bitsLE(MVT::i16)) 1752 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1753 return TargetLoweringBase::getPreferredVectorAction(VT); 1754 } 1755 1756 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1757 Type *Ty) const { 1758 // FIXME: Could be smarter if called for vector constants. 1759 return true; 1760 } 1761 1762 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1763 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1764 switch (Op) { 1765 case ISD::LOAD: 1766 case ISD::STORE: 1767 1768 // These operations are done with 32-bit instructions anyway. 1769 case ISD::AND: 1770 case ISD::OR: 1771 case ISD::XOR: 1772 case ISD::SELECT: 1773 // TODO: Extensions? 1774 return true; 1775 default: 1776 return false; 1777 } 1778 } 1779 1780 // SimplifySetCC uses this function to determine whether or not it should 1781 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1782 if (VT == MVT::i1 && Op == ISD::SETCC) 1783 return false; 1784 1785 return TargetLowering::isTypeDesirableForOp(Op, VT); 1786 } 1787 1788 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1789 const SDLoc &SL, 1790 SDValue Chain, 1791 uint64_t Offset) const { 1792 const DataLayout &DL = DAG.getDataLayout(); 1793 MachineFunction &MF = DAG.getMachineFunction(); 1794 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1795 1796 const ArgDescriptor *InputPtrReg; 1797 const TargetRegisterClass *RC; 1798 LLT ArgTy; 1799 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1800 1801 std::tie(InputPtrReg, RC, ArgTy) = 1802 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1803 1804 // We may not have the kernarg segment argument if we have no kernel 1805 // arguments. 1806 if (!InputPtrReg) 1807 return DAG.getConstant(0, SL, PtrVT); 1808 1809 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1810 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1811 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1812 1813 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset)); 1814 } 1815 1816 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1817 const SDLoc &SL) const { 1818 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1819 FIRST_IMPLICIT); 1820 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1821 } 1822 1823 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1824 const SDLoc &SL, SDValue Val, 1825 bool Signed, 1826 const ISD::InputArg *Arg) const { 1827 // First, if it is a widened vector, narrow it. 1828 if (VT.isVector() && 1829 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1830 EVT NarrowedVT = 1831 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1832 VT.getVectorNumElements()); 1833 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1834 DAG.getConstant(0, SL, MVT::i32)); 1835 } 1836 1837 // Then convert the vector elements or scalar value. 1838 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1839 VT.bitsLT(MemVT)) { 1840 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1841 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1842 } 1843 1844 if (MemVT.isFloatingPoint()) 1845 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1846 else if (Signed) 1847 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1848 else 1849 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1850 1851 return Val; 1852 } 1853 1854 SDValue SITargetLowering::lowerKernargMemParameter( 1855 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1856 uint64_t Offset, Align Alignment, bool Signed, 1857 const ISD::InputArg *Arg) const { 1858 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1859 1860 // Try to avoid using an extload by loading earlier than the argument address, 1861 // and extracting the relevant bits. The load should hopefully be merged with 1862 // the previous argument. 1863 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1864 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1865 int64_t AlignDownOffset = alignDown(Offset, 4); 1866 int64_t OffsetDiff = Offset - AlignDownOffset; 1867 1868 EVT IntVT = MemVT.changeTypeToInteger(); 1869 1870 // TODO: If we passed in the base kernel offset we could have a better 1871 // alignment than 4, but we don't really need it. 1872 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1873 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4), 1874 MachineMemOperand::MODereferenceable | 1875 MachineMemOperand::MOInvariant); 1876 1877 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1878 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1879 1880 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1881 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1882 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1883 1884 1885 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1886 } 1887 1888 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1889 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1890 MachineMemOperand::MODereferenceable | 1891 MachineMemOperand::MOInvariant); 1892 1893 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1894 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1895 } 1896 1897 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1898 const SDLoc &SL, SDValue Chain, 1899 const ISD::InputArg &Arg) const { 1900 MachineFunction &MF = DAG.getMachineFunction(); 1901 MachineFrameInfo &MFI = MF.getFrameInfo(); 1902 1903 if (Arg.Flags.isByVal()) { 1904 unsigned Size = Arg.Flags.getByValSize(); 1905 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1906 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1907 } 1908 1909 unsigned ArgOffset = VA.getLocMemOffset(); 1910 unsigned ArgSize = VA.getValVT().getStoreSize(); 1911 1912 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1913 1914 // Create load nodes to retrieve arguments from the stack. 1915 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1916 SDValue ArgValue; 1917 1918 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1919 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1920 MVT MemVT = VA.getValVT(); 1921 1922 switch (VA.getLocInfo()) { 1923 default: 1924 break; 1925 case CCValAssign::BCvt: 1926 MemVT = VA.getLocVT(); 1927 break; 1928 case CCValAssign::SExt: 1929 ExtType = ISD::SEXTLOAD; 1930 break; 1931 case CCValAssign::ZExt: 1932 ExtType = ISD::ZEXTLOAD; 1933 break; 1934 case CCValAssign::AExt: 1935 ExtType = ISD::EXTLOAD; 1936 break; 1937 } 1938 1939 ArgValue = DAG.getExtLoad( 1940 ExtType, SL, VA.getLocVT(), Chain, FIN, 1941 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1942 MemVT); 1943 return ArgValue; 1944 } 1945 1946 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1947 const SIMachineFunctionInfo &MFI, 1948 EVT VT, 1949 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1950 const ArgDescriptor *Reg; 1951 const TargetRegisterClass *RC; 1952 LLT Ty; 1953 1954 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1955 if (!Reg) { 1956 if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) { 1957 // It's possible for a kernarg intrinsic call to appear in a kernel with 1958 // no allocated segment, in which case we do not add the user sgpr 1959 // argument, so just return null. 1960 return DAG.getConstant(0, SDLoc(), VT); 1961 } 1962 1963 // It's undefined behavior if a function marked with the amdgpu-no-* 1964 // attributes uses the corresponding intrinsic. 1965 return DAG.getUNDEF(VT); 1966 } 1967 1968 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1969 } 1970 1971 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1972 CallingConv::ID CallConv, 1973 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped, 1974 FunctionType *FType, 1975 SIMachineFunctionInfo *Info) { 1976 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1977 const ISD::InputArg *Arg = &Ins[I]; 1978 1979 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1980 "vector type argument should have been split"); 1981 1982 // First check if it's a PS input addr. 1983 if (CallConv == CallingConv::AMDGPU_PS && 1984 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1985 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1986 1987 // Inconveniently only the first part of the split is marked as isSplit, 1988 // so skip to the end. We only want to increment PSInputNum once for the 1989 // entire split argument. 1990 if (Arg->Flags.isSplit()) { 1991 while (!Arg->Flags.isSplitEnd()) { 1992 assert((!Arg->VT.isVector() || 1993 Arg->VT.getScalarSizeInBits() == 16) && 1994 "unexpected vector split in ps argument type"); 1995 if (!SkipArg) 1996 Splits.push_back(*Arg); 1997 Arg = &Ins[++I]; 1998 } 1999 } 2000 2001 if (SkipArg) { 2002 // We can safely skip PS inputs. 2003 Skipped.set(Arg->getOrigArgIndex()); 2004 ++PSInputNum; 2005 continue; 2006 } 2007 2008 Info->markPSInputAllocated(PSInputNum); 2009 if (Arg->Used) 2010 Info->markPSInputEnabled(PSInputNum); 2011 2012 ++PSInputNum; 2013 } 2014 2015 Splits.push_back(*Arg); 2016 } 2017 } 2018 2019 // Allocate special inputs passed in VGPRs. 2020 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 2021 MachineFunction &MF, 2022 const SIRegisterInfo &TRI, 2023 SIMachineFunctionInfo &Info) const { 2024 const LLT S32 = LLT::scalar(32); 2025 MachineRegisterInfo &MRI = MF.getRegInfo(); 2026 2027 if (Info.hasWorkItemIDX()) { 2028 Register Reg = AMDGPU::VGPR0; 2029 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 2030 2031 CCInfo.AllocateReg(Reg); 2032 unsigned Mask = (Subtarget->hasPackedTID() && 2033 Info.hasWorkItemIDY()) ? 0x3ff : ~0u; 2034 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 2035 } 2036 2037 if (Info.hasWorkItemIDY()) { 2038 assert(Info.hasWorkItemIDX()); 2039 if (Subtarget->hasPackedTID()) { 2040 Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0, 2041 0x3ff << 10)); 2042 } else { 2043 unsigned Reg = AMDGPU::VGPR1; 2044 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 2045 2046 CCInfo.AllocateReg(Reg); 2047 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 2048 } 2049 } 2050 2051 if (Info.hasWorkItemIDZ()) { 2052 assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY()); 2053 if (Subtarget->hasPackedTID()) { 2054 Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0, 2055 0x3ff << 20)); 2056 } else { 2057 unsigned Reg = AMDGPU::VGPR2; 2058 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 2059 2060 CCInfo.AllocateReg(Reg); 2061 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 2062 } 2063 } 2064 } 2065 2066 // Try to allocate a VGPR at the end of the argument list, or if no argument 2067 // VGPRs are left allocating a stack slot. 2068 // If \p Mask is is given it indicates bitfield position in the register. 2069 // If \p Arg is given use it with new ]p Mask instead of allocating new. 2070 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 2071 ArgDescriptor Arg = ArgDescriptor()) { 2072 if (Arg.isSet()) 2073 return ArgDescriptor::createArg(Arg, Mask); 2074 2075 ArrayRef<MCPhysReg> ArgVGPRs 2076 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 2077 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 2078 if (RegIdx == ArgVGPRs.size()) { 2079 // Spill to stack required. 2080 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 2081 2082 return ArgDescriptor::createStack(Offset, Mask); 2083 } 2084 2085 unsigned Reg = ArgVGPRs[RegIdx]; 2086 Reg = CCInfo.AllocateReg(Reg); 2087 assert(Reg != AMDGPU::NoRegister); 2088 2089 MachineFunction &MF = CCInfo.getMachineFunction(); 2090 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 2091 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 2092 return ArgDescriptor::createRegister(Reg, Mask); 2093 } 2094 2095 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 2096 const TargetRegisterClass *RC, 2097 unsigned NumArgRegs) { 2098 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 2099 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 2100 if (RegIdx == ArgSGPRs.size()) 2101 report_fatal_error("ran out of SGPRs for arguments"); 2102 2103 unsigned Reg = ArgSGPRs[RegIdx]; 2104 Reg = CCInfo.AllocateReg(Reg); 2105 assert(Reg != AMDGPU::NoRegister); 2106 2107 MachineFunction &MF = CCInfo.getMachineFunction(); 2108 MF.addLiveIn(Reg, RC); 2109 return ArgDescriptor::createRegister(Reg); 2110 } 2111 2112 // If this has a fixed position, we still should allocate the register in the 2113 // CCInfo state. Technically we could get away with this for values passed 2114 // outside of the normal argument range. 2115 static void allocateFixedSGPRInputImpl(CCState &CCInfo, 2116 const TargetRegisterClass *RC, 2117 MCRegister Reg) { 2118 Reg = CCInfo.AllocateReg(Reg); 2119 assert(Reg != AMDGPU::NoRegister); 2120 MachineFunction &MF = CCInfo.getMachineFunction(); 2121 MF.addLiveIn(Reg, RC); 2122 } 2123 2124 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) { 2125 if (Arg) { 2126 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 2127 Arg.getRegister()); 2128 } else 2129 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 2130 } 2131 2132 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) { 2133 if (Arg) { 2134 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 2135 Arg.getRegister()); 2136 } else 2137 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 2138 } 2139 2140 /// Allocate implicit function VGPR arguments at the end of allocated user 2141 /// arguments. 2142 void SITargetLowering::allocateSpecialInputVGPRs( 2143 CCState &CCInfo, MachineFunction &MF, 2144 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 2145 const unsigned Mask = 0x3ff; 2146 ArgDescriptor Arg; 2147 2148 if (Info.hasWorkItemIDX()) { 2149 Arg = allocateVGPR32Input(CCInfo, Mask); 2150 Info.setWorkItemIDX(Arg); 2151 } 2152 2153 if (Info.hasWorkItemIDY()) { 2154 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 2155 Info.setWorkItemIDY(Arg); 2156 } 2157 2158 if (Info.hasWorkItemIDZ()) 2159 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 2160 } 2161 2162 /// Allocate implicit function VGPR arguments in fixed registers. 2163 void SITargetLowering::allocateSpecialInputVGPRsFixed( 2164 CCState &CCInfo, MachineFunction &MF, 2165 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 2166 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 2167 if (!Reg) 2168 report_fatal_error("failed to allocated VGPR for implicit arguments"); 2169 2170 const unsigned Mask = 0x3ff; 2171 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 2172 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 2173 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 2174 } 2175 2176 void SITargetLowering::allocateSpecialInputSGPRs( 2177 CCState &CCInfo, 2178 MachineFunction &MF, 2179 const SIRegisterInfo &TRI, 2180 SIMachineFunctionInfo &Info) const { 2181 auto &ArgInfo = Info.getArgInfo(); 2182 2183 // TODO: Unify handling with private memory pointers. 2184 if (Info.hasDispatchPtr()) 2185 allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr); 2186 2187 if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5) 2188 allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr); 2189 2190 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 2191 // constant offset from the kernarg segment. 2192 if (Info.hasImplicitArgPtr()) 2193 allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr); 2194 2195 if (Info.hasDispatchID()) 2196 allocateSGPR64Input(CCInfo, ArgInfo.DispatchID); 2197 2198 // flat_scratch_init is not applicable for non-kernel functions. 2199 2200 if (Info.hasWorkGroupIDX()) 2201 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX); 2202 2203 if (Info.hasWorkGroupIDY()) 2204 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY); 2205 2206 if (Info.hasWorkGroupIDZ()) 2207 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ); 2208 } 2209 2210 // Allocate special inputs passed in user SGPRs. 2211 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 2212 MachineFunction &MF, 2213 const SIRegisterInfo &TRI, 2214 SIMachineFunctionInfo &Info) const { 2215 if (Info.hasImplicitBufferPtr()) { 2216 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 2217 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 2218 CCInfo.AllocateReg(ImplicitBufferPtrReg); 2219 } 2220 2221 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 2222 if (Info.hasPrivateSegmentBuffer()) { 2223 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 2224 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 2225 CCInfo.AllocateReg(PrivateSegmentBufferReg); 2226 } 2227 2228 if (Info.hasDispatchPtr()) { 2229 Register DispatchPtrReg = Info.addDispatchPtr(TRI); 2230 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 2231 CCInfo.AllocateReg(DispatchPtrReg); 2232 } 2233 2234 if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5) { 2235 Register QueuePtrReg = Info.addQueuePtr(TRI); 2236 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 2237 CCInfo.AllocateReg(QueuePtrReg); 2238 } 2239 2240 if (Info.hasKernargSegmentPtr()) { 2241 MachineRegisterInfo &MRI = MF.getRegInfo(); 2242 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 2243 CCInfo.AllocateReg(InputPtrReg); 2244 2245 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 2246 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 2247 } 2248 2249 if (Info.hasDispatchID()) { 2250 Register DispatchIDReg = Info.addDispatchID(TRI); 2251 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 2252 CCInfo.AllocateReg(DispatchIDReg); 2253 } 2254 2255 if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) { 2256 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI); 2257 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 2258 CCInfo.AllocateReg(FlatScratchInitReg); 2259 } 2260 2261 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 2262 // these from the dispatch pointer. 2263 } 2264 2265 // Allocate special input registers that are initialized per-wave. 2266 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 2267 MachineFunction &MF, 2268 SIMachineFunctionInfo &Info, 2269 CallingConv::ID CallConv, 2270 bool IsShader) const { 2271 if (Info.hasWorkGroupIDX()) { 2272 Register Reg = Info.addWorkGroupIDX(); 2273 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2274 CCInfo.AllocateReg(Reg); 2275 } 2276 2277 if (Info.hasWorkGroupIDY()) { 2278 Register Reg = Info.addWorkGroupIDY(); 2279 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2280 CCInfo.AllocateReg(Reg); 2281 } 2282 2283 if (Info.hasWorkGroupIDZ()) { 2284 Register Reg = Info.addWorkGroupIDZ(); 2285 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2286 CCInfo.AllocateReg(Reg); 2287 } 2288 2289 if (Info.hasWorkGroupInfo()) { 2290 Register Reg = Info.addWorkGroupInfo(); 2291 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2292 CCInfo.AllocateReg(Reg); 2293 } 2294 2295 if (Info.hasPrivateSegmentWaveByteOffset()) { 2296 // Scratch wave offset passed in system SGPR. 2297 unsigned PrivateSegmentWaveByteOffsetReg; 2298 2299 if (IsShader) { 2300 PrivateSegmentWaveByteOffsetReg = 2301 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 2302 2303 // This is true if the scratch wave byte offset doesn't have a fixed 2304 // location. 2305 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 2306 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 2307 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 2308 } 2309 } else 2310 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 2311 2312 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 2313 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 2314 } 2315 } 2316 2317 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2318 MachineFunction &MF, 2319 const SIRegisterInfo &TRI, 2320 SIMachineFunctionInfo &Info) { 2321 // Now that we've figured out where the scratch register inputs are, see if 2322 // should reserve the arguments and use them directly. 2323 MachineFrameInfo &MFI = MF.getFrameInfo(); 2324 bool HasStackObjects = MFI.hasStackObjects(); 2325 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2326 2327 // Record that we know we have non-spill stack objects so we don't need to 2328 // check all stack objects later. 2329 if (HasStackObjects) 2330 Info.setHasNonSpillStackObjects(true); 2331 2332 // Everything live out of a block is spilled with fast regalloc, so it's 2333 // almost certain that spilling will be required. 2334 if (TM.getOptLevel() == CodeGenOpt::None) 2335 HasStackObjects = true; 2336 2337 // For now assume stack access is needed in any callee functions, so we need 2338 // the scratch registers to pass in. 2339 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2340 2341 if (!ST.enableFlatScratch()) { 2342 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2343 // If we have stack objects, we unquestionably need the private buffer 2344 // resource. For the Code Object V2 ABI, this will be the first 4 user 2345 // SGPR inputs. We can reserve those and use them directly. 2346 2347 Register PrivateSegmentBufferReg = 2348 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2349 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2350 } else { 2351 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2352 // We tentatively reserve the last registers (skipping the last registers 2353 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2354 // we'll replace these with the ones immediately after those which were 2355 // really allocated. In the prologue copies will be inserted from the 2356 // argument to these reserved registers. 2357 2358 // Without HSA, relocations are used for the scratch pointer and the 2359 // buffer resource setup is always inserted in the prologue. Scratch wave 2360 // offset is still in an input SGPR. 2361 Info.setScratchRSrcReg(ReservedBufferReg); 2362 } 2363 } 2364 2365 MachineRegisterInfo &MRI = MF.getRegInfo(); 2366 2367 // For entry functions we have to set up the stack pointer if we use it, 2368 // whereas non-entry functions get this "for free". This means there is no 2369 // intrinsic advantage to using S32 over S34 in cases where we do not have 2370 // calls but do need a frame pointer (i.e. if we are requested to have one 2371 // because frame pointer elimination is disabled). To keep things simple we 2372 // only ever use S32 as the call ABI stack pointer, and so using it does not 2373 // imply we need a separate frame pointer. 2374 // 2375 // Try to use s32 as the SP, but move it if it would interfere with input 2376 // arguments. This won't work with calls though. 2377 // 2378 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2379 // registers. 2380 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2381 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2382 } else { 2383 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2384 2385 if (MFI.hasCalls()) 2386 report_fatal_error("call in graphics shader with too many input SGPRs"); 2387 2388 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2389 if (!MRI.isLiveIn(Reg)) { 2390 Info.setStackPtrOffsetReg(Reg); 2391 break; 2392 } 2393 } 2394 2395 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2396 report_fatal_error("failed to find register for SP"); 2397 } 2398 2399 // hasFP should be accurate for entry functions even before the frame is 2400 // finalized, because it does not rely on the known stack size, only 2401 // properties like whether variable sized objects are present. 2402 if (ST.getFrameLowering()->hasFP(MF)) { 2403 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2404 } 2405 } 2406 2407 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2408 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2409 return !Info->isEntryFunction(); 2410 } 2411 2412 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2413 2414 } 2415 2416 void SITargetLowering::insertCopiesSplitCSR( 2417 MachineBasicBlock *Entry, 2418 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2419 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2420 2421 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2422 if (!IStart) 2423 return; 2424 2425 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2426 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2427 MachineBasicBlock::iterator MBBI = Entry->begin(); 2428 for (const MCPhysReg *I = IStart; *I; ++I) { 2429 const TargetRegisterClass *RC = nullptr; 2430 if (AMDGPU::SReg_64RegClass.contains(*I)) 2431 RC = &AMDGPU::SGPR_64RegClass; 2432 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2433 RC = &AMDGPU::SGPR_32RegClass; 2434 else 2435 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2436 2437 Register NewVR = MRI->createVirtualRegister(RC); 2438 // Create copy from CSR to a virtual register. 2439 Entry->addLiveIn(*I); 2440 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2441 .addReg(*I); 2442 2443 // Insert the copy-back instructions right before the terminator. 2444 for (auto *Exit : Exits) 2445 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2446 TII->get(TargetOpcode::COPY), *I) 2447 .addReg(NewVR); 2448 } 2449 } 2450 2451 SDValue SITargetLowering::LowerFormalArguments( 2452 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2453 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2454 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2455 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2456 2457 MachineFunction &MF = DAG.getMachineFunction(); 2458 const Function &Fn = MF.getFunction(); 2459 FunctionType *FType = MF.getFunction().getFunctionType(); 2460 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2461 2462 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) { 2463 DiagnosticInfoUnsupported NoGraphicsHSA( 2464 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2465 DAG.getContext()->diagnose(NoGraphicsHSA); 2466 return DAG.getEntryNode(); 2467 } 2468 2469 Info->allocateModuleLDSGlobal(Fn); 2470 2471 SmallVector<ISD::InputArg, 16> Splits; 2472 SmallVector<CCValAssign, 16> ArgLocs; 2473 BitVector Skipped(Ins.size()); 2474 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2475 *DAG.getContext()); 2476 2477 bool IsGraphics = AMDGPU::isGraphics(CallConv); 2478 bool IsKernel = AMDGPU::isKernel(CallConv); 2479 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2480 2481 if (IsGraphics) { 2482 assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && 2483 (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && 2484 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2485 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2486 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2487 !Info->hasWorkItemIDZ()); 2488 } 2489 2490 if (CallConv == CallingConv::AMDGPU_PS) { 2491 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2492 2493 // At least one interpolation mode must be enabled or else the GPU will 2494 // hang. 2495 // 2496 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2497 // set PSInputAddr, the user wants to enable some bits after the compilation 2498 // based on run-time states. Since we can't know what the final PSInputEna 2499 // will look like, so we shouldn't do anything here and the user should take 2500 // responsibility for the correct programming. 2501 // 2502 // Otherwise, the following restrictions apply: 2503 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2504 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2505 // enabled too. 2506 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2507 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) { 2508 CCInfo.AllocateReg(AMDGPU::VGPR0); 2509 CCInfo.AllocateReg(AMDGPU::VGPR1); 2510 Info->markPSInputAllocated(0); 2511 Info->markPSInputEnabled(0); 2512 } 2513 if (Subtarget->isAmdPalOS()) { 2514 // For isAmdPalOS, the user does not enable some bits after compilation 2515 // based on run-time states; the register values being generated here are 2516 // the final ones set in hardware. Therefore we need to apply the 2517 // workaround to PSInputAddr and PSInputEnable together. (The case where 2518 // a bit is set in PSInputAddr but not PSInputEnable is where the 2519 // frontend set up an input arg for a particular interpolation mode, but 2520 // nothing uses that input arg. Really we should have an earlier pass 2521 // that removes such an arg.) 2522 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2523 if ((PsInputBits & 0x7F) == 0 || 2524 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1))) 2525 Info->markPSInputEnabled( 2526 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2527 } 2528 } else if (IsKernel) { 2529 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2530 } else { 2531 Splits.append(Ins.begin(), Ins.end()); 2532 } 2533 2534 if (IsEntryFunc) { 2535 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2536 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2537 } else if (!IsGraphics) { 2538 // For the fixed ABI, pass workitem IDs in the last argument register. 2539 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2540 } 2541 2542 if (IsKernel) { 2543 analyzeFormalArgumentsCompute(CCInfo, Ins); 2544 } else { 2545 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2546 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2547 } 2548 2549 SmallVector<SDValue, 16> Chains; 2550 2551 // FIXME: This is the minimum kernel argument alignment. We should improve 2552 // this to the maximum alignment of the arguments. 2553 // 2554 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2555 // kern arg offset. 2556 const Align KernelArgBaseAlign = Align(16); 2557 2558 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2559 const ISD::InputArg &Arg = Ins[i]; 2560 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2561 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2562 continue; 2563 } 2564 2565 CCValAssign &VA = ArgLocs[ArgIdx++]; 2566 MVT VT = VA.getLocVT(); 2567 2568 if (IsEntryFunc && VA.isMemLoc()) { 2569 VT = Ins[i].VT; 2570 EVT MemVT = VA.getLocVT(); 2571 2572 const uint64_t Offset = VA.getLocMemOffset(); 2573 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2574 2575 if (Arg.Flags.isByRef()) { 2576 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset); 2577 2578 const GCNTargetMachine &TM = 2579 static_cast<const GCNTargetMachine &>(getTargetMachine()); 2580 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS, 2581 Arg.Flags.getPointerAddrSpace())) { 2582 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS, 2583 Arg.Flags.getPointerAddrSpace()); 2584 } 2585 2586 InVals.push_back(Ptr); 2587 continue; 2588 } 2589 2590 SDValue Arg = lowerKernargMemParameter( 2591 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]); 2592 Chains.push_back(Arg.getValue(1)); 2593 2594 auto *ParamTy = 2595 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2596 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2597 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2598 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2599 // On SI local pointers are just offsets into LDS, so they are always 2600 // less than 16-bits. On CI and newer they could potentially be 2601 // real pointers, so we can't guarantee their size. 2602 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2603 DAG.getValueType(MVT::i16)); 2604 } 2605 2606 InVals.push_back(Arg); 2607 continue; 2608 } else if (!IsEntryFunc && VA.isMemLoc()) { 2609 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2610 InVals.push_back(Val); 2611 if (!Arg.Flags.isByVal()) 2612 Chains.push_back(Val.getValue(1)); 2613 continue; 2614 } 2615 2616 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2617 2618 Register Reg = VA.getLocReg(); 2619 const TargetRegisterClass *RC = nullptr; 2620 if (AMDGPU::VGPR_32RegClass.contains(Reg)) 2621 RC = &AMDGPU::VGPR_32RegClass; 2622 else if (AMDGPU::SGPR_32RegClass.contains(Reg)) 2623 RC = &AMDGPU::SGPR_32RegClass; 2624 else 2625 llvm_unreachable("Unexpected register class in LowerFormalArguments!"); 2626 EVT ValVT = VA.getValVT(); 2627 2628 Reg = MF.addLiveIn(Reg, RC); 2629 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2630 2631 if (Arg.Flags.isSRet()) { 2632 // The return object should be reasonably addressable. 2633 2634 // FIXME: This helps when the return is a real sret. If it is a 2635 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2636 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2637 unsigned NumBits 2638 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2639 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2640 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2641 } 2642 2643 // If this is an 8 or 16-bit value, it is really passed promoted 2644 // to 32 bits. Insert an assert[sz]ext to capture this, then 2645 // truncate to the right size. 2646 switch (VA.getLocInfo()) { 2647 case CCValAssign::Full: 2648 break; 2649 case CCValAssign::BCvt: 2650 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2651 break; 2652 case CCValAssign::SExt: 2653 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2654 DAG.getValueType(ValVT)); 2655 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2656 break; 2657 case CCValAssign::ZExt: 2658 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2659 DAG.getValueType(ValVT)); 2660 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2661 break; 2662 case CCValAssign::AExt: 2663 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2664 break; 2665 default: 2666 llvm_unreachable("Unknown loc info!"); 2667 } 2668 2669 InVals.push_back(Val); 2670 } 2671 2672 // Start adding system SGPRs. 2673 if (IsEntryFunc) { 2674 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics); 2675 } else { 2676 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2677 if (!IsGraphics) 2678 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2679 } 2680 2681 auto &ArgUsageInfo = 2682 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2683 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2684 2685 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2686 Info->setBytesInStackArgArea(StackArgSize); 2687 2688 return Chains.empty() ? Chain : 2689 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2690 } 2691 2692 // TODO: If return values can't fit in registers, we should return as many as 2693 // possible in registers before passing on stack. 2694 bool SITargetLowering::CanLowerReturn( 2695 CallingConv::ID CallConv, 2696 MachineFunction &MF, bool IsVarArg, 2697 const SmallVectorImpl<ISD::OutputArg> &Outs, 2698 LLVMContext &Context) const { 2699 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2700 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2701 // for shaders. Vector types should be explicitly handled by CC. 2702 if (AMDGPU::isEntryFunctionCC(CallConv)) 2703 return true; 2704 2705 SmallVector<CCValAssign, 16> RVLocs; 2706 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2707 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2708 } 2709 2710 SDValue 2711 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2712 bool isVarArg, 2713 const SmallVectorImpl<ISD::OutputArg> &Outs, 2714 const SmallVectorImpl<SDValue> &OutVals, 2715 const SDLoc &DL, SelectionDAG &DAG) const { 2716 MachineFunction &MF = DAG.getMachineFunction(); 2717 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2718 2719 if (AMDGPU::isKernel(CallConv)) { 2720 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2721 OutVals, DL, DAG); 2722 } 2723 2724 bool IsShader = AMDGPU::isShader(CallConv); 2725 2726 Info->setIfReturnsVoid(Outs.empty()); 2727 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2728 2729 // CCValAssign - represent the assignment of the return value to a location. 2730 SmallVector<CCValAssign, 48> RVLocs; 2731 SmallVector<ISD::OutputArg, 48> Splits; 2732 2733 // CCState - Info about the registers and stack slots. 2734 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2735 *DAG.getContext()); 2736 2737 // Analyze outgoing return values. 2738 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2739 2740 SDValue Flag; 2741 SmallVector<SDValue, 48> RetOps; 2742 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2743 2744 // Copy the result values into the output registers. 2745 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2746 ++I, ++RealRVLocIdx) { 2747 CCValAssign &VA = RVLocs[I]; 2748 assert(VA.isRegLoc() && "Can only return in registers!"); 2749 // TODO: Partially return in registers if return values don't fit. 2750 SDValue Arg = OutVals[RealRVLocIdx]; 2751 2752 // Copied from other backends. 2753 switch (VA.getLocInfo()) { 2754 case CCValAssign::Full: 2755 break; 2756 case CCValAssign::BCvt: 2757 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2758 break; 2759 case CCValAssign::SExt: 2760 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2761 break; 2762 case CCValAssign::ZExt: 2763 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2764 break; 2765 case CCValAssign::AExt: 2766 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2767 break; 2768 default: 2769 llvm_unreachable("Unknown loc info!"); 2770 } 2771 2772 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2773 Flag = Chain.getValue(1); 2774 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2775 } 2776 2777 // FIXME: Does sret work properly? 2778 if (!Info->isEntryFunction()) { 2779 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2780 const MCPhysReg *I = 2781 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2782 if (I) { 2783 for (; *I; ++I) { 2784 if (AMDGPU::SReg_64RegClass.contains(*I)) 2785 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2786 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2787 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2788 else 2789 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2790 } 2791 } 2792 } 2793 2794 // Update chain and glue. 2795 RetOps[0] = Chain; 2796 if (Flag.getNode()) 2797 RetOps.push_back(Flag); 2798 2799 unsigned Opc = AMDGPUISD::ENDPGM; 2800 if (!IsWaveEnd) 2801 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2802 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2803 } 2804 2805 SDValue SITargetLowering::LowerCallResult( 2806 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2807 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2808 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2809 SDValue ThisVal) const { 2810 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2811 2812 // Assign locations to each value returned by this call. 2813 SmallVector<CCValAssign, 16> RVLocs; 2814 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2815 *DAG.getContext()); 2816 CCInfo.AnalyzeCallResult(Ins, RetCC); 2817 2818 // Copy all of the result registers out of their specified physreg. 2819 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2820 CCValAssign VA = RVLocs[i]; 2821 SDValue Val; 2822 2823 if (VA.isRegLoc()) { 2824 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2825 Chain = Val.getValue(1); 2826 InFlag = Val.getValue(2); 2827 } else if (VA.isMemLoc()) { 2828 report_fatal_error("TODO: return values in memory"); 2829 } else 2830 llvm_unreachable("unknown argument location type"); 2831 2832 switch (VA.getLocInfo()) { 2833 case CCValAssign::Full: 2834 break; 2835 case CCValAssign::BCvt: 2836 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2837 break; 2838 case CCValAssign::ZExt: 2839 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2840 DAG.getValueType(VA.getValVT())); 2841 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2842 break; 2843 case CCValAssign::SExt: 2844 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2845 DAG.getValueType(VA.getValVT())); 2846 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2847 break; 2848 case CCValAssign::AExt: 2849 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2850 break; 2851 default: 2852 llvm_unreachable("Unknown loc info!"); 2853 } 2854 2855 InVals.push_back(Val); 2856 } 2857 2858 return Chain; 2859 } 2860 2861 // Add code to pass special inputs required depending on used features separate 2862 // from the explicit user arguments present in the IR. 2863 void SITargetLowering::passSpecialInputs( 2864 CallLoweringInfo &CLI, 2865 CCState &CCInfo, 2866 const SIMachineFunctionInfo &Info, 2867 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2868 SmallVectorImpl<SDValue> &MemOpChains, 2869 SDValue Chain) const { 2870 // If we don't have a call site, this was a call inserted by 2871 // legalization. These can never use special inputs. 2872 if (!CLI.CB) 2873 return; 2874 2875 SelectionDAG &DAG = CLI.DAG; 2876 const SDLoc &DL = CLI.DL; 2877 const Function &F = DAG.getMachineFunction().getFunction(); 2878 2879 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2880 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2881 2882 const AMDGPUFunctionArgInfo *CalleeArgInfo 2883 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2884 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2885 auto &ArgUsageInfo = 2886 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2887 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2888 } 2889 2890 // TODO: Unify with private memory register handling. This is complicated by 2891 // the fact that at least in kernels, the input argument is not necessarily 2892 // in the same location as the input. 2893 static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue, 2894 StringLiteral> ImplicitAttrs[] = { 2895 {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"}, 2896 {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" }, 2897 {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"}, 2898 {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"}, 2899 {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"}, 2900 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"}, 2901 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"} 2902 }; 2903 2904 for (auto Attr : ImplicitAttrs) { 2905 const ArgDescriptor *OutgoingArg; 2906 const TargetRegisterClass *ArgRC; 2907 LLT ArgTy; 2908 2909 AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first; 2910 2911 // If the callee does not use the attribute value, skip copying the value. 2912 if (CLI.CB->hasFnAttr(Attr.second)) 2913 continue; 2914 2915 std::tie(OutgoingArg, ArgRC, ArgTy) = 2916 CalleeArgInfo->getPreloadedValue(InputID); 2917 if (!OutgoingArg) 2918 continue; 2919 2920 const ArgDescriptor *IncomingArg; 2921 const TargetRegisterClass *IncomingArgRC; 2922 LLT Ty; 2923 std::tie(IncomingArg, IncomingArgRC, Ty) = 2924 CallerArgInfo.getPreloadedValue(InputID); 2925 assert(IncomingArgRC == ArgRC); 2926 2927 // All special arguments are ints for now. 2928 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2929 SDValue InputReg; 2930 2931 if (IncomingArg) { 2932 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2933 } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) { 2934 // The implicit arg ptr is special because it doesn't have a corresponding 2935 // input for kernels, and is computed from the kernarg segment pointer. 2936 InputReg = getImplicitArgPtr(DAG, DL); 2937 } else { 2938 // We may have proven the input wasn't needed, although the ABI is 2939 // requiring it. We just need to allocate the register appropriately. 2940 InputReg = DAG.getUNDEF(ArgVT); 2941 } 2942 2943 if (OutgoingArg->isRegister()) { 2944 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2945 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2946 report_fatal_error("failed to allocate implicit input argument"); 2947 } else { 2948 unsigned SpecialArgOffset = 2949 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2950 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2951 SpecialArgOffset); 2952 MemOpChains.push_back(ArgStore); 2953 } 2954 } 2955 2956 // Pack workitem IDs into a single register or pass it as is if already 2957 // packed. 2958 const ArgDescriptor *OutgoingArg; 2959 const TargetRegisterClass *ArgRC; 2960 LLT Ty; 2961 2962 std::tie(OutgoingArg, ArgRC, Ty) = 2963 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2964 if (!OutgoingArg) 2965 std::tie(OutgoingArg, ArgRC, Ty) = 2966 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2967 if (!OutgoingArg) 2968 std::tie(OutgoingArg, ArgRC, Ty) = 2969 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2970 if (!OutgoingArg) 2971 return; 2972 2973 const ArgDescriptor *IncomingArgX = std::get<0>( 2974 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2975 const ArgDescriptor *IncomingArgY = std::get<0>( 2976 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2977 const ArgDescriptor *IncomingArgZ = std::get<0>( 2978 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2979 2980 SDValue InputReg; 2981 SDLoc SL; 2982 2983 const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x"); 2984 const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y"); 2985 const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z"); 2986 2987 // If incoming ids are not packed we need to pack them. 2988 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX && 2989 NeedWorkItemIDX) { 2990 if (Subtarget->getMaxWorkitemID(F, 0) != 0) { 2991 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2992 } else { 2993 InputReg = DAG.getConstant(0, DL, MVT::i32); 2994 } 2995 } 2996 2997 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY && 2998 NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) { 2999 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 3000 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 3001 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 3002 InputReg = InputReg.getNode() ? 3003 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 3004 } 3005 3006 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ && 3007 NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) { 3008 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 3009 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 3010 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 3011 InputReg = InputReg.getNode() ? 3012 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 3013 } 3014 3015 if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) { 3016 if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) { 3017 // We're in a situation where the outgoing function requires the workitem 3018 // ID, but the calling function does not have it (e.g a graphics function 3019 // calling a C calling convention function). This is illegal, but we need 3020 // to produce something. 3021 InputReg = DAG.getUNDEF(MVT::i32); 3022 } else { 3023 // Workitem ids are already packed, any of present incoming arguments 3024 // will carry all required fields. 3025 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 3026 IncomingArgX ? *IncomingArgX : 3027 IncomingArgY ? *IncomingArgY : 3028 *IncomingArgZ, ~0u); 3029 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 3030 } 3031 } 3032 3033 if (OutgoingArg->isRegister()) { 3034 if (InputReg) 3035 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 3036 3037 CCInfo.AllocateReg(OutgoingArg->getRegister()); 3038 } else { 3039 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 3040 if (InputReg) { 3041 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 3042 SpecialArgOffset); 3043 MemOpChains.push_back(ArgStore); 3044 } 3045 } 3046 } 3047 3048 static bool canGuaranteeTCO(CallingConv::ID CC) { 3049 return CC == CallingConv::Fast; 3050 } 3051 3052 /// Return true if we might ever do TCO for calls with this calling convention. 3053 static bool mayTailCallThisCC(CallingConv::ID CC) { 3054 switch (CC) { 3055 case CallingConv::C: 3056 case CallingConv::AMDGPU_Gfx: 3057 return true; 3058 default: 3059 return canGuaranteeTCO(CC); 3060 } 3061 } 3062 3063 bool SITargetLowering::isEligibleForTailCallOptimization( 3064 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 3065 const SmallVectorImpl<ISD::OutputArg> &Outs, 3066 const SmallVectorImpl<SDValue> &OutVals, 3067 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 3068 if (!mayTailCallThisCC(CalleeCC)) 3069 return false; 3070 3071 // For a divergent call target, we need to do a waterfall loop over the 3072 // possible callees which precludes us from using a simple jump. 3073 if (Callee->isDivergent()) 3074 return false; 3075 3076 MachineFunction &MF = DAG.getMachineFunction(); 3077 const Function &CallerF = MF.getFunction(); 3078 CallingConv::ID CallerCC = CallerF.getCallingConv(); 3079 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3080 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 3081 3082 // Kernels aren't callable, and don't have a live in return address so it 3083 // doesn't make sense to do a tail call with entry functions. 3084 if (!CallerPreserved) 3085 return false; 3086 3087 bool CCMatch = CallerCC == CalleeCC; 3088 3089 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 3090 if (canGuaranteeTCO(CalleeCC) && CCMatch) 3091 return true; 3092 return false; 3093 } 3094 3095 // TODO: Can we handle var args? 3096 if (IsVarArg) 3097 return false; 3098 3099 for (const Argument &Arg : CallerF.args()) { 3100 if (Arg.hasByValAttr()) 3101 return false; 3102 } 3103 3104 LLVMContext &Ctx = *DAG.getContext(); 3105 3106 // Check that the call results are passed in the same way. 3107 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 3108 CCAssignFnForCall(CalleeCC, IsVarArg), 3109 CCAssignFnForCall(CallerCC, IsVarArg))) 3110 return false; 3111 3112 // The callee has to preserve all registers the caller needs to preserve. 3113 if (!CCMatch) { 3114 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 3115 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 3116 return false; 3117 } 3118 3119 // Nothing more to check if the callee is taking no arguments. 3120 if (Outs.empty()) 3121 return true; 3122 3123 SmallVector<CCValAssign, 16> ArgLocs; 3124 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 3125 3126 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 3127 3128 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 3129 // If the stack arguments for this call do not fit into our own save area then 3130 // the call cannot be made tail. 3131 // TODO: Is this really necessary? 3132 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 3133 return false; 3134 3135 const MachineRegisterInfo &MRI = MF.getRegInfo(); 3136 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 3137 } 3138 3139 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 3140 if (!CI->isTailCall()) 3141 return false; 3142 3143 const Function *ParentFn = CI->getParent()->getParent(); 3144 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 3145 return false; 3146 return true; 3147 } 3148 3149 // The wave scratch offset register is used as the global base pointer. 3150 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 3151 SmallVectorImpl<SDValue> &InVals) const { 3152 SelectionDAG &DAG = CLI.DAG; 3153 const SDLoc &DL = CLI.DL; 3154 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 3155 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 3156 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 3157 SDValue Chain = CLI.Chain; 3158 SDValue Callee = CLI.Callee; 3159 bool &IsTailCall = CLI.IsTailCall; 3160 CallingConv::ID CallConv = CLI.CallConv; 3161 bool IsVarArg = CLI.IsVarArg; 3162 bool IsSibCall = false; 3163 bool IsThisReturn = false; 3164 MachineFunction &MF = DAG.getMachineFunction(); 3165 3166 if (Callee.isUndef() || isNullConstant(Callee)) { 3167 if (!CLI.IsTailCall) { 3168 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 3169 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 3170 } 3171 3172 return Chain; 3173 } 3174 3175 if (IsVarArg) { 3176 return lowerUnhandledCall(CLI, InVals, 3177 "unsupported call to variadic function "); 3178 } 3179 3180 if (!CLI.CB) 3181 report_fatal_error("unsupported libcall legalization"); 3182 3183 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 3184 return lowerUnhandledCall(CLI, InVals, 3185 "unsupported required tail call to function "); 3186 } 3187 3188 if (AMDGPU::isShader(CallConv)) { 3189 // Note the issue is with the CC of the called function, not of the call 3190 // itself. 3191 return lowerUnhandledCall(CLI, InVals, 3192 "unsupported call to a shader function "); 3193 } 3194 3195 if (AMDGPU::isShader(MF.getFunction().getCallingConv()) && 3196 CallConv != CallingConv::AMDGPU_Gfx) { 3197 // Only allow calls with specific calling conventions. 3198 return lowerUnhandledCall(CLI, InVals, 3199 "unsupported calling convention for call from " 3200 "graphics shader of function "); 3201 } 3202 3203 if (IsTailCall) { 3204 IsTailCall = isEligibleForTailCallOptimization( 3205 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 3206 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 3207 report_fatal_error("failed to perform tail call elimination on a call " 3208 "site marked musttail"); 3209 } 3210 3211 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 3212 3213 // A sibling call is one where we're under the usual C ABI and not planning 3214 // to change that but can still do a tail call: 3215 if (!TailCallOpt && IsTailCall) 3216 IsSibCall = true; 3217 3218 if (IsTailCall) 3219 ++NumTailCalls; 3220 } 3221 3222 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3223 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3224 SmallVector<SDValue, 8> MemOpChains; 3225 3226 // Analyze operands of the call, assigning locations to each operand. 3227 SmallVector<CCValAssign, 16> ArgLocs; 3228 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 3229 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 3230 3231 if (CallConv != CallingConv::AMDGPU_Gfx) { 3232 // With a fixed ABI, allocate fixed registers before user arguments. 3233 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3234 } 3235 3236 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 3237 3238 // Get a count of how many bytes are to be pushed on the stack. 3239 unsigned NumBytes = CCInfo.getNextStackOffset(); 3240 3241 if (IsSibCall) { 3242 // Since we're not changing the ABI to make this a tail call, the memory 3243 // operands are already available in the caller's incoming argument space. 3244 NumBytes = 0; 3245 } 3246 3247 // FPDiff is the byte offset of the call's argument area from the callee's. 3248 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3249 // by this amount for a tail call. In a sibling call it must be 0 because the 3250 // caller will deallocate the entire stack and the callee still expects its 3251 // arguments to begin at SP+0. Completely unused for non-tail calls. 3252 int32_t FPDiff = 0; 3253 MachineFrameInfo &MFI = MF.getFrameInfo(); 3254 3255 // Adjust the stack pointer for the new arguments... 3256 // These operations are automatically eliminated by the prolog/epilog pass 3257 if (!IsSibCall) { 3258 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 3259 3260 if (!Subtarget->enableFlatScratch()) { 3261 SmallVector<SDValue, 4> CopyFromChains; 3262 3263 // In the HSA case, this should be an identity copy. 3264 SDValue ScratchRSrcReg 3265 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 3266 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 3267 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 3268 Chain = DAG.getTokenFactor(DL, CopyFromChains); 3269 } 3270 } 3271 3272 MVT PtrVT = MVT::i32; 3273 3274 // Walk the register/memloc assignments, inserting copies/loads. 3275 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3276 CCValAssign &VA = ArgLocs[i]; 3277 SDValue Arg = OutVals[i]; 3278 3279 // Promote the value if needed. 3280 switch (VA.getLocInfo()) { 3281 case CCValAssign::Full: 3282 break; 3283 case CCValAssign::BCvt: 3284 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3285 break; 3286 case CCValAssign::ZExt: 3287 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3288 break; 3289 case CCValAssign::SExt: 3290 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3291 break; 3292 case CCValAssign::AExt: 3293 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3294 break; 3295 case CCValAssign::FPExt: 3296 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3297 break; 3298 default: 3299 llvm_unreachable("Unknown loc info!"); 3300 } 3301 3302 if (VA.isRegLoc()) { 3303 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3304 } else { 3305 assert(VA.isMemLoc()); 3306 3307 SDValue DstAddr; 3308 MachinePointerInfo DstInfo; 3309 3310 unsigned LocMemOffset = VA.getLocMemOffset(); 3311 int32_t Offset = LocMemOffset; 3312 3313 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3314 MaybeAlign Alignment; 3315 3316 if (IsTailCall) { 3317 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3318 unsigned OpSize = Flags.isByVal() ? 3319 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3320 3321 // FIXME: We can have better than the minimum byval required alignment. 3322 Alignment = 3323 Flags.isByVal() 3324 ? Flags.getNonZeroByValAlign() 3325 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3326 3327 Offset = Offset + FPDiff; 3328 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3329 3330 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3331 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3332 3333 // Make sure any stack arguments overlapping with where we're storing 3334 // are loaded before this eventual operation. Otherwise they'll be 3335 // clobbered. 3336 3337 // FIXME: Why is this really necessary? This seems to just result in a 3338 // lot of code to copy the stack and write them back to the same 3339 // locations, which are supposed to be immutable? 3340 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3341 } else { 3342 // Stores to the argument stack area are relative to the stack pointer. 3343 SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(), 3344 MVT::i32); 3345 DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff); 3346 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3347 Alignment = 3348 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3349 } 3350 3351 if (Outs[i].Flags.isByVal()) { 3352 SDValue SizeNode = 3353 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3354 SDValue Cpy = 3355 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3356 Outs[i].Flags.getNonZeroByValAlign(), 3357 /*isVol = */ false, /*AlwaysInline = */ true, 3358 /*isTailCall = */ false, DstInfo, 3359 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3360 3361 MemOpChains.push_back(Cpy); 3362 } else { 3363 SDValue Store = 3364 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment); 3365 MemOpChains.push_back(Store); 3366 } 3367 } 3368 } 3369 3370 if (!MemOpChains.empty()) 3371 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3372 3373 // Build a sequence of copy-to-reg nodes chained together with token chain 3374 // and flag operands which copy the outgoing args into the appropriate regs. 3375 SDValue InFlag; 3376 for (auto &RegToPass : RegsToPass) { 3377 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3378 RegToPass.second, InFlag); 3379 InFlag = Chain.getValue(1); 3380 } 3381 3382 3383 // We don't usually want to end the call-sequence here because we would tidy 3384 // the frame up *after* the call, however in the ABI-changing tail-call case 3385 // we've carefully laid out the parameters so that when sp is reset they'll be 3386 // in the correct location. 3387 if (IsTailCall && !IsSibCall) { 3388 Chain = DAG.getCALLSEQ_END(Chain, 3389 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3390 DAG.getTargetConstant(0, DL, MVT::i32), 3391 InFlag, DL); 3392 InFlag = Chain.getValue(1); 3393 } 3394 3395 std::vector<SDValue> Ops; 3396 Ops.push_back(Chain); 3397 Ops.push_back(Callee); 3398 // Add a redundant copy of the callee global which will not be legalized, as 3399 // we need direct access to the callee later. 3400 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3401 const GlobalValue *GV = GSD->getGlobal(); 3402 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3403 } else { 3404 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3405 } 3406 3407 if (IsTailCall) { 3408 // Each tail call may have to adjust the stack by a different amount, so 3409 // this information must travel along with the operation for eventual 3410 // consumption by emitEpilogue. 3411 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3412 } 3413 3414 // Add argument registers to the end of the list so that they are known live 3415 // into the call. 3416 for (auto &RegToPass : RegsToPass) { 3417 Ops.push_back(DAG.getRegister(RegToPass.first, 3418 RegToPass.second.getValueType())); 3419 } 3420 3421 // Add a register mask operand representing the call-preserved registers. 3422 3423 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3424 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3425 assert(Mask && "Missing call preserved mask for calling convention"); 3426 Ops.push_back(DAG.getRegisterMask(Mask)); 3427 3428 if (InFlag.getNode()) 3429 Ops.push_back(InFlag); 3430 3431 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3432 3433 // If we're doing a tall call, use a TC_RETURN here rather than an 3434 // actual call instruction. 3435 if (IsTailCall) { 3436 MFI.setHasTailCall(); 3437 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3438 } 3439 3440 // Returns a chain and a flag for retval copy to use. 3441 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3442 Chain = Call.getValue(0); 3443 InFlag = Call.getValue(1); 3444 3445 uint64_t CalleePopBytes = NumBytes; 3446 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3447 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3448 InFlag, DL); 3449 if (!Ins.empty()) 3450 InFlag = Chain.getValue(1); 3451 3452 // Handle result values, copying them out of physregs into vregs that we 3453 // return. 3454 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3455 InVals, IsThisReturn, 3456 IsThisReturn ? OutVals[0] : SDValue()); 3457 } 3458 3459 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3460 // except for applying the wave size scale to the increment amount. 3461 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3462 SDValue Op, SelectionDAG &DAG) const { 3463 const MachineFunction &MF = DAG.getMachineFunction(); 3464 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3465 3466 SDLoc dl(Op); 3467 EVT VT = Op.getValueType(); 3468 SDValue Tmp1 = Op; 3469 SDValue Tmp2 = Op.getValue(1); 3470 SDValue Tmp3 = Op.getOperand(2); 3471 SDValue Chain = Tmp1.getOperand(0); 3472 3473 Register SPReg = Info->getStackPtrOffsetReg(); 3474 3475 // Chain the dynamic stack allocation so that it doesn't modify the stack 3476 // pointer when other instructions are using the stack. 3477 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3478 3479 SDValue Size = Tmp2.getOperand(1); 3480 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3481 Chain = SP.getValue(1); 3482 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3483 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3484 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3485 unsigned Opc = 3486 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3487 ISD::ADD : ISD::SUB; 3488 3489 SDValue ScaledSize = DAG.getNode( 3490 ISD::SHL, dl, VT, Size, 3491 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3492 3493 Align StackAlign = TFL->getStackAlign(); 3494 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3495 if (Alignment && *Alignment > StackAlign) { 3496 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3497 DAG.getConstant(-(uint64_t)Alignment->value() 3498 << ST.getWavefrontSizeLog2(), 3499 dl, VT)); 3500 } 3501 3502 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3503 Tmp2 = DAG.getCALLSEQ_END( 3504 Chain, DAG.getIntPtrConstant(0, dl, true), 3505 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3506 3507 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3508 } 3509 3510 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3511 SelectionDAG &DAG) const { 3512 // We only handle constant sizes here to allow non-entry block, static sized 3513 // allocas. A truly dynamic value is more difficult to support because we 3514 // don't know if the size value is uniform or not. If the size isn't uniform, 3515 // we would need to do a wave reduction to get the maximum size to know how 3516 // much to increment the uniform stack pointer. 3517 SDValue Size = Op.getOperand(1); 3518 if (isa<ConstantSDNode>(Size)) 3519 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3520 3521 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3522 } 3523 3524 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3525 const MachineFunction &MF) const { 3526 Register Reg = StringSwitch<Register>(RegName) 3527 .Case("m0", AMDGPU::M0) 3528 .Case("exec", AMDGPU::EXEC) 3529 .Case("exec_lo", AMDGPU::EXEC_LO) 3530 .Case("exec_hi", AMDGPU::EXEC_HI) 3531 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3532 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3533 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3534 .Default(Register()); 3535 3536 if (Reg == AMDGPU::NoRegister) { 3537 report_fatal_error(Twine("invalid register name \"" 3538 + StringRef(RegName) + "\".")); 3539 3540 } 3541 3542 if (!Subtarget->hasFlatScrRegister() && 3543 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3544 report_fatal_error(Twine("invalid register \"" 3545 + StringRef(RegName) + "\" for subtarget.")); 3546 } 3547 3548 switch (Reg) { 3549 case AMDGPU::M0: 3550 case AMDGPU::EXEC_LO: 3551 case AMDGPU::EXEC_HI: 3552 case AMDGPU::FLAT_SCR_LO: 3553 case AMDGPU::FLAT_SCR_HI: 3554 if (VT.getSizeInBits() == 32) 3555 return Reg; 3556 break; 3557 case AMDGPU::EXEC: 3558 case AMDGPU::FLAT_SCR: 3559 if (VT.getSizeInBits() == 64) 3560 return Reg; 3561 break; 3562 default: 3563 llvm_unreachable("missing register type checking"); 3564 } 3565 3566 report_fatal_error(Twine("invalid type for register \"" 3567 + StringRef(RegName) + "\".")); 3568 } 3569 3570 // If kill is not the last instruction, split the block so kill is always a 3571 // proper terminator. 3572 MachineBasicBlock * 3573 SITargetLowering::splitKillBlock(MachineInstr &MI, 3574 MachineBasicBlock *BB) const { 3575 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/); 3576 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3577 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3578 return SplitBB; 3579 } 3580 3581 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3582 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3583 // be the first instruction in the remainder block. 3584 // 3585 /// \returns { LoopBody, Remainder } 3586 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3587 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3588 MachineFunction *MF = MBB.getParent(); 3589 MachineBasicBlock::iterator I(&MI); 3590 3591 // To insert the loop we need to split the block. Move everything after this 3592 // point to a new block, and insert a new empty block between the two. 3593 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3594 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3595 MachineFunction::iterator MBBI(MBB); 3596 ++MBBI; 3597 3598 MF->insert(MBBI, LoopBB); 3599 MF->insert(MBBI, RemainderBB); 3600 3601 LoopBB->addSuccessor(LoopBB); 3602 LoopBB->addSuccessor(RemainderBB); 3603 3604 // Move the rest of the block into a new block. 3605 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3606 3607 if (InstInLoop) { 3608 auto Next = std::next(I); 3609 3610 // Move instruction to loop body. 3611 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3612 3613 // Move the rest of the block. 3614 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3615 } else { 3616 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3617 } 3618 3619 MBB.addSuccessor(LoopBB); 3620 3621 return std::make_pair(LoopBB, RemainderBB); 3622 } 3623 3624 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3625 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3626 MachineBasicBlock *MBB = MI.getParent(); 3627 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3628 auto I = MI.getIterator(); 3629 auto E = std::next(I); 3630 3631 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3632 .addImm(0); 3633 3634 MIBundleBuilder Bundler(*MBB, I, E); 3635 finalizeBundle(*MBB, Bundler.begin()); 3636 } 3637 3638 MachineBasicBlock * 3639 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3640 MachineBasicBlock *BB) const { 3641 const DebugLoc &DL = MI.getDebugLoc(); 3642 3643 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3644 3645 MachineBasicBlock *LoopBB; 3646 MachineBasicBlock *RemainderBB; 3647 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3648 3649 // Apparently kill flags are only valid if the def is in the same block? 3650 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3651 Src->setIsKill(false); 3652 3653 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3654 3655 MachineBasicBlock::iterator I = LoopBB->end(); 3656 3657 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3658 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3659 3660 // Clear TRAP_STS.MEM_VIOL 3661 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3662 .addImm(0) 3663 .addImm(EncodedReg); 3664 3665 bundleInstWithWaitcnt(MI); 3666 3667 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3668 3669 // Load and check TRAP_STS.MEM_VIOL 3670 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3671 .addImm(EncodedReg); 3672 3673 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3674 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3675 .addReg(Reg, RegState::Kill) 3676 .addImm(0); 3677 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3678 .addMBB(LoopBB); 3679 3680 return RemainderBB; 3681 } 3682 3683 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3684 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3685 // will only do one iteration. In the worst case, this will loop 64 times. 3686 // 3687 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3688 static MachineBasicBlock::iterator 3689 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI, 3690 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB, 3691 const DebugLoc &DL, const MachineOperand &Idx, 3692 unsigned InitReg, unsigned ResultReg, unsigned PhiReg, 3693 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode, 3694 Register &SGPRIdxReg) { 3695 3696 MachineFunction *MF = OrigBB.getParent(); 3697 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3698 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3699 MachineBasicBlock::iterator I = LoopBB.begin(); 3700 3701 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3702 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3703 Register NewExec = MRI.createVirtualRegister(BoolRC); 3704 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3705 Register CondReg = MRI.createVirtualRegister(BoolRC); 3706 3707 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3708 .addReg(InitReg) 3709 .addMBB(&OrigBB) 3710 .addReg(ResultReg) 3711 .addMBB(&LoopBB); 3712 3713 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3714 .addReg(InitSaveExecReg) 3715 .addMBB(&OrigBB) 3716 .addReg(NewExec) 3717 .addMBB(&LoopBB); 3718 3719 // Read the next variant <- also loop target. 3720 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3721 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef())); 3722 3723 // Compare the just read M0 value to all possible Idx values. 3724 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3725 .addReg(CurrentIdxReg) 3726 .addReg(Idx.getReg(), 0, Idx.getSubReg()); 3727 3728 // Update EXEC, save the original EXEC value to VCC. 3729 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3730 : AMDGPU::S_AND_SAVEEXEC_B64), 3731 NewExec) 3732 .addReg(CondReg, RegState::Kill); 3733 3734 MRI.setSimpleHint(NewExec, CondReg); 3735 3736 if (UseGPRIdxMode) { 3737 if (Offset == 0) { 3738 SGPRIdxReg = CurrentIdxReg; 3739 } else { 3740 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3741 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg) 3742 .addReg(CurrentIdxReg, RegState::Kill) 3743 .addImm(Offset); 3744 } 3745 } else { 3746 // Move index from VCC into M0 3747 if (Offset == 0) { 3748 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3749 .addReg(CurrentIdxReg, RegState::Kill); 3750 } else { 3751 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3752 .addReg(CurrentIdxReg, RegState::Kill) 3753 .addImm(Offset); 3754 } 3755 } 3756 3757 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3758 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3759 MachineInstr *InsertPt = 3760 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3761 : AMDGPU::S_XOR_B64_term), Exec) 3762 .addReg(Exec) 3763 .addReg(NewExec); 3764 3765 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3766 // s_cbranch_scc0? 3767 3768 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3769 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3770 .addMBB(&LoopBB); 3771 3772 return InsertPt->getIterator(); 3773 } 3774 3775 // This has slightly sub-optimal regalloc when the source vector is killed by 3776 // the read. The register allocator does not understand that the kill is 3777 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3778 // subregister from it, using 1 more VGPR than necessary. This was saved when 3779 // this was expanded after register allocation. 3780 static MachineBasicBlock::iterator 3781 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI, 3782 unsigned InitResultReg, unsigned PhiReg, int Offset, 3783 bool UseGPRIdxMode, Register &SGPRIdxReg) { 3784 MachineFunction *MF = MBB.getParent(); 3785 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3786 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3787 MachineRegisterInfo &MRI = MF->getRegInfo(); 3788 const DebugLoc &DL = MI.getDebugLoc(); 3789 MachineBasicBlock::iterator I(&MI); 3790 3791 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3792 Register DstReg = MI.getOperand(0).getReg(); 3793 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3794 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3795 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3796 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3797 3798 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3799 3800 // Save the EXEC mask 3801 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3802 .addReg(Exec); 3803 3804 MachineBasicBlock *LoopBB; 3805 MachineBasicBlock *RemainderBB; 3806 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3807 3808 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3809 3810 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3811 InitResultReg, DstReg, PhiReg, TmpExec, 3812 Offset, UseGPRIdxMode, SGPRIdxReg); 3813 3814 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3815 MachineFunction::iterator MBBI(LoopBB); 3816 ++MBBI; 3817 MF->insert(MBBI, LandingPad); 3818 LoopBB->removeSuccessor(RemainderBB); 3819 LandingPad->addSuccessor(RemainderBB); 3820 LoopBB->addSuccessor(LandingPad); 3821 MachineBasicBlock::iterator First = LandingPad->begin(); 3822 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3823 .addReg(SaveExec); 3824 3825 return InsPt; 3826 } 3827 3828 // Returns subreg index, offset 3829 static std::pair<unsigned, int> 3830 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3831 const TargetRegisterClass *SuperRC, 3832 unsigned VecReg, 3833 int Offset) { 3834 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3835 3836 // Skip out of bounds offsets, or else we would end up using an undefined 3837 // register. 3838 if (Offset >= NumElts || Offset < 0) 3839 return std::make_pair(AMDGPU::sub0, Offset); 3840 3841 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3842 } 3843 3844 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3845 MachineRegisterInfo &MRI, MachineInstr &MI, 3846 int Offset) { 3847 MachineBasicBlock *MBB = MI.getParent(); 3848 const DebugLoc &DL = MI.getDebugLoc(); 3849 MachineBasicBlock::iterator I(&MI); 3850 3851 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3852 3853 assert(Idx->getReg() != AMDGPU::NoRegister); 3854 3855 if (Offset == 0) { 3856 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx); 3857 } else { 3858 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3859 .add(*Idx) 3860 .addImm(Offset); 3861 } 3862 } 3863 3864 static Register getIndirectSGPRIdx(const SIInstrInfo *TII, 3865 MachineRegisterInfo &MRI, MachineInstr &MI, 3866 int Offset) { 3867 MachineBasicBlock *MBB = MI.getParent(); 3868 const DebugLoc &DL = MI.getDebugLoc(); 3869 MachineBasicBlock::iterator I(&MI); 3870 3871 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3872 3873 if (Offset == 0) 3874 return Idx->getReg(); 3875 3876 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3877 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3878 .add(*Idx) 3879 .addImm(Offset); 3880 return Tmp; 3881 } 3882 3883 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3884 MachineBasicBlock &MBB, 3885 const GCNSubtarget &ST) { 3886 const SIInstrInfo *TII = ST.getInstrInfo(); 3887 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3888 MachineFunction *MF = MBB.getParent(); 3889 MachineRegisterInfo &MRI = MF->getRegInfo(); 3890 3891 Register Dst = MI.getOperand(0).getReg(); 3892 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3893 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3894 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3895 3896 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3897 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3898 3899 unsigned SubReg; 3900 std::tie(SubReg, Offset) 3901 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3902 3903 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3904 3905 // Check for a SGPR index. 3906 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3907 MachineBasicBlock::iterator I(&MI); 3908 const DebugLoc &DL = MI.getDebugLoc(); 3909 3910 if (UseGPRIdxMode) { 3911 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3912 // to avoid interfering with other uses, so probably requires a new 3913 // optimization pass. 3914 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3915 3916 const MCInstrDesc &GPRIDXDesc = 3917 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3918 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3919 .addReg(SrcReg) 3920 .addReg(Idx) 3921 .addImm(SubReg); 3922 } else { 3923 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3924 3925 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3926 .addReg(SrcReg, 0, SubReg) 3927 .addReg(SrcReg, RegState::Implicit); 3928 } 3929 3930 MI.eraseFromParent(); 3931 3932 return &MBB; 3933 } 3934 3935 // Control flow needs to be inserted if indexing with a VGPR. 3936 const DebugLoc &DL = MI.getDebugLoc(); 3937 MachineBasicBlock::iterator I(&MI); 3938 3939 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3940 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3941 3942 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3943 3944 Register SGPRIdxReg; 3945 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, 3946 UseGPRIdxMode, SGPRIdxReg); 3947 3948 MachineBasicBlock *LoopBB = InsPt->getParent(); 3949 3950 if (UseGPRIdxMode) { 3951 const MCInstrDesc &GPRIDXDesc = 3952 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3953 3954 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3955 .addReg(SrcReg) 3956 .addReg(SGPRIdxReg) 3957 .addImm(SubReg); 3958 } else { 3959 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3960 .addReg(SrcReg, 0, SubReg) 3961 .addReg(SrcReg, RegState::Implicit); 3962 } 3963 3964 MI.eraseFromParent(); 3965 3966 return LoopBB; 3967 } 3968 3969 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3970 MachineBasicBlock &MBB, 3971 const GCNSubtarget &ST) { 3972 const SIInstrInfo *TII = ST.getInstrInfo(); 3973 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3974 MachineFunction *MF = MBB.getParent(); 3975 MachineRegisterInfo &MRI = MF->getRegInfo(); 3976 3977 Register Dst = MI.getOperand(0).getReg(); 3978 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3979 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3980 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3981 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3982 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3983 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3984 3985 // This can be an immediate, but will be folded later. 3986 assert(Val->getReg()); 3987 3988 unsigned SubReg; 3989 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3990 SrcVec->getReg(), 3991 Offset); 3992 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3993 3994 if (Idx->getReg() == AMDGPU::NoRegister) { 3995 MachineBasicBlock::iterator I(&MI); 3996 const DebugLoc &DL = MI.getDebugLoc(); 3997 3998 assert(Offset == 0); 3999 4000 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 4001 .add(*SrcVec) 4002 .add(*Val) 4003 .addImm(SubReg); 4004 4005 MI.eraseFromParent(); 4006 return &MBB; 4007 } 4008 4009 // Check for a SGPR index. 4010 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 4011 MachineBasicBlock::iterator I(&MI); 4012 const DebugLoc &DL = MI.getDebugLoc(); 4013 4014 if (UseGPRIdxMode) { 4015 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 4016 4017 const MCInstrDesc &GPRIDXDesc = 4018 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 4019 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 4020 .addReg(SrcVec->getReg()) 4021 .add(*Val) 4022 .addReg(Idx) 4023 .addImm(SubReg); 4024 } else { 4025 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 4026 4027 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 4028 TRI.getRegSizeInBits(*VecRC), 32, false); 4029 BuildMI(MBB, I, DL, MovRelDesc, Dst) 4030 .addReg(SrcVec->getReg()) 4031 .add(*Val) 4032 .addImm(SubReg); 4033 } 4034 MI.eraseFromParent(); 4035 return &MBB; 4036 } 4037 4038 // Control flow needs to be inserted if indexing with a VGPR. 4039 if (Val->isReg()) 4040 MRI.clearKillFlags(Val->getReg()); 4041 4042 const DebugLoc &DL = MI.getDebugLoc(); 4043 4044 Register PhiReg = MRI.createVirtualRegister(VecRC); 4045 4046 Register SGPRIdxReg; 4047 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset, 4048 UseGPRIdxMode, SGPRIdxReg); 4049 MachineBasicBlock *LoopBB = InsPt->getParent(); 4050 4051 if (UseGPRIdxMode) { 4052 const MCInstrDesc &GPRIDXDesc = 4053 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 4054 4055 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 4056 .addReg(PhiReg) 4057 .add(*Val) 4058 .addReg(SGPRIdxReg) 4059 .addImm(AMDGPU::sub0); 4060 } else { 4061 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 4062 TRI.getRegSizeInBits(*VecRC), 32, false); 4063 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 4064 .addReg(PhiReg) 4065 .add(*Val) 4066 .addImm(AMDGPU::sub0); 4067 } 4068 4069 MI.eraseFromParent(); 4070 return LoopBB; 4071 } 4072 4073 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 4074 MachineInstr &MI, MachineBasicBlock *BB) const { 4075 4076 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4077 MachineFunction *MF = BB->getParent(); 4078 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 4079 4080 switch (MI.getOpcode()) { 4081 case AMDGPU::S_UADDO_PSEUDO: 4082 case AMDGPU::S_USUBO_PSEUDO: { 4083 const DebugLoc &DL = MI.getDebugLoc(); 4084 MachineOperand &Dest0 = MI.getOperand(0); 4085 MachineOperand &Dest1 = MI.getOperand(1); 4086 MachineOperand &Src0 = MI.getOperand(2); 4087 MachineOperand &Src1 = MI.getOperand(3); 4088 4089 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 4090 ? AMDGPU::S_ADD_I32 4091 : AMDGPU::S_SUB_I32; 4092 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 4093 4094 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 4095 .addImm(1) 4096 .addImm(0); 4097 4098 MI.eraseFromParent(); 4099 return BB; 4100 } 4101 case AMDGPU::S_ADD_U64_PSEUDO: 4102 case AMDGPU::S_SUB_U64_PSEUDO: { 4103 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4104 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4105 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4106 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 4107 const DebugLoc &DL = MI.getDebugLoc(); 4108 4109 MachineOperand &Dest = MI.getOperand(0); 4110 MachineOperand &Src0 = MI.getOperand(1); 4111 MachineOperand &Src1 = MI.getOperand(2); 4112 4113 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4114 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4115 4116 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 4117 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 4118 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 4119 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 4120 4121 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 4122 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 4123 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 4124 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 4125 4126 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 4127 4128 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 4129 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 4130 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 4131 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 4132 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 4133 .addReg(DestSub0) 4134 .addImm(AMDGPU::sub0) 4135 .addReg(DestSub1) 4136 .addImm(AMDGPU::sub1); 4137 MI.eraseFromParent(); 4138 return BB; 4139 } 4140 case AMDGPU::V_ADD_U64_PSEUDO: 4141 case AMDGPU::V_SUB_U64_PSEUDO: { 4142 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4143 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4144 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4145 const DebugLoc &DL = MI.getDebugLoc(); 4146 4147 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 4148 4149 MachineOperand &Dest = MI.getOperand(0); 4150 MachineOperand &Src0 = MI.getOperand(1); 4151 MachineOperand &Src1 = MI.getOperand(2); 4152 4153 if (IsAdd && ST.hasLshlAddB64()) { 4154 auto Add = BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_LSHL_ADD_U64_e64), 4155 Dest.getReg()) 4156 .add(Src0) 4157 .addImm(0) 4158 .add(Src1); 4159 TII->legalizeOperands(*Add); 4160 MI.eraseFromParent(); 4161 return BB; 4162 } 4163 4164 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4165 4166 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4167 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4168 4169 Register CarryReg = MRI.createVirtualRegister(CarryRC); 4170 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 4171 4172 const TargetRegisterClass *Src0RC = Src0.isReg() 4173 ? MRI.getRegClass(Src0.getReg()) 4174 : &AMDGPU::VReg_64RegClass; 4175 const TargetRegisterClass *Src1RC = Src1.isReg() 4176 ? MRI.getRegClass(Src1.getReg()) 4177 : &AMDGPU::VReg_64RegClass; 4178 4179 const TargetRegisterClass *Src0SubRC = 4180 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 4181 const TargetRegisterClass *Src1SubRC = 4182 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 4183 4184 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 4185 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 4186 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 4187 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 4188 4189 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 4190 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 4191 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 4192 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 4193 4194 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 4195 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 4196 .addReg(CarryReg, RegState::Define) 4197 .add(SrcReg0Sub0) 4198 .add(SrcReg1Sub0) 4199 .addImm(0); // clamp bit 4200 4201 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 4202 MachineInstr *HiHalf = 4203 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 4204 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 4205 .add(SrcReg0Sub1) 4206 .add(SrcReg1Sub1) 4207 .addReg(CarryReg, RegState::Kill) 4208 .addImm(0); // clamp bit 4209 4210 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 4211 .addReg(DestSub0) 4212 .addImm(AMDGPU::sub0) 4213 .addReg(DestSub1) 4214 .addImm(AMDGPU::sub1); 4215 TII->legalizeOperands(*LoHalf); 4216 TII->legalizeOperands(*HiHalf); 4217 MI.eraseFromParent(); 4218 return BB; 4219 } 4220 case AMDGPU::S_ADD_CO_PSEUDO: 4221 case AMDGPU::S_SUB_CO_PSEUDO: { 4222 // This pseudo has a chance to be selected 4223 // only from uniform add/subcarry node. All the VGPR operands 4224 // therefore assumed to be splat vectors. 4225 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4226 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4227 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4228 MachineBasicBlock::iterator MII = MI; 4229 const DebugLoc &DL = MI.getDebugLoc(); 4230 MachineOperand &Dest = MI.getOperand(0); 4231 MachineOperand &CarryDest = MI.getOperand(1); 4232 MachineOperand &Src0 = MI.getOperand(2); 4233 MachineOperand &Src1 = MI.getOperand(3); 4234 MachineOperand &Src2 = MI.getOperand(4); 4235 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 4236 ? AMDGPU::S_ADDC_U32 4237 : AMDGPU::S_SUBB_U32; 4238 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 4239 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4240 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 4241 .addReg(Src0.getReg()); 4242 Src0.setReg(RegOp0); 4243 } 4244 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 4245 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4246 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 4247 .addReg(Src1.getReg()); 4248 Src1.setReg(RegOp1); 4249 } 4250 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4251 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 4252 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 4253 .addReg(Src2.getReg()); 4254 Src2.setReg(RegOp2); 4255 } 4256 4257 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg()); 4258 unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC); 4259 assert(WaveSize == 64 || WaveSize == 32); 4260 4261 if (WaveSize == 64) { 4262 if (ST.hasScalarCompareEq64()) { 4263 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 4264 .addReg(Src2.getReg()) 4265 .addImm(0); 4266 } else { 4267 const TargetRegisterClass *SubRC = 4268 TRI->getSubRegClass(Src2RC, AMDGPU::sub0); 4269 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm( 4270 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC); 4271 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm( 4272 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC); 4273 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4274 4275 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32) 4276 .add(Src2Sub0) 4277 .add(Src2Sub1); 4278 4279 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 4280 .addReg(Src2_32, RegState::Kill) 4281 .addImm(0); 4282 } 4283 } else { 4284 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4285 .addReg(Src2.getReg()) 4286 .addImm(0); 4287 } 4288 4289 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4290 4291 unsigned SelOpc = 4292 (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32; 4293 4294 BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg()) 4295 .addImm(-1) 4296 .addImm(0); 4297 4298 MI.eraseFromParent(); 4299 return BB; 4300 } 4301 case AMDGPU::SI_INIT_M0: { 4302 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4303 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4304 .add(MI.getOperand(0)); 4305 MI.eraseFromParent(); 4306 return BB; 4307 } 4308 case AMDGPU::GET_GROUPSTATICSIZE: { 4309 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4310 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4311 DebugLoc DL = MI.getDebugLoc(); 4312 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4313 .add(MI.getOperand(0)) 4314 .addImm(MFI->getLDSSize()); 4315 MI.eraseFromParent(); 4316 return BB; 4317 } 4318 case AMDGPU::SI_INDIRECT_SRC_V1: 4319 case AMDGPU::SI_INDIRECT_SRC_V2: 4320 case AMDGPU::SI_INDIRECT_SRC_V4: 4321 case AMDGPU::SI_INDIRECT_SRC_V8: 4322 case AMDGPU::SI_INDIRECT_SRC_V16: 4323 case AMDGPU::SI_INDIRECT_SRC_V32: 4324 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4325 case AMDGPU::SI_INDIRECT_DST_V1: 4326 case AMDGPU::SI_INDIRECT_DST_V2: 4327 case AMDGPU::SI_INDIRECT_DST_V4: 4328 case AMDGPU::SI_INDIRECT_DST_V8: 4329 case AMDGPU::SI_INDIRECT_DST_V16: 4330 case AMDGPU::SI_INDIRECT_DST_V32: 4331 return emitIndirectDst(MI, *BB, *getSubtarget()); 4332 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4333 case AMDGPU::SI_KILL_I1_PSEUDO: 4334 return splitKillBlock(MI, BB); 4335 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4336 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4337 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4338 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4339 4340 Register Dst = MI.getOperand(0).getReg(); 4341 Register Src0 = MI.getOperand(1).getReg(); 4342 Register Src1 = MI.getOperand(2).getReg(); 4343 const DebugLoc &DL = MI.getDebugLoc(); 4344 Register SrcCond = MI.getOperand(3).getReg(); 4345 4346 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4347 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4348 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4349 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4350 4351 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4352 .addReg(SrcCond); 4353 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4354 .addImm(0) 4355 .addReg(Src0, 0, AMDGPU::sub0) 4356 .addImm(0) 4357 .addReg(Src1, 0, AMDGPU::sub0) 4358 .addReg(SrcCondCopy); 4359 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4360 .addImm(0) 4361 .addReg(Src0, 0, AMDGPU::sub1) 4362 .addImm(0) 4363 .addReg(Src1, 0, AMDGPU::sub1) 4364 .addReg(SrcCondCopy); 4365 4366 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4367 .addReg(DstLo) 4368 .addImm(AMDGPU::sub0) 4369 .addReg(DstHi) 4370 .addImm(AMDGPU::sub1); 4371 MI.eraseFromParent(); 4372 return BB; 4373 } 4374 case AMDGPU::SI_BR_UNDEF: { 4375 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4376 const DebugLoc &DL = MI.getDebugLoc(); 4377 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4378 .add(MI.getOperand(0)); 4379 Br->getOperand(1).setIsUndef(true); // read undef SCC 4380 MI.eraseFromParent(); 4381 return BB; 4382 } 4383 case AMDGPU::ADJCALLSTACKUP: 4384 case AMDGPU::ADJCALLSTACKDOWN: { 4385 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4386 MachineInstrBuilder MIB(*MF, &MI); 4387 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4388 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 4389 return BB; 4390 } 4391 case AMDGPU::SI_CALL_ISEL: { 4392 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4393 const DebugLoc &DL = MI.getDebugLoc(); 4394 4395 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4396 4397 MachineInstrBuilder MIB; 4398 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4399 4400 for (const MachineOperand &MO : MI.operands()) 4401 MIB.add(MO); 4402 4403 MIB.cloneMemRefs(MI); 4404 MI.eraseFromParent(); 4405 return BB; 4406 } 4407 case AMDGPU::V_ADD_CO_U32_e32: 4408 case AMDGPU::V_SUB_CO_U32_e32: 4409 case AMDGPU::V_SUBREV_CO_U32_e32: { 4410 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4411 const DebugLoc &DL = MI.getDebugLoc(); 4412 unsigned Opc = MI.getOpcode(); 4413 4414 bool NeedClampOperand = false; 4415 if (TII->pseudoToMCOpcode(Opc) == -1) { 4416 Opc = AMDGPU::getVOPe64(Opc); 4417 NeedClampOperand = true; 4418 } 4419 4420 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4421 if (TII->isVOP3(*I)) { 4422 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4423 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4424 I.addReg(TRI->getVCC(), RegState::Define); 4425 } 4426 I.add(MI.getOperand(1)) 4427 .add(MI.getOperand(2)); 4428 if (NeedClampOperand) 4429 I.addImm(0); // clamp bit for e64 encoding 4430 4431 TII->legalizeOperands(*I); 4432 4433 MI.eraseFromParent(); 4434 return BB; 4435 } 4436 case AMDGPU::V_ADDC_U32_e32: 4437 case AMDGPU::V_SUBB_U32_e32: 4438 case AMDGPU::V_SUBBREV_U32_e32: 4439 // These instructions have an implicit use of vcc which counts towards the 4440 // constant bus limit. 4441 TII->legalizeOperands(MI); 4442 return BB; 4443 case AMDGPU::DS_GWS_INIT: 4444 case AMDGPU::DS_GWS_SEMA_BR: 4445 case AMDGPU::DS_GWS_BARRIER: 4446 if (Subtarget->needsAlignedVGPRs()) { 4447 // Add implicit aligned super-reg to force alignment on the data operand. 4448 const DebugLoc &DL = MI.getDebugLoc(); 4449 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4450 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 4451 MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0); 4452 Register DataReg = Op->getReg(); 4453 bool IsAGPR = TRI->isAGPR(MRI, DataReg); 4454 Register Undef = MRI.createVirtualRegister( 4455 IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass); 4456 BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef); 4457 Register NewVR = 4458 MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass 4459 : &AMDGPU::VReg_64_Align2RegClass); 4460 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR) 4461 .addReg(DataReg, 0, Op->getSubReg()) 4462 .addImm(AMDGPU::sub0) 4463 .addReg(Undef) 4464 .addImm(AMDGPU::sub1); 4465 Op->setReg(NewVR); 4466 Op->setSubReg(AMDGPU::sub0); 4467 MI.addOperand(MachineOperand::CreateReg(NewVR, false, true)); 4468 } 4469 LLVM_FALLTHROUGH; 4470 case AMDGPU::DS_GWS_SEMA_V: 4471 case AMDGPU::DS_GWS_SEMA_P: 4472 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4473 // A s_waitcnt 0 is required to be the instruction immediately following. 4474 if (getSubtarget()->hasGWSAutoReplay()) { 4475 bundleInstWithWaitcnt(MI); 4476 return BB; 4477 } 4478 4479 return emitGWSMemViolTestLoop(MI, BB); 4480 case AMDGPU::S_SETREG_B32: { 4481 // Try to optimize cases that only set the denormal mode or rounding mode. 4482 // 4483 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4484 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4485 // instead. 4486 // 4487 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4488 // allow you to have a no side effect instruction in the output of a 4489 // sideeffecting pattern. 4490 unsigned ID, Offset, Width; 4491 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4492 if (ID != AMDGPU::Hwreg::ID_MODE) 4493 return BB; 4494 4495 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4496 const unsigned SetMask = WidthMask << Offset; 4497 4498 if (getSubtarget()->hasDenormModeInst()) { 4499 unsigned SetDenormOp = 0; 4500 unsigned SetRoundOp = 0; 4501 4502 // The dedicated instructions can only set the whole denorm or round mode 4503 // at once, not a subset of bits in either. 4504 if (SetMask == 4505 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4506 // If this fully sets both the round and denorm mode, emit the two 4507 // dedicated instructions for these. 4508 SetRoundOp = AMDGPU::S_ROUND_MODE; 4509 SetDenormOp = AMDGPU::S_DENORM_MODE; 4510 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4511 SetRoundOp = AMDGPU::S_ROUND_MODE; 4512 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4513 SetDenormOp = AMDGPU::S_DENORM_MODE; 4514 } 4515 4516 if (SetRoundOp || SetDenormOp) { 4517 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4518 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4519 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4520 unsigned ImmVal = Def->getOperand(1).getImm(); 4521 if (SetRoundOp) { 4522 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4523 .addImm(ImmVal & 0xf); 4524 4525 // If we also have the denorm mode, get just the denorm mode bits. 4526 ImmVal >>= 4; 4527 } 4528 4529 if (SetDenormOp) { 4530 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4531 .addImm(ImmVal & 0xf); 4532 } 4533 4534 MI.eraseFromParent(); 4535 return BB; 4536 } 4537 } 4538 } 4539 4540 // If only FP bits are touched, used the no side effects pseudo. 4541 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4542 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) 4543 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode)); 4544 4545 return BB; 4546 } 4547 default: 4548 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4549 } 4550 } 4551 4552 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4553 return isTypeLegal(VT.getScalarType()); 4554 } 4555 4556 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4557 // This currently forces unfolding various combinations of fsub into fma with 4558 // free fneg'd operands. As long as we have fast FMA (controlled by 4559 // isFMAFasterThanFMulAndFAdd), we should perform these. 4560 4561 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4562 // most of these combines appear to be cycle neutral but save on instruction 4563 // count / code size. 4564 return true; 4565 } 4566 4567 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; } 4568 4569 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4570 EVT VT) const { 4571 if (!VT.isVector()) { 4572 return MVT::i1; 4573 } 4574 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4575 } 4576 4577 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4578 // TODO: Should i16 be used always if legal? For now it would force VALU 4579 // shifts. 4580 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4581 } 4582 4583 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4584 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4585 ? Ty.changeElementSize(16) 4586 : Ty.changeElementSize(32); 4587 } 4588 4589 // Answering this is somewhat tricky and depends on the specific device which 4590 // have different rates for fma or all f64 operations. 4591 // 4592 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4593 // regardless of which device (although the number of cycles differs between 4594 // devices), so it is always profitable for f64. 4595 // 4596 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4597 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4598 // which we can always do even without fused FP ops since it returns the same 4599 // result as the separate operations and since it is always full 4600 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4601 // however does not support denormals, so we do report fma as faster if we have 4602 // a fast fma device and require denormals. 4603 // 4604 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4605 EVT VT) const { 4606 VT = VT.getScalarType(); 4607 4608 switch (VT.getSimpleVT().SimpleTy) { 4609 case MVT::f32: { 4610 // If mad is not available this depends only on if f32 fma is full rate. 4611 if (!Subtarget->hasMadMacF32Insts()) 4612 return Subtarget->hasFastFMAF32(); 4613 4614 // Otherwise f32 mad is always full rate and returns the same result as 4615 // the separate operations so should be preferred over fma. 4616 // However does not support denormals. 4617 if (hasFP32Denormals(MF)) 4618 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4619 4620 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4621 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4622 } 4623 case MVT::f64: 4624 return true; 4625 case MVT::f16: 4626 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4627 default: 4628 break; 4629 } 4630 4631 return false; 4632 } 4633 4634 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4635 LLT Ty) const { 4636 switch (Ty.getScalarSizeInBits()) { 4637 case 16: 4638 return isFMAFasterThanFMulAndFAdd(MF, MVT::f16); 4639 case 32: 4640 return isFMAFasterThanFMulAndFAdd(MF, MVT::f32); 4641 case 64: 4642 return isFMAFasterThanFMulAndFAdd(MF, MVT::f64); 4643 default: 4644 break; 4645 } 4646 4647 return false; 4648 } 4649 4650 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const { 4651 if (!Ty.isScalar()) 4652 return false; 4653 4654 if (Ty.getScalarSizeInBits() == 16) 4655 return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF()); 4656 if (Ty.getScalarSizeInBits() == 32) 4657 return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF()); 4658 4659 return false; 4660 } 4661 4662 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4663 const SDNode *N) const { 4664 // TODO: Check future ftz flag 4665 // v_mad_f32/v_mac_f32 do not support denormals. 4666 EVT VT = N->getValueType(0); 4667 if (VT == MVT::f32) 4668 return Subtarget->hasMadMacF32Insts() && 4669 !hasFP32Denormals(DAG.getMachineFunction()); 4670 if (VT == MVT::f16) { 4671 return Subtarget->hasMadF16() && 4672 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4673 } 4674 4675 return false; 4676 } 4677 4678 //===----------------------------------------------------------------------===// 4679 // Custom DAG Lowering Operations 4680 //===----------------------------------------------------------------------===// 4681 4682 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4683 // wider vector type is legal. 4684 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4685 SelectionDAG &DAG) const { 4686 unsigned Opc = Op.getOpcode(); 4687 EVT VT = Op.getValueType(); 4688 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4689 4690 SDValue Lo, Hi; 4691 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4692 4693 SDLoc SL(Op); 4694 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4695 Op->getFlags()); 4696 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4697 Op->getFlags()); 4698 4699 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4700 } 4701 4702 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4703 // wider vector type is legal. 4704 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4705 SelectionDAG &DAG) const { 4706 unsigned Opc = Op.getOpcode(); 4707 EVT VT = Op.getValueType(); 4708 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4709 VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8f32 || 4710 VT == MVT::v16f32 || VT == MVT::v32f32); 4711 4712 SDValue Lo0, Hi0; 4713 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4714 SDValue Lo1, Hi1; 4715 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4716 4717 SDLoc SL(Op); 4718 4719 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4720 Op->getFlags()); 4721 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4722 Op->getFlags()); 4723 4724 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4725 } 4726 4727 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4728 SelectionDAG &DAG) const { 4729 unsigned Opc = Op.getOpcode(); 4730 EVT VT = Op.getValueType(); 4731 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 || 4732 VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v8f32 || 4733 VT == MVT::v16f32 || VT == MVT::v32f32); 4734 4735 SDValue Lo0, Hi0; 4736 SDValue Op0 = Op.getOperand(0); 4737 std::tie(Lo0, Hi0) = Op0.getValueType().isVector() 4738 ? DAG.SplitVectorOperand(Op.getNode(), 0) 4739 : std::make_pair(Op0, Op0); 4740 SDValue Lo1, Hi1; 4741 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4742 SDValue Lo2, Hi2; 4743 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4744 4745 SDLoc SL(Op); 4746 auto ResVT = DAG.GetSplitDestVTs(VT); 4747 4748 SDValue OpLo = DAG.getNode(Opc, SL, ResVT.first, Lo0, Lo1, Lo2, 4749 Op->getFlags()); 4750 SDValue OpHi = DAG.getNode(Opc, SL, ResVT.second, Hi0, Hi1, Hi2, 4751 Op->getFlags()); 4752 4753 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4754 } 4755 4756 4757 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4758 switch (Op.getOpcode()) { 4759 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4760 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4761 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4762 case ISD::LOAD: { 4763 SDValue Result = LowerLOAD(Op, DAG); 4764 assert((!Result.getNode() || 4765 Result.getNode()->getNumValues() == 2) && 4766 "Load should return a value and a chain"); 4767 return Result; 4768 } 4769 4770 case ISD::FSIN: 4771 case ISD::FCOS: 4772 return LowerTrig(Op, DAG); 4773 case ISD::SELECT: return LowerSELECT(Op, DAG); 4774 case ISD::FDIV: return LowerFDIV(Op, DAG); 4775 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4776 case ISD::STORE: return LowerSTORE(Op, DAG); 4777 case ISD::GlobalAddress: { 4778 MachineFunction &MF = DAG.getMachineFunction(); 4779 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4780 return LowerGlobalAddress(MFI, Op, DAG); 4781 } 4782 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4783 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4784 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4785 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4786 case ISD::INSERT_SUBVECTOR: 4787 return lowerINSERT_SUBVECTOR(Op, DAG); 4788 case ISD::INSERT_VECTOR_ELT: 4789 return lowerINSERT_VECTOR_ELT(Op, DAG); 4790 case ISD::EXTRACT_VECTOR_ELT: 4791 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4792 case ISD::VECTOR_SHUFFLE: 4793 return lowerVECTOR_SHUFFLE(Op, DAG); 4794 case ISD::SCALAR_TO_VECTOR: 4795 return lowerSCALAR_TO_VECTOR(Op, DAG); 4796 case ISD::BUILD_VECTOR: 4797 return lowerBUILD_VECTOR(Op, DAG); 4798 case ISD::FP_ROUND: 4799 return lowerFP_ROUND(Op, DAG); 4800 case ISD::FPTRUNC_ROUND: { 4801 unsigned Opc; 4802 SDLoc DL(Op); 4803 4804 if (Op.getOperand(0)->getValueType(0) != MVT::f32) 4805 return SDValue(); 4806 4807 // Get the rounding mode from the last operand 4808 int RoundMode = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 4809 if (RoundMode == (int)RoundingMode::TowardPositive) 4810 Opc = AMDGPUISD::FPTRUNC_ROUND_UPWARD; 4811 else if (RoundMode == (int)RoundingMode::TowardNegative) 4812 Opc = AMDGPUISD::FPTRUNC_ROUND_DOWNWARD; 4813 else 4814 return SDValue(); 4815 4816 return DAG.getNode(Opc, DL, Op.getNode()->getVTList(), Op->getOperand(0)); 4817 } 4818 case ISD::TRAP: 4819 return lowerTRAP(Op, DAG); 4820 case ISD::DEBUGTRAP: 4821 return lowerDEBUGTRAP(Op, DAG); 4822 case ISD::FABS: 4823 case ISD::FNEG: 4824 case ISD::FCANONICALIZE: 4825 case ISD::BSWAP: 4826 return splitUnaryVectorOp(Op, DAG); 4827 case ISD::FMINNUM: 4828 case ISD::FMAXNUM: 4829 return lowerFMINNUM_FMAXNUM(Op, DAG); 4830 case ISD::FMA: 4831 return splitTernaryVectorOp(Op, DAG); 4832 case ISD::FP_TO_SINT: 4833 case ISD::FP_TO_UINT: 4834 return LowerFP_TO_INT(Op, DAG); 4835 case ISD::SHL: 4836 case ISD::SRA: 4837 case ISD::SRL: 4838 case ISD::ADD: 4839 case ISD::SUB: 4840 case ISD::MUL: 4841 case ISD::SMIN: 4842 case ISD::SMAX: 4843 case ISD::UMIN: 4844 case ISD::UMAX: 4845 case ISD::FADD: 4846 case ISD::FMUL: 4847 case ISD::FMINNUM_IEEE: 4848 case ISD::FMAXNUM_IEEE: 4849 case ISD::UADDSAT: 4850 case ISD::USUBSAT: 4851 case ISD::SADDSAT: 4852 case ISD::SSUBSAT: 4853 return splitBinaryVectorOp(Op, DAG); 4854 case ISD::SMULO: 4855 case ISD::UMULO: 4856 return lowerXMULO(Op, DAG); 4857 case ISD::SMUL_LOHI: 4858 case ISD::UMUL_LOHI: 4859 return lowerXMUL_LOHI(Op, DAG); 4860 case ISD::DYNAMIC_STACKALLOC: 4861 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4862 } 4863 return SDValue(); 4864 } 4865 4866 // Used for D16: Casts the result of an instruction into the right vector, 4867 // packs values if loads return unpacked values. 4868 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4869 const SDLoc &DL, 4870 SelectionDAG &DAG, bool Unpacked) { 4871 if (!LoadVT.isVector()) 4872 return Result; 4873 4874 // Cast back to the original packed type or to a larger type that is a 4875 // multiple of 32 bit for D16. Widening the return type is a required for 4876 // legalization. 4877 EVT FittingLoadVT = LoadVT; 4878 if ((LoadVT.getVectorNumElements() % 2) == 1) { 4879 FittingLoadVT = 4880 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4881 LoadVT.getVectorNumElements() + 1); 4882 } 4883 4884 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4885 // Truncate to v2i16/v4i16. 4886 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger(); 4887 4888 // Workaround legalizer not scalarizing truncate after vector op 4889 // legalization but not creating intermediate vector trunc. 4890 SmallVector<SDValue, 4> Elts; 4891 DAG.ExtractVectorElements(Result, Elts); 4892 for (SDValue &Elt : Elts) 4893 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4894 4895 // Pad illegal v1i16/v3fi6 to v4i16 4896 if ((LoadVT.getVectorNumElements() % 2) == 1) 4897 Elts.push_back(DAG.getUNDEF(MVT::i16)); 4898 4899 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4900 4901 // Bitcast to original type (v2f16/v4f16). 4902 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4903 } 4904 4905 // Cast back to the original packed type. 4906 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4907 } 4908 4909 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4910 MemSDNode *M, 4911 SelectionDAG &DAG, 4912 ArrayRef<SDValue> Ops, 4913 bool IsIntrinsic) const { 4914 SDLoc DL(M); 4915 4916 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4917 EVT LoadVT = M->getValueType(0); 4918 4919 EVT EquivLoadVT = LoadVT; 4920 if (LoadVT.isVector()) { 4921 if (Unpacked) { 4922 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4923 LoadVT.getVectorNumElements()); 4924 } else if ((LoadVT.getVectorNumElements() % 2) == 1) { 4925 // Widen v3f16 to legal type 4926 EquivLoadVT = 4927 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4928 LoadVT.getVectorNumElements() + 1); 4929 } 4930 } 4931 4932 // Change from v4f16/v2f16 to EquivLoadVT. 4933 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4934 4935 SDValue Load 4936 = DAG.getMemIntrinsicNode( 4937 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4938 VTList, Ops, M->getMemoryVT(), 4939 M->getMemOperand()); 4940 4941 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4942 4943 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4944 } 4945 4946 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4947 SelectionDAG &DAG, 4948 ArrayRef<SDValue> Ops) const { 4949 SDLoc DL(M); 4950 EVT LoadVT = M->getValueType(0); 4951 EVT EltType = LoadVT.getScalarType(); 4952 EVT IntVT = LoadVT.changeTypeToInteger(); 4953 4954 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4955 4956 unsigned Opc = 4957 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4958 4959 if (IsD16) { 4960 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4961 } 4962 4963 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4964 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4965 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4966 4967 if (isTypeLegal(LoadVT)) { 4968 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4969 M->getMemOperand(), DAG); 4970 } 4971 4972 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4973 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4974 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4975 M->getMemOperand(), DAG); 4976 return DAG.getMergeValues( 4977 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4978 DL); 4979 } 4980 4981 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4982 SDNode *N, SelectionDAG &DAG) { 4983 EVT VT = N->getValueType(0); 4984 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4985 unsigned CondCode = CD->getZExtValue(); 4986 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4987 return DAG.getUNDEF(VT); 4988 4989 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4990 4991 SDValue LHS = N->getOperand(1); 4992 SDValue RHS = N->getOperand(2); 4993 4994 SDLoc DL(N); 4995 4996 EVT CmpVT = LHS.getValueType(); 4997 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4998 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4999 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 5000 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 5001 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 5002 } 5003 5004 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 5005 5006 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 5007 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 5008 5009 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 5010 DAG.getCondCode(CCOpcode)); 5011 if (VT.bitsEq(CCVT)) 5012 return SetCC; 5013 return DAG.getZExtOrTrunc(SetCC, DL, VT); 5014 } 5015 5016 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 5017 SDNode *N, SelectionDAG &DAG) { 5018 EVT VT = N->getValueType(0); 5019 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 5020 5021 unsigned CondCode = CD->getZExtValue(); 5022 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 5023 return DAG.getUNDEF(VT); 5024 5025 SDValue Src0 = N->getOperand(1); 5026 SDValue Src1 = N->getOperand(2); 5027 EVT CmpVT = Src0.getValueType(); 5028 SDLoc SL(N); 5029 5030 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 5031 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 5032 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 5033 } 5034 5035 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 5036 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 5037 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 5038 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 5039 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 5040 Src1, DAG.getCondCode(CCOpcode)); 5041 if (VT.bitsEq(CCVT)) 5042 return SetCC; 5043 return DAG.getZExtOrTrunc(SetCC, SL, VT); 5044 } 5045 5046 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 5047 SelectionDAG &DAG) { 5048 EVT VT = N->getValueType(0); 5049 SDValue Src = N->getOperand(1); 5050 SDLoc SL(N); 5051 5052 if (Src.getOpcode() == ISD::SETCC) { 5053 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 5054 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 5055 Src.getOperand(1), Src.getOperand(2)); 5056 } 5057 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 5058 // (ballot 0) -> 0 5059 if (Arg->isZero()) 5060 return DAG.getConstant(0, SL, VT); 5061 5062 // (ballot 1) -> EXEC/EXEC_LO 5063 if (Arg->isOne()) { 5064 Register Exec; 5065 if (VT.getScalarSizeInBits() == 32) 5066 Exec = AMDGPU::EXEC_LO; 5067 else if (VT.getScalarSizeInBits() == 64) 5068 Exec = AMDGPU::EXEC; 5069 else 5070 return SDValue(); 5071 5072 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 5073 } 5074 } 5075 5076 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 5077 // ISD::SETNE) 5078 return DAG.getNode( 5079 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 5080 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 5081 } 5082 5083 void SITargetLowering::ReplaceNodeResults(SDNode *N, 5084 SmallVectorImpl<SDValue> &Results, 5085 SelectionDAG &DAG) const { 5086 switch (N->getOpcode()) { 5087 case ISD::INSERT_VECTOR_ELT: { 5088 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 5089 Results.push_back(Res); 5090 return; 5091 } 5092 case ISD::EXTRACT_VECTOR_ELT: { 5093 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 5094 Results.push_back(Res); 5095 return; 5096 } 5097 case ISD::INTRINSIC_WO_CHAIN: { 5098 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 5099 switch (IID) { 5100 case Intrinsic::amdgcn_cvt_pkrtz: { 5101 SDValue Src0 = N->getOperand(1); 5102 SDValue Src1 = N->getOperand(2); 5103 SDLoc SL(N); 5104 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 5105 Src0, Src1); 5106 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 5107 return; 5108 } 5109 case Intrinsic::amdgcn_cvt_pknorm_i16: 5110 case Intrinsic::amdgcn_cvt_pknorm_u16: 5111 case Intrinsic::amdgcn_cvt_pk_i16: 5112 case Intrinsic::amdgcn_cvt_pk_u16: { 5113 SDValue Src0 = N->getOperand(1); 5114 SDValue Src1 = N->getOperand(2); 5115 SDLoc SL(N); 5116 unsigned Opcode; 5117 5118 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 5119 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 5120 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 5121 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 5122 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 5123 Opcode = AMDGPUISD::CVT_PK_I16_I32; 5124 else 5125 Opcode = AMDGPUISD::CVT_PK_U16_U32; 5126 5127 EVT VT = N->getValueType(0); 5128 if (isTypeLegal(VT)) 5129 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 5130 else { 5131 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 5132 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 5133 } 5134 return; 5135 } 5136 } 5137 break; 5138 } 5139 case ISD::INTRINSIC_W_CHAIN: { 5140 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 5141 if (Res.getOpcode() == ISD::MERGE_VALUES) { 5142 // FIXME: Hacky 5143 for (unsigned I = 0; I < Res.getNumOperands(); I++) { 5144 Results.push_back(Res.getOperand(I)); 5145 } 5146 } else { 5147 Results.push_back(Res); 5148 Results.push_back(Res.getValue(1)); 5149 } 5150 return; 5151 } 5152 5153 break; 5154 } 5155 case ISD::SELECT: { 5156 SDLoc SL(N); 5157 EVT VT = N->getValueType(0); 5158 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 5159 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 5160 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 5161 5162 EVT SelectVT = NewVT; 5163 if (NewVT.bitsLT(MVT::i32)) { 5164 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 5165 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 5166 SelectVT = MVT::i32; 5167 } 5168 5169 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 5170 N->getOperand(0), LHS, RHS); 5171 5172 if (NewVT != SelectVT) 5173 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 5174 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 5175 return; 5176 } 5177 case ISD::FNEG: { 5178 if (N->getValueType(0) != MVT::v2f16) 5179 break; 5180 5181 SDLoc SL(N); 5182 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 5183 5184 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 5185 BC, 5186 DAG.getConstant(0x80008000, SL, MVT::i32)); 5187 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 5188 return; 5189 } 5190 case ISD::FABS: { 5191 if (N->getValueType(0) != MVT::v2f16) 5192 break; 5193 5194 SDLoc SL(N); 5195 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 5196 5197 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 5198 BC, 5199 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 5200 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 5201 return; 5202 } 5203 default: 5204 break; 5205 } 5206 } 5207 5208 /// Helper function for LowerBRCOND 5209 static SDNode *findUser(SDValue Value, unsigned Opcode) { 5210 5211 SDNode *Parent = Value.getNode(); 5212 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 5213 I != E; ++I) { 5214 5215 if (I.getUse().get() != Value) 5216 continue; 5217 5218 if (I->getOpcode() == Opcode) 5219 return *I; 5220 } 5221 return nullptr; 5222 } 5223 5224 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 5225 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 5226 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 5227 case Intrinsic::amdgcn_if: 5228 return AMDGPUISD::IF; 5229 case Intrinsic::amdgcn_else: 5230 return AMDGPUISD::ELSE; 5231 case Intrinsic::amdgcn_loop: 5232 return AMDGPUISD::LOOP; 5233 case Intrinsic::amdgcn_end_cf: 5234 llvm_unreachable("should not occur"); 5235 default: 5236 return 0; 5237 } 5238 } 5239 5240 // break, if_break, else_break are all only used as inputs to loop, not 5241 // directly as branch conditions. 5242 return 0; 5243 } 5244 5245 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 5246 const Triple &TT = getTargetMachine().getTargetTriple(); 5247 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5248 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5249 AMDGPU::shouldEmitConstantsToTextSection(TT); 5250 } 5251 5252 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 5253 // FIXME: Either avoid relying on address space here or change the default 5254 // address space for functions to avoid the explicit check. 5255 return (GV->getValueType()->isFunctionTy() || 5256 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 5257 !shouldEmitFixup(GV) && 5258 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 5259 } 5260 5261 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 5262 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 5263 } 5264 5265 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 5266 if (!GV->hasExternalLinkage()) 5267 return true; 5268 5269 const auto OS = getTargetMachine().getTargetTriple().getOS(); 5270 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 5271 } 5272 5273 /// This transforms the control flow intrinsics to get the branch destination as 5274 /// last parameter, also switches branch target with BR if the need arise 5275 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 5276 SelectionDAG &DAG) const { 5277 SDLoc DL(BRCOND); 5278 5279 SDNode *Intr = BRCOND.getOperand(1).getNode(); 5280 SDValue Target = BRCOND.getOperand(2); 5281 SDNode *BR = nullptr; 5282 SDNode *SetCC = nullptr; 5283 5284 if (Intr->getOpcode() == ISD::SETCC) { 5285 // As long as we negate the condition everything is fine 5286 SetCC = Intr; 5287 Intr = SetCC->getOperand(0).getNode(); 5288 5289 } else { 5290 // Get the target from BR if we don't negate the condition 5291 BR = findUser(BRCOND, ISD::BR); 5292 assert(BR && "brcond missing unconditional branch user"); 5293 Target = BR->getOperand(1); 5294 } 5295 5296 unsigned CFNode = isCFIntrinsic(Intr); 5297 if (CFNode == 0) { 5298 // This is a uniform branch so we don't need to legalize. 5299 return BRCOND; 5300 } 5301 5302 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 5303 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 5304 5305 assert(!SetCC || 5306 (SetCC->getConstantOperandVal(1) == 1 && 5307 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 5308 ISD::SETNE)); 5309 5310 // operands of the new intrinsic call 5311 SmallVector<SDValue, 4> Ops; 5312 if (HaveChain) 5313 Ops.push_back(BRCOND.getOperand(0)); 5314 5315 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 5316 Ops.push_back(Target); 5317 5318 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 5319 5320 // build the new intrinsic call 5321 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 5322 5323 if (!HaveChain) { 5324 SDValue Ops[] = { 5325 SDValue(Result, 0), 5326 BRCOND.getOperand(0) 5327 }; 5328 5329 Result = DAG.getMergeValues(Ops, DL).getNode(); 5330 } 5331 5332 if (BR) { 5333 // Give the branch instruction our target 5334 SDValue Ops[] = { 5335 BR->getOperand(0), 5336 BRCOND.getOperand(2) 5337 }; 5338 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5339 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5340 } 5341 5342 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5343 5344 // Copy the intrinsic results to registers 5345 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5346 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5347 if (!CopyToReg) 5348 continue; 5349 5350 Chain = DAG.getCopyToReg( 5351 Chain, DL, 5352 CopyToReg->getOperand(1), 5353 SDValue(Result, i - 1), 5354 SDValue()); 5355 5356 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5357 } 5358 5359 // Remove the old intrinsic from the chain 5360 DAG.ReplaceAllUsesOfValueWith( 5361 SDValue(Intr, Intr->getNumValues() - 1), 5362 Intr->getOperand(0)); 5363 5364 return Chain; 5365 } 5366 5367 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5368 SelectionDAG &DAG) const { 5369 MVT VT = Op.getSimpleValueType(); 5370 SDLoc DL(Op); 5371 // Checking the depth 5372 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5373 return DAG.getConstant(0, DL, VT); 5374 5375 MachineFunction &MF = DAG.getMachineFunction(); 5376 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5377 // Check for kernel and shader functions 5378 if (Info->isEntryFunction()) 5379 return DAG.getConstant(0, DL, VT); 5380 5381 MachineFrameInfo &MFI = MF.getFrameInfo(); 5382 // There is a call to @llvm.returnaddress in this function 5383 MFI.setReturnAddressIsTaken(true); 5384 5385 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5386 // Get the return address reg and mark it as an implicit live-in 5387 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5388 5389 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5390 } 5391 5392 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5393 SDValue Op, 5394 const SDLoc &DL, 5395 EVT VT) const { 5396 return Op.getValueType().bitsLE(VT) ? 5397 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5398 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5399 DAG.getTargetConstant(0, DL, MVT::i32)); 5400 } 5401 5402 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5403 assert(Op.getValueType() == MVT::f16 && 5404 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5405 5406 SDValue Src = Op.getOperand(0); 5407 EVT SrcVT = Src.getValueType(); 5408 if (SrcVT != MVT::f64) 5409 return Op; 5410 5411 SDLoc DL(Op); 5412 5413 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5414 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5415 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5416 } 5417 5418 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5419 SelectionDAG &DAG) const { 5420 EVT VT = Op.getValueType(); 5421 const MachineFunction &MF = DAG.getMachineFunction(); 5422 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5423 bool IsIEEEMode = Info->getMode().IEEE; 5424 5425 // FIXME: Assert during selection that this is only selected for 5426 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5427 // mode functions, but this happens to be OK since it's only done in cases 5428 // where there is known no sNaN. 5429 if (IsIEEEMode) 5430 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5431 5432 if (VT == MVT::v4f16 || VT == MVT::v8f16) 5433 return splitBinaryVectorOp(Op, DAG); 5434 return Op; 5435 } 5436 5437 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5438 EVT VT = Op.getValueType(); 5439 SDLoc SL(Op); 5440 SDValue LHS = Op.getOperand(0); 5441 SDValue RHS = Op.getOperand(1); 5442 bool isSigned = Op.getOpcode() == ISD::SMULO; 5443 5444 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5445 const APInt &C = RHSC->getAPIntValue(); 5446 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5447 if (C.isPowerOf2()) { 5448 // smulo(x, signed_min) is same as umulo(x, signed_min). 5449 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5450 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5451 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5452 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5453 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5454 SL, VT, Result, ShiftAmt), 5455 LHS, ISD::SETNE); 5456 return DAG.getMergeValues({ Result, Overflow }, SL); 5457 } 5458 } 5459 5460 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5461 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5462 SL, VT, LHS, RHS); 5463 5464 SDValue Sign = isSigned 5465 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5466 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5467 : DAG.getConstant(0, SL, VT); 5468 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5469 5470 return DAG.getMergeValues({ Result, Overflow }, SL); 5471 } 5472 5473 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const { 5474 if (Op->isDivergent()) { 5475 // Select to V_MAD_[IU]64_[IU]32. 5476 return Op; 5477 } 5478 if (Subtarget->hasSMulHi()) { 5479 // Expand to S_MUL_I32 + S_MUL_HI_[IU]32. 5480 return SDValue(); 5481 } 5482 // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to 5483 // calculate the high part, so we might as well do the whole thing with 5484 // V_MAD_[IU]64_[IU]32. 5485 return Op; 5486 } 5487 5488 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5489 if (!Subtarget->isTrapHandlerEnabled() || 5490 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) 5491 return lowerTrapEndpgm(Op, DAG); 5492 5493 if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) { 5494 switch (*HsaAbiVer) { 5495 case ELF::ELFABIVERSION_AMDGPU_HSA_V2: 5496 case ELF::ELFABIVERSION_AMDGPU_HSA_V3: 5497 return lowerTrapHsaQueuePtr(Op, DAG); 5498 case ELF::ELFABIVERSION_AMDGPU_HSA_V4: 5499 case ELF::ELFABIVERSION_AMDGPU_HSA_V5: 5500 return Subtarget->supportsGetDoorbellID() ? 5501 lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG); 5502 } 5503 } 5504 5505 llvm_unreachable("Unknown trap handler"); 5506 } 5507 5508 SDValue SITargetLowering::lowerTrapEndpgm( 5509 SDValue Op, SelectionDAG &DAG) const { 5510 SDLoc SL(Op); 5511 SDValue Chain = Op.getOperand(0); 5512 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5513 } 5514 5515 SDValue SITargetLowering::loadImplicitKernelArgument(SelectionDAG &DAG, MVT VT, 5516 const SDLoc &DL, Align Alignment, ImplicitParameter Param) const { 5517 MachineFunction &MF = DAG.getMachineFunction(); 5518 uint64_t Offset = getImplicitParameterOffset(MF, Param); 5519 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, DAG.getEntryNode(), Offset); 5520 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5521 return DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, PtrInfo, Alignment, 5522 MachineMemOperand::MODereferenceable | 5523 MachineMemOperand::MOInvariant); 5524 } 5525 5526 SDValue SITargetLowering::lowerTrapHsaQueuePtr( 5527 SDValue Op, SelectionDAG &DAG) const { 5528 SDLoc SL(Op); 5529 SDValue Chain = Op.getOperand(0); 5530 5531 SDValue QueuePtr; 5532 // For code object version 5, QueuePtr is passed through implicit kernarg. 5533 if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) { 5534 QueuePtr = 5535 loadImplicitKernelArgument(DAG, MVT::i64, SL, Align(8), QUEUE_PTR); 5536 } else { 5537 MachineFunction &MF = DAG.getMachineFunction(); 5538 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5539 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5540 5541 if (UserSGPR == AMDGPU::NoRegister) { 5542 // We probably are in a function incorrectly marked with 5543 // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the 5544 // trap, so just use a null pointer. 5545 QueuePtr = DAG.getConstant(0, SL, MVT::i64); 5546 } else { 5547 QueuePtr = CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, UserSGPR, 5548 MVT::i64); 5549 } 5550 } 5551 5552 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5553 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5554 QueuePtr, SDValue()); 5555 5556 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5557 SDValue Ops[] = { 5558 ToReg, 5559 DAG.getTargetConstant(TrapID, SL, MVT::i16), 5560 SGPR01, 5561 ToReg.getValue(1) 5562 }; 5563 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5564 } 5565 5566 SDValue SITargetLowering::lowerTrapHsa( 5567 SDValue Op, SelectionDAG &DAG) const { 5568 SDLoc SL(Op); 5569 SDValue Chain = Op.getOperand(0); 5570 5571 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5572 SDValue Ops[] = { 5573 Chain, 5574 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5575 }; 5576 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5577 } 5578 5579 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5580 SDLoc SL(Op); 5581 SDValue Chain = Op.getOperand(0); 5582 MachineFunction &MF = DAG.getMachineFunction(); 5583 5584 if (!Subtarget->isTrapHandlerEnabled() || 5585 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) { 5586 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5587 "debugtrap handler not supported", 5588 Op.getDebugLoc(), 5589 DS_Warning); 5590 LLVMContext &Ctx = MF.getFunction().getContext(); 5591 Ctx.diagnose(NoTrap); 5592 return Chain; 5593 } 5594 5595 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap); 5596 SDValue Ops[] = { 5597 Chain, 5598 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5599 }; 5600 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5601 } 5602 5603 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5604 SelectionDAG &DAG) const { 5605 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5606 if (Subtarget->hasApertureRegs()) { 5607 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5608 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5609 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5610 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5611 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5612 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5613 unsigned Encoding = 5614 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5615 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5616 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5617 5618 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5619 SDValue ApertureReg = SDValue( 5620 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5621 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5622 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5623 } 5624 5625 // For code object version 5, private_base and shared_base are passed through 5626 // implicit kernargs. 5627 if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) { 5628 ImplicitParameter Param = 5629 (AS == AMDGPUAS::LOCAL_ADDRESS) ? SHARED_BASE : PRIVATE_BASE; 5630 return loadImplicitKernelArgument(DAG, MVT::i32, DL, Align(4), Param); 5631 } 5632 5633 MachineFunction &MF = DAG.getMachineFunction(); 5634 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5635 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5636 if (UserSGPR == AMDGPU::NoRegister) { 5637 // We probably are in a function incorrectly marked with 5638 // amdgpu-no-queue-ptr. This is undefined. 5639 return DAG.getUNDEF(MVT::i32); 5640 } 5641 5642 SDValue QueuePtr = CreateLiveInRegister( 5643 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5644 5645 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5646 // private_segment_aperture_base_hi. 5647 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5648 5649 SDValue Ptr = 5650 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5651 5652 // TODO: Use custom target PseudoSourceValue. 5653 // TODO: We should use the value from the IR intrinsic call, but it might not 5654 // be available and how do we get it? 5655 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5656 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5657 commonAlignment(Align(64), StructOffset), 5658 MachineMemOperand::MODereferenceable | 5659 MachineMemOperand::MOInvariant); 5660 } 5661 5662 /// Return true if the value is a known valid address, such that a null check is 5663 /// not necessary. 5664 static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG, 5665 const AMDGPUTargetMachine &TM, unsigned AddrSpace) { 5666 if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) || 5667 isa<BasicBlockSDNode>(Val)) 5668 return true; 5669 5670 if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val)) 5671 return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace); 5672 5673 // TODO: Search through arithmetic, handle arguments and loads 5674 // marked nonnull. 5675 return false; 5676 } 5677 5678 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5679 SelectionDAG &DAG) const { 5680 SDLoc SL(Op); 5681 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5682 5683 SDValue Src = ASC->getOperand(0); 5684 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5685 unsigned SrcAS = ASC->getSrcAddressSpace(); 5686 5687 const AMDGPUTargetMachine &TM = 5688 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5689 5690 // flat -> local/private 5691 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) { 5692 unsigned DestAS = ASC->getDestAddressSpace(); 5693 5694 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5695 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5696 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5697 5698 if (isKnownNonNull(Src, DAG, TM, SrcAS)) 5699 return Ptr; 5700 5701 unsigned NullVal = TM.getNullPointerValue(DestAS); 5702 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5703 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5704 5705 return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr, 5706 SegmentNullPtr); 5707 } 5708 } 5709 5710 // local/private -> flat 5711 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5712 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5713 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5714 5715 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5716 SDValue CvtPtr = 5717 DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5718 CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr); 5719 5720 if (isKnownNonNull(Src, DAG, TM, SrcAS)) 5721 return CvtPtr; 5722 5723 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5724 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5725 5726 SDValue NonNull 5727 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5728 5729 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr, 5730 FlatNullPtr); 5731 } 5732 } 5733 5734 if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5735 Op.getValueType() == MVT::i64) { 5736 const SIMachineFunctionInfo *Info = 5737 DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>(); 5738 SDValue Hi = DAG.getConstant(Info->get32BitAddressHighBits(), SL, MVT::i32); 5739 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Hi); 5740 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 5741 } 5742 5743 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5744 Src.getValueType() == MVT::i64) 5745 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5746 5747 // global <-> flat are no-ops and never emitted. 5748 5749 const MachineFunction &MF = DAG.getMachineFunction(); 5750 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5751 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5752 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5753 5754 return DAG.getUNDEF(ASC->getValueType(0)); 5755 } 5756 5757 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5758 // the small vector and inserting them into the big vector. That is better than 5759 // the default expansion of doing it via a stack slot. Even though the use of 5760 // the stack slot would be optimized away afterwards, the stack slot itself 5761 // remains. 5762 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5763 SelectionDAG &DAG) const { 5764 SDValue Vec = Op.getOperand(0); 5765 SDValue Ins = Op.getOperand(1); 5766 SDValue Idx = Op.getOperand(2); 5767 EVT VecVT = Vec.getValueType(); 5768 EVT InsVT = Ins.getValueType(); 5769 EVT EltVT = VecVT.getVectorElementType(); 5770 unsigned InsNumElts = InsVT.getVectorNumElements(); 5771 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5772 SDLoc SL(Op); 5773 5774 for (unsigned I = 0; I != InsNumElts; ++I) { 5775 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5776 DAG.getConstant(I, SL, MVT::i32)); 5777 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5778 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5779 } 5780 return Vec; 5781 } 5782 5783 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5784 SelectionDAG &DAG) const { 5785 SDValue Vec = Op.getOperand(0); 5786 SDValue InsVal = Op.getOperand(1); 5787 SDValue Idx = Op.getOperand(2); 5788 EVT VecVT = Vec.getValueType(); 5789 EVT EltVT = VecVT.getVectorElementType(); 5790 unsigned VecSize = VecVT.getSizeInBits(); 5791 unsigned EltSize = EltVT.getSizeInBits(); 5792 SDLoc SL(Op); 5793 5794 // Specially handle the case of v4i16 with static indexing. 5795 unsigned NumElts = VecVT.getVectorNumElements(); 5796 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5797 if (NumElts == 4 && EltSize == 16 && KIdx) { 5798 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5799 5800 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5801 DAG.getConstant(0, SL, MVT::i32)); 5802 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5803 DAG.getConstant(1, SL, MVT::i32)); 5804 5805 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5806 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5807 5808 unsigned Idx = KIdx->getZExtValue(); 5809 bool InsertLo = Idx < 2; 5810 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5811 InsertLo ? LoVec : HiVec, 5812 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5813 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5814 5815 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5816 5817 SDValue Concat = InsertLo ? 5818 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5819 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5820 5821 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5822 } 5823 5824 // Static indexing does not lower to stack access, and hence there is no need 5825 // for special custom lowering to avoid stack access. 5826 if (isa<ConstantSDNode>(Idx)) 5827 return SDValue(); 5828 5829 // Avoid stack access for dynamic indexing by custom lowering to 5830 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5831 5832 assert(VecSize <= 64 && "Expected target vector size to be <= 64 bits"); 5833 5834 MVT IntVT = MVT::getIntegerVT(VecSize); 5835 5836 // Convert vector index to bit-index and get the required bit mask. 5837 assert(isPowerOf2_32(EltSize)); 5838 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5839 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5840 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5841 DAG.getConstant(0xffff, SL, IntVT), 5842 ScaledIdx); 5843 5844 // 1. Create a congruent vector with the target value in each element. 5845 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5846 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5847 5848 // 2. Mask off all other indicies except the required index within (1). 5849 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5850 5851 // 3. Mask off the required index within the target vector. 5852 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5853 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5854 DAG.getNOT(SL, BFM, IntVT), BCVec); 5855 5856 // 4. Get (2) and (3) ORed into the target vector. 5857 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5858 5859 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5860 } 5861 5862 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5863 SelectionDAG &DAG) const { 5864 SDLoc SL(Op); 5865 5866 EVT ResultVT = Op.getValueType(); 5867 SDValue Vec = Op.getOperand(0); 5868 SDValue Idx = Op.getOperand(1); 5869 EVT VecVT = Vec.getValueType(); 5870 unsigned VecSize = VecVT.getSizeInBits(); 5871 EVT EltVT = VecVT.getVectorElementType(); 5872 5873 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5874 5875 // Make sure we do any optimizations that will make it easier to fold 5876 // source modifiers before obscuring it with bit operations. 5877 5878 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5879 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5880 return Combined; 5881 5882 if (VecSize == 128) { 5883 SDValue Lo, Hi; 5884 EVT LoVT, HiVT; 5885 SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec); 5886 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5887 Lo = 5888 DAG.getBitcast(LoVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, 5889 V2, DAG.getConstant(0, SL, MVT::i32))); 5890 Hi = 5891 DAG.getBitcast(HiVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, 5892 V2, DAG.getConstant(1, SL, MVT::i32))); 5893 EVT IdxVT = Idx.getValueType(); 5894 unsigned NElem = VecVT.getVectorNumElements(); 5895 assert(isPowerOf2_32(NElem)); 5896 SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT); 5897 SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask); 5898 SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT); 5899 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx); 5900 } 5901 5902 assert(VecSize <= 64); 5903 5904 MVT IntVT = MVT::getIntegerVT(VecSize); 5905 5906 // If Vec is just a SCALAR_TO_VECTOR, then use the scalar integer directly. 5907 SDValue VecBC = peekThroughBitcasts(Vec); 5908 if (VecBC.getOpcode() == ISD::SCALAR_TO_VECTOR) { 5909 SDValue Src = VecBC.getOperand(0); 5910 Src = DAG.getBitcast(Src.getValueType().changeTypeToInteger(), Src); 5911 Vec = DAG.getAnyExtOrTrunc(Src, SL, IntVT); 5912 } 5913 5914 unsigned EltSize = EltVT.getSizeInBits(); 5915 assert(isPowerOf2_32(EltSize)); 5916 5917 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5918 5919 // Convert vector index to bit-index (* EltSize) 5920 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5921 5922 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5923 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5924 5925 if (ResultVT == MVT::f16) { 5926 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5927 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5928 } 5929 5930 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5931 } 5932 5933 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5934 assert(Elt % 2 == 0); 5935 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5936 } 5937 5938 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5939 SelectionDAG &DAG) const { 5940 SDLoc SL(Op); 5941 EVT ResultVT = Op.getValueType(); 5942 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5943 5944 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5945 EVT EltVT = PackVT.getVectorElementType(); 5946 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5947 5948 // vector_shuffle <0,1,6,7> lhs, rhs 5949 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5950 // 5951 // vector_shuffle <6,7,2,3> lhs, rhs 5952 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5953 // 5954 // vector_shuffle <6,7,0,1> lhs, rhs 5955 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5956 5957 // Avoid scalarizing when both halves are reading from consecutive elements. 5958 SmallVector<SDValue, 4> Pieces; 5959 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5960 if (elementPairIsContiguous(SVN->getMask(), I)) { 5961 const int Idx = SVN->getMaskElt(I); 5962 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5963 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5964 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5965 PackVT, SVN->getOperand(VecIdx), 5966 DAG.getConstant(EltIdx, SL, MVT::i32)); 5967 Pieces.push_back(SubVec); 5968 } else { 5969 const int Idx0 = SVN->getMaskElt(I); 5970 const int Idx1 = SVN->getMaskElt(I + 1); 5971 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5972 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5973 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5974 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5975 5976 SDValue Vec0 = SVN->getOperand(VecIdx0); 5977 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5978 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5979 5980 SDValue Vec1 = SVN->getOperand(VecIdx1); 5981 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5982 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5983 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5984 } 5985 } 5986 5987 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5988 } 5989 5990 SDValue SITargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op, 5991 SelectionDAG &DAG) const { 5992 SDValue SVal = Op.getOperand(0); 5993 EVT ResultVT = Op.getValueType(); 5994 EVT SValVT = SVal.getValueType(); 5995 SDValue UndefVal = DAG.getUNDEF(SValVT); 5996 SDLoc SL(Op); 5997 5998 SmallVector<SDValue, 8> VElts; 5999 VElts.push_back(SVal); 6000 for (int I = 1, E = ResultVT.getVectorNumElements(); I < E; ++I) 6001 VElts.push_back(UndefVal); 6002 6003 return DAG.getBuildVector(ResultVT, SL, VElts); 6004 } 6005 6006 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 6007 SelectionDAG &DAG) const { 6008 SDLoc SL(Op); 6009 EVT VT = Op.getValueType(); 6010 6011 if (VT == MVT::v4i16 || VT == MVT::v4f16 || 6012 VT == MVT::v8i16 || VT == MVT::v8f16) { 6013 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 6014 VT.getVectorNumElements() / 2); 6015 MVT HalfIntVT = MVT::getIntegerVT(HalfVT.getSizeInBits()); 6016 6017 // Turn into pair of packed build_vectors. 6018 // TODO: Special case for constants that can be materialized with s_mov_b64. 6019 SmallVector<SDValue, 4> LoOps, HiOps; 6020 for (unsigned I = 0, E = VT.getVectorNumElements() / 2; I != E; ++I) { 6021 LoOps.push_back(Op.getOperand(I)); 6022 HiOps.push_back(Op.getOperand(I + E)); 6023 } 6024 SDValue Lo = DAG.getBuildVector(HalfVT, SL, LoOps); 6025 SDValue Hi = DAG.getBuildVector(HalfVT, SL, HiOps); 6026 6027 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Lo); 6028 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Hi); 6029 6030 SDValue Blend = DAG.getBuildVector(MVT::getVectorVT(HalfIntVT, 2), SL, 6031 { CastLo, CastHi }); 6032 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 6033 } 6034 6035 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 6036 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 6037 6038 SDValue Lo = Op.getOperand(0); 6039 SDValue Hi = Op.getOperand(1); 6040 6041 // Avoid adding defined bits with the zero_extend. 6042 if (Hi.isUndef()) { 6043 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 6044 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 6045 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 6046 } 6047 6048 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 6049 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 6050 6051 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 6052 DAG.getConstant(16, SL, MVT::i32)); 6053 if (Lo.isUndef()) 6054 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 6055 6056 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 6057 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 6058 6059 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 6060 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 6061 } 6062 6063 bool 6064 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 6065 // We can fold offsets for anything that doesn't require a GOT relocation. 6066 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 6067 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 6068 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 6069 !shouldEmitGOTReloc(GA->getGlobal()); 6070 } 6071 6072 static SDValue 6073 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 6074 const SDLoc &DL, int64_t Offset, EVT PtrVT, 6075 unsigned GAFlags = SIInstrInfo::MO_NONE) { 6076 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 6077 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 6078 // lowered to the following code sequence: 6079 // 6080 // For constant address space: 6081 // s_getpc_b64 s[0:1] 6082 // s_add_u32 s0, s0, $symbol 6083 // s_addc_u32 s1, s1, 0 6084 // 6085 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 6086 // a fixup or relocation is emitted to replace $symbol with a literal 6087 // constant, which is a pc-relative offset from the encoding of the $symbol 6088 // operand to the global variable. 6089 // 6090 // For global address space: 6091 // s_getpc_b64 s[0:1] 6092 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 6093 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 6094 // 6095 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 6096 // fixups or relocations are emitted to replace $symbol@*@lo and 6097 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 6098 // which is a 64-bit pc-relative offset from the encoding of the $symbol 6099 // operand to the global variable. 6100 // 6101 // What we want here is an offset from the value returned by s_getpc 6102 // (which is the address of the s_add_u32 instruction) to the global 6103 // variable, but since the encoding of $symbol starts 4 bytes after the start 6104 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 6105 // small. This requires us to add 4 to the global variable offset in order to 6106 // compute the correct address. Similarly for the s_addc_u32 instruction, the 6107 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 6108 // instruction. 6109 SDValue PtrLo = 6110 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 6111 SDValue PtrHi; 6112 if (GAFlags == SIInstrInfo::MO_NONE) { 6113 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 6114 } else { 6115 PtrHi = 6116 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 6117 } 6118 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 6119 } 6120 6121 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 6122 SDValue Op, 6123 SelectionDAG &DAG) const { 6124 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 6125 SDLoc DL(GSD); 6126 EVT PtrVT = Op.getValueType(); 6127 6128 const GlobalValue *GV = GSD->getGlobal(); 6129 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 6130 shouldUseLDSConstAddress(GV)) || 6131 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 6132 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 6133 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 6134 GV->hasExternalLinkage()) { 6135 Type *Ty = GV->getValueType(); 6136 // HIP uses an unsized array `extern __shared__ T s[]` or similar 6137 // zero-sized type in other languages to declare the dynamic shared 6138 // memory which size is not known at the compile time. They will be 6139 // allocated by the runtime and placed directly after the static 6140 // allocated ones. They all share the same offset. 6141 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 6142 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 6143 // Adjust alignment for that dynamic shared memory array. 6144 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 6145 return SDValue( 6146 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 6147 } 6148 } 6149 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 6150 } 6151 6152 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 6153 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 6154 SIInstrInfo::MO_ABS32_LO); 6155 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 6156 } 6157 6158 if (shouldEmitFixup(GV)) 6159 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 6160 else if (shouldEmitPCReloc(GV)) 6161 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 6162 SIInstrInfo::MO_REL32); 6163 6164 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 6165 SIInstrInfo::MO_GOTPCREL32); 6166 6167 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 6168 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 6169 const DataLayout &DataLayout = DAG.getDataLayout(); 6170 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 6171 MachinePointerInfo PtrInfo 6172 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 6173 6174 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 6175 MachineMemOperand::MODereferenceable | 6176 MachineMemOperand::MOInvariant); 6177 } 6178 6179 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 6180 const SDLoc &DL, SDValue V) const { 6181 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 6182 // the destination register. 6183 // 6184 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 6185 // so we will end up with redundant moves to m0. 6186 // 6187 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 6188 6189 // A Null SDValue creates a glue result. 6190 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 6191 V, Chain); 6192 return SDValue(M0, 0); 6193 } 6194 6195 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 6196 SDValue Op, 6197 MVT VT, 6198 unsigned Offset) const { 6199 SDLoc SL(Op); 6200 SDValue Param = lowerKernargMemParameter( 6201 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 6202 // The local size values will have the hi 16-bits as zero. 6203 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 6204 DAG.getValueType(VT)); 6205 } 6206 6207 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 6208 EVT VT) { 6209 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 6210 "non-hsa intrinsic with hsa target", 6211 DL.getDebugLoc()); 6212 DAG.getContext()->diagnose(BadIntrin); 6213 return DAG.getUNDEF(VT); 6214 } 6215 6216 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 6217 EVT VT) { 6218 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 6219 "intrinsic not supported on subtarget", 6220 DL.getDebugLoc()); 6221 DAG.getContext()->diagnose(BadIntrin); 6222 return DAG.getUNDEF(VT); 6223 } 6224 6225 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 6226 ArrayRef<SDValue> Elts) { 6227 assert(!Elts.empty()); 6228 MVT Type; 6229 unsigned NumElts = Elts.size(); 6230 6231 if (NumElts <= 8) { 6232 Type = MVT::getVectorVT(MVT::f32, NumElts); 6233 } else { 6234 assert(Elts.size() <= 16); 6235 Type = MVT::v16f32; 6236 NumElts = 16; 6237 } 6238 6239 SmallVector<SDValue, 16> VecElts(NumElts); 6240 for (unsigned i = 0; i < Elts.size(); ++i) { 6241 SDValue Elt = Elts[i]; 6242 if (Elt.getValueType() != MVT::f32) 6243 Elt = DAG.getBitcast(MVT::f32, Elt); 6244 VecElts[i] = Elt; 6245 } 6246 for (unsigned i = Elts.size(); i < NumElts; ++i) 6247 VecElts[i] = DAG.getUNDEF(MVT::f32); 6248 6249 if (NumElts == 1) 6250 return VecElts[0]; 6251 return DAG.getBuildVector(Type, DL, VecElts); 6252 } 6253 6254 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 6255 SDValue Src, int ExtraElts) { 6256 EVT SrcVT = Src.getValueType(); 6257 6258 SmallVector<SDValue, 8> Elts; 6259 6260 if (SrcVT.isVector()) 6261 DAG.ExtractVectorElements(Src, Elts); 6262 else 6263 Elts.push_back(Src); 6264 6265 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 6266 while (ExtraElts--) 6267 Elts.push_back(Undef); 6268 6269 return DAG.getBuildVector(CastVT, DL, Elts); 6270 } 6271 6272 // Re-construct the required return value for a image load intrinsic. 6273 // This is more complicated due to the optional use TexFailCtrl which means the required 6274 // return type is an aggregate 6275 static SDValue constructRetValue(SelectionDAG &DAG, 6276 MachineSDNode *Result, 6277 ArrayRef<EVT> ResultTypes, 6278 bool IsTexFail, bool Unpacked, bool IsD16, 6279 int DMaskPop, int NumVDataDwords, 6280 const SDLoc &DL) { 6281 // Determine the required return type. This is the same regardless of IsTexFail flag 6282 EVT ReqRetVT = ResultTypes[0]; 6283 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 6284 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 6285 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 6286 6287 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 6288 DMaskPop : (DMaskPop + 1) / 2; 6289 6290 MVT DataDwordVT = NumDataDwords == 1 ? 6291 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 6292 6293 MVT MaskPopVT = MaskPopDwords == 1 ? 6294 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 6295 6296 SDValue Data(Result, 0); 6297 SDValue TexFail; 6298 6299 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) { 6300 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 6301 if (MaskPopVT.isVector()) { 6302 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 6303 SDValue(Result, 0), ZeroIdx); 6304 } else { 6305 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 6306 SDValue(Result, 0), ZeroIdx); 6307 } 6308 } 6309 6310 if (DataDwordVT.isVector()) 6311 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 6312 NumDataDwords - MaskPopDwords); 6313 6314 if (IsD16) 6315 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 6316 6317 EVT LegalReqRetVT = ReqRetVT; 6318 if (!ReqRetVT.isVector()) { 6319 if (!Data.getValueType().isInteger()) 6320 Data = DAG.getNode(ISD::BITCAST, DL, 6321 Data.getValueType().changeTypeToInteger(), Data); 6322 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 6323 } else { 6324 // We need to widen the return vector to a legal type 6325 if ((ReqRetVT.getVectorNumElements() % 2) == 1 && 6326 ReqRetVT.getVectorElementType().getSizeInBits() == 16) { 6327 LegalReqRetVT = 6328 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(), 6329 ReqRetVT.getVectorNumElements() + 1); 6330 } 6331 } 6332 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data); 6333 6334 if (IsTexFail) { 6335 TexFail = 6336 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0), 6337 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 6338 6339 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 6340 } 6341 6342 if (Result->getNumValues() == 1) 6343 return Data; 6344 6345 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 6346 } 6347 6348 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 6349 SDValue *LWE, bool &IsTexFail) { 6350 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 6351 6352 uint64_t Value = TexFailCtrlConst->getZExtValue(); 6353 if (Value) { 6354 IsTexFail = true; 6355 } 6356 6357 SDLoc DL(TexFailCtrlConst); 6358 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 6359 Value &= ~(uint64_t)0x1; 6360 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 6361 Value &= ~(uint64_t)0x2; 6362 6363 return Value == 0; 6364 } 6365 6366 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op, 6367 MVT PackVectorVT, 6368 SmallVectorImpl<SDValue> &PackedAddrs, 6369 unsigned DimIdx, unsigned EndIdx, 6370 unsigned NumGradients) { 6371 SDLoc DL(Op); 6372 for (unsigned I = DimIdx; I < EndIdx; I++) { 6373 SDValue Addr = Op.getOperand(I); 6374 6375 // Gradients are packed with undef for each coordinate. 6376 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 6377 // 1D: undef,dx/dh; undef,dx/dv 6378 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 6379 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 6380 if (((I + 1) >= EndIdx) || 6381 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 6382 I == DimIdx + NumGradients - 1))) { 6383 if (Addr.getValueType() != MVT::i16) 6384 Addr = DAG.getBitcast(MVT::i16, Addr); 6385 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 6386 } else { 6387 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 6388 I++; 6389 } 6390 Addr = DAG.getBitcast(MVT::f32, Addr); 6391 PackedAddrs.push_back(Addr); 6392 } 6393 } 6394 6395 SDValue SITargetLowering::lowerImage(SDValue Op, 6396 const AMDGPU::ImageDimIntrinsicInfo *Intr, 6397 SelectionDAG &DAG, bool WithChain) const { 6398 SDLoc DL(Op); 6399 MachineFunction &MF = DAG.getMachineFunction(); 6400 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 6401 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 6402 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 6403 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 6404 unsigned IntrOpcode = Intr->BaseOpcode; 6405 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget); 6406 6407 SmallVector<EVT, 3> ResultTypes(Op->values()); 6408 SmallVector<EVT, 3> OrigResultTypes(Op->values()); 6409 bool IsD16 = false; 6410 bool IsG16 = false; 6411 bool IsA16 = false; 6412 SDValue VData; 6413 int NumVDataDwords; 6414 bool AdjustRetType = false; 6415 6416 // Offset of intrinsic arguments 6417 const unsigned ArgOffset = WithChain ? 2 : 1; 6418 6419 unsigned DMask; 6420 unsigned DMaskLanes = 0; 6421 6422 if (BaseOpcode->Atomic) { 6423 VData = Op.getOperand(2); 6424 6425 bool Is64Bit = VData.getValueType() == MVT::i64; 6426 if (BaseOpcode->AtomicX2) { 6427 SDValue VData2 = Op.getOperand(3); 6428 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 6429 {VData, VData2}); 6430 if (Is64Bit) 6431 VData = DAG.getBitcast(MVT::v4i32, VData); 6432 6433 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 6434 DMask = Is64Bit ? 0xf : 0x3; 6435 NumVDataDwords = Is64Bit ? 4 : 2; 6436 } else { 6437 DMask = Is64Bit ? 0x3 : 0x1; 6438 NumVDataDwords = Is64Bit ? 2 : 1; 6439 } 6440 } else { 6441 auto *DMaskConst = 6442 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex)); 6443 DMask = DMaskConst->getZExtValue(); 6444 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 6445 6446 if (BaseOpcode->Store) { 6447 VData = Op.getOperand(2); 6448 6449 MVT StoreVT = VData.getSimpleValueType(); 6450 if (StoreVT.getScalarType() == MVT::f16) { 6451 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6452 return Op; // D16 is unsupported for this instruction 6453 6454 IsD16 = true; 6455 VData = handleD16VData(VData, DAG, true); 6456 } 6457 6458 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 6459 } else { 6460 // Work out the num dwords based on the dmask popcount and underlying type 6461 // and whether packing is supported. 6462 MVT LoadVT = ResultTypes[0].getSimpleVT(); 6463 if (LoadVT.getScalarType() == MVT::f16) { 6464 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6465 return Op; // D16 is unsupported for this instruction 6466 6467 IsD16 = true; 6468 } 6469 6470 // Confirm that the return type is large enough for the dmask specified 6471 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 6472 (!LoadVT.isVector() && DMaskLanes > 1)) 6473 return Op; 6474 6475 // The sq block of gfx8 and gfx9 do not estimate register use correctly 6476 // for d16 image_gather4, image_gather4_l, and image_gather4_lz 6477 // instructions. 6478 if (IsD16 && !Subtarget->hasUnpackedD16VMem() && 6479 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug())) 6480 NumVDataDwords = (DMaskLanes + 1) / 2; 6481 else 6482 NumVDataDwords = DMaskLanes; 6483 6484 AdjustRetType = true; 6485 } 6486 } 6487 6488 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd; 6489 SmallVector<SDValue, 4> VAddrs; 6490 6491 // Check for 16 bit addresses or derivatives and pack if true. 6492 MVT VAddrVT = 6493 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType(); 6494 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6495 MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6496 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6497 6498 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType(); 6499 VAddrScalarVT = VAddrVT.getScalarType(); 6500 MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6501 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6502 6503 // Push back extra arguments. 6504 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) { 6505 if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) { 6506 assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument"); 6507 // Special handling of bias when A16 is on. Bias is of type half but 6508 // occupies full 32-bit. 6509 SDValue Bias = DAG.getBuildVector( 6510 MVT::v2f16, DL, 6511 {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)}); 6512 VAddrs.push_back(Bias); 6513 } else { 6514 assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) && 6515 "Bias needs to be converted to 16 bit in A16 mode"); 6516 VAddrs.push_back(Op.getOperand(ArgOffset + I)); 6517 } 6518 } 6519 6520 if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) { 6521 // 16 bit gradients are supported, but are tied to the A16 control 6522 // so both gradients and addresses must be 16 bit 6523 LLVM_DEBUG( 6524 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6525 "require 16 bit args for both gradients and addresses"); 6526 return Op; 6527 } 6528 6529 if (IsA16) { 6530 if (!ST->hasA16()) { 6531 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6532 "support 16 bit addresses\n"); 6533 return Op; 6534 } 6535 } 6536 6537 // We've dealt with incorrect input so we know that if IsA16, IsG16 6538 // are set then we have to compress/pack operands (either address, 6539 // gradient or both) 6540 // In the case where a16 and gradients are tied (no G16 support) then we 6541 // have already verified that both IsA16 and IsG16 are true 6542 if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) { 6543 // Activate g16 6544 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6545 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6546 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6547 } 6548 6549 // Add gradients (packed or unpacked) 6550 if (IsG16) { 6551 // Pack the gradients 6552 // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart); 6553 packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs, 6554 ArgOffset + Intr->GradientStart, 6555 ArgOffset + Intr->CoordStart, Intr->NumGradients); 6556 } else { 6557 for (unsigned I = ArgOffset + Intr->GradientStart; 6558 I < ArgOffset + Intr->CoordStart; I++) 6559 VAddrs.push_back(Op.getOperand(I)); 6560 } 6561 6562 // Add addresses (packed or unpacked) 6563 if (IsA16) { 6564 packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs, 6565 ArgOffset + Intr->CoordStart, VAddrEnd, 6566 0 /* No gradients */); 6567 } else { 6568 // Add uncompressed address 6569 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++) 6570 VAddrs.push_back(Op.getOperand(I)); 6571 } 6572 6573 // If the register allocator cannot place the address registers contiguously 6574 // without introducing moves, then using the non-sequential address encoding 6575 // is always preferable, since it saves VALU instructions and is usually a 6576 // wash in terms of code size or even better. 6577 // 6578 // However, we currently have no way of hinting to the register allocator that 6579 // MIMG addresses should be placed contiguously when it is possible to do so, 6580 // so force non-NSA for the common 2-address case as a heuristic. 6581 // 6582 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6583 // allocation when possible. 6584 bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) && 6585 VAddrs.size() >= 3 && 6586 VAddrs.size() <= (unsigned)ST->getNSAMaxSize(); 6587 SDValue VAddr; 6588 if (!UseNSA) 6589 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6590 6591 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6592 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6593 SDValue Unorm; 6594 if (!BaseOpcode->Sampler) { 6595 Unorm = True; 6596 } else { 6597 auto UnormConst = 6598 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex)); 6599 6600 Unorm = UnormConst->getZExtValue() ? True : False; 6601 } 6602 6603 SDValue TFE; 6604 SDValue LWE; 6605 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex); 6606 bool IsTexFail = false; 6607 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6608 return Op; 6609 6610 if (IsTexFail) { 6611 if (!DMaskLanes) { 6612 // Expecting to get an error flag since TFC is on - and dmask is 0 6613 // Force dmask to be at least 1 otherwise the instruction will fail 6614 DMask = 0x1; 6615 DMaskLanes = 1; 6616 NumVDataDwords = 1; 6617 } 6618 NumVDataDwords += 1; 6619 AdjustRetType = true; 6620 } 6621 6622 // Has something earlier tagged that the return type needs adjusting 6623 // This happens if the instruction is a load or has set TexFailCtrl flags 6624 if (AdjustRetType) { 6625 // NumVDataDwords reflects the true number of dwords required in the return type 6626 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6627 // This is a no-op load. This can be eliminated 6628 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6629 if (isa<MemSDNode>(Op)) 6630 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6631 return Undef; 6632 } 6633 6634 EVT NewVT = NumVDataDwords > 1 ? 6635 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6636 : MVT::i32; 6637 6638 ResultTypes[0] = NewVT; 6639 if (ResultTypes.size() == 3) { 6640 // Original result was aggregate type used for TexFailCtrl results 6641 // The actual instruction returns as a vector type which has now been 6642 // created. Remove the aggregate result. 6643 ResultTypes.erase(&ResultTypes[1]); 6644 } 6645 } 6646 6647 unsigned CPol = cast<ConstantSDNode>( 6648 Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue(); 6649 if (BaseOpcode->Atomic) 6650 CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization 6651 if (CPol & ~AMDGPU::CPol::ALL) 6652 return Op; 6653 6654 SmallVector<SDValue, 26> Ops; 6655 if (BaseOpcode->Store || BaseOpcode->Atomic) 6656 Ops.push_back(VData); // vdata 6657 if (UseNSA) 6658 append_range(Ops, VAddrs); 6659 else 6660 Ops.push_back(VAddr); 6661 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex)); 6662 if (BaseOpcode->Sampler) 6663 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex)); 6664 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6665 if (IsGFX10Plus) 6666 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6667 Ops.push_back(Unorm); 6668 Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32)); 6669 Ops.push_back(IsA16 && // r128, a16 for gfx9 6670 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6671 if (IsGFX10Plus) 6672 Ops.push_back(IsA16 ? True : False); 6673 if (!Subtarget->hasGFX90AInsts()) { 6674 Ops.push_back(TFE); //tfe 6675 } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) { 6676 report_fatal_error("TFE is not supported on this GPU"); 6677 } 6678 Ops.push_back(LWE); // lwe 6679 if (!IsGFX10Plus) 6680 Ops.push_back(DimInfo->DA ? True : False); 6681 if (BaseOpcode->HasD16) 6682 Ops.push_back(IsD16 ? True : False); 6683 if (isa<MemSDNode>(Op)) 6684 Ops.push_back(Op.getOperand(0)); // chain 6685 6686 int NumVAddrDwords = 6687 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6688 int Opcode = -1; 6689 6690 if (IsGFX10Plus) { 6691 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6692 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6693 : AMDGPU::MIMGEncGfx10Default, 6694 NumVDataDwords, NumVAddrDwords); 6695 } else { 6696 if (Subtarget->hasGFX90AInsts()) { 6697 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a, 6698 NumVDataDwords, NumVAddrDwords); 6699 if (Opcode == -1) 6700 report_fatal_error( 6701 "requested image instruction is not supported on this GPU"); 6702 } 6703 if (Opcode == -1 && 6704 Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6705 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6706 NumVDataDwords, NumVAddrDwords); 6707 if (Opcode == -1) 6708 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6709 NumVDataDwords, NumVAddrDwords); 6710 } 6711 assert(Opcode != -1); 6712 6713 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6714 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6715 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6716 DAG.setNodeMemRefs(NewNode, {MemRef}); 6717 } 6718 6719 if (BaseOpcode->AtomicX2) { 6720 SmallVector<SDValue, 1> Elt; 6721 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6722 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6723 } 6724 if (BaseOpcode->Store) 6725 return SDValue(NewNode, 0); 6726 return constructRetValue(DAG, NewNode, 6727 OrigResultTypes, IsTexFail, 6728 Subtarget->hasUnpackedD16VMem(), IsD16, 6729 DMaskLanes, NumVDataDwords, DL); 6730 } 6731 6732 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6733 SDValue Offset, SDValue CachePolicy, 6734 SelectionDAG &DAG) const { 6735 MachineFunction &MF = DAG.getMachineFunction(); 6736 6737 const DataLayout &DataLayout = DAG.getDataLayout(); 6738 Align Alignment = 6739 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6740 6741 MachineMemOperand *MMO = MF.getMachineMemOperand( 6742 MachinePointerInfo(), 6743 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6744 MachineMemOperand::MOInvariant, 6745 VT.getStoreSize(), Alignment); 6746 6747 if (!Offset->isDivergent()) { 6748 SDValue Ops[] = { 6749 Rsrc, 6750 Offset, // Offset 6751 CachePolicy 6752 }; 6753 6754 // Widen vec3 load to vec4. 6755 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6756 EVT WidenedVT = 6757 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6758 auto WidenedOp = DAG.getMemIntrinsicNode( 6759 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6760 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6761 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6762 DAG.getVectorIdxConstant(0, DL)); 6763 return Subvector; 6764 } 6765 6766 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6767 DAG.getVTList(VT), Ops, VT, MMO); 6768 } 6769 6770 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6771 // assume that the buffer is unswizzled. 6772 SmallVector<SDValue, 4> Loads; 6773 unsigned NumLoads = 1; 6774 MVT LoadVT = VT.getSimpleVT(); 6775 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6776 assert((LoadVT.getScalarType() == MVT::i32 || 6777 LoadVT.getScalarType() == MVT::f32)); 6778 6779 if (NumElts == 8 || NumElts == 16) { 6780 NumLoads = NumElts / 4; 6781 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6782 } 6783 6784 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6785 SDValue Ops[] = { 6786 DAG.getEntryNode(), // Chain 6787 Rsrc, // rsrc 6788 DAG.getConstant(0, DL, MVT::i32), // vindex 6789 {}, // voffset 6790 {}, // soffset 6791 {}, // offset 6792 CachePolicy, // cachepolicy 6793 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6794 }; 6795 6796 // Use the alignment to ensure that the required offsets will fit into the 6797 // immediate offsets. 6798 setBufferOffsets(Offset, DAG, &Ops[3], 6799 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6800 6801 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6802 for (unsigned i = 0; i < NumLoads; ++i) { 6803 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6804 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6805 LoadVT, MMO, DAG)); 6806 } 6807 6808 if (NumElts == 8 || NumElts == 16) 6809 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6810 6811 return Loads[0]; 6812 } 6813 6814 SDValue SITargetLowering::lowerWorkitemID(SelectionDAG &DAG, SDValue Op, 6815 unsigned Dim, 6816 const ArgDescriptor &Arg) const { 6817 SDLoc SL(Op); 6818 MachineFunction &MF = DAG.getMachineFunction(); 6819 unsigned MaxID = Subtarget->getMaxWorkitemID(MF.getFunction(), Dim); 6820 if (MaxID == 0) 6821 return DAG.getConstant(0, SL, MVT::i32); 6822 6823 SDValue Val = loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6824 SDLoc(DAG.getEntryNode()), Arg); 6825 6826 // Don't bother inserting AssertZext for packed IDs since we're emitting the 6827 // masking operations anyway. 6828 // 6829 // TODO: We could assert the top bit is 0 for the source copy. 6830 if (Arg.isMasked()) 6831 return Val; 6832 6833 // Preserve the known bits after expansion to a copy. 6834 EVT SmallVT = 6835 EVT::getIntegerVT(*DAG.getContext(), 32 - countLeadingZeros(MaxID)); 6836 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Val, 6837 DAG.getValueType(SmallVT)); 6838 } 6839 6840 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6841 SelectionDAG &DAG) const { 6842 MachineFunction &MF = DAG.getMachineFunction(); 6843 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6844 6845 EVT VT = Op.getValueType(); 6846 SDLoc DL(Op); 6847 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6848 6849 // TODO: Should this propagate fast-math-flags? 6850 6851 switch (IntrinsicID) { 6852 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6853 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6854 return emitNonHSAIntrinsicError(DAG, DL, VT); 6855 return getPreloadedValue(DAG, *MFI, VT, 6856 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6857 } 6858 case Intrinsic::amdgcn_dispatch_ptr: 6859 case Intrinsic::amdgcn_queue_ptr: { 6860 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6861 DiagnosticInfoUnsupported BadIntrin( 6862 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6863 DL.getDebugLoc()); 6864 DAG.getContext()->diagnose(BadIntrin); 6865 return DAG.getUNDEF(VT); 6866 } 6867 6868 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6869 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6870 return getPreloadedValue(DAG, *MFI, VT, RegID); 6871 } 6872 case Intrinsic::amdgcn_implicitarg_ptr: { 6873 if (MFI->isEntryFunction()) 6874 return getImplicitArgPtr(DAG, DL); 6875 return getPreloadedValue(DAG, *MFI, VT, 6876 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6877 } 6878 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6879 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6880 // This only makes sense to call in a kernel, so just lower to null. 6881 return DAG.getConstant(0, DL, VT); 6882 } 6883 6884 return getPreloadedValue(DAG, *MFI, VT, 6885 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6886 } 6887 case Intrinsic::amdgcn_dispatch_id: { 6888 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6889 } 6890 case Intrinsic::amdgcn_rcp: 6891 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6892 case Intrinsic::amdgcn_rsq: 6893 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6894 case Intrinsic::amdgcn_rsq_legacy: 6895 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6896 return emitRemovedIntrinsicError(DAG, DL, VT); 6897 return SDValue(); 6898 case Intrinsic::amdgcn_rcp_legacy: 6899 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6900 return emitRemovedIntrinsicError(DAG, DL, VT); 6901 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6902 case Intrinsic::amdgcn_rsq_clamp: { 6903 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6904 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6905 6906 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6907 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6908 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6909 6910 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6911 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6912 DAG.getConstantFP(Max, DL, VT)); 6913 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6914 DAG.getConstantFP(Min, DL, VT)); 6915 } 6916 case Intrinsic::r600_read_ngroups_x: 6917 if (Subtarget->isAmdHsaOS()) 6918 return emitNonHSAIntrinsicError(DAG, DL, VT); 6919 6920 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6921 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6922 false); 6923 case Intrinsic::r600_read_ngroups_y: 6924 if (Subtarget->isAmdHsaOS()) 6925 return emitNonHSAIntrinsicError(DAG, DL, VT); 6926 6927 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6928 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6929 false); 6930 case Intrinsic::r600_read_ngroups_z: 6931 if (Subtarget->isAmdHsaOS()) 6932 return emitNonHSAIntrinsicError(DAG, DL, VT); 6933 6934 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6935 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6936 false); 6937 case Intrinsic::r600_read_global_size_x: 6938 if (Subtarget->isAmdHsaOS()) 6939 return emitNonHSAIntrinsicError(DAG, DL, VT); 6940 6941 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6942 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6943 Align(4), false); 6944 case Intrinsic::r600_read_global_size_y: 6945 if (Subtarget->isAmdHsaOS()) 6946 return emitNonHSAIntrinsicError(DAG, DL, VT); 6947 6948 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6949 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6950 Align(4), false); 6951 case Intrinsic::r600_read_global_size_z: 6952 if (Subtarget->isAmdHsaOS()) 6953 return emitNonHSAIntrinsicError(DAG, DL, VT); 6954 6955 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6956 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6957 Align(4), false); 6958 case Intrinsic::r600_read_local_size_x: 6959 if (Subtarget->isAmdHsaOS()) 6960 return emitNonHSAIntrinsicError(DAG, DL, VT); 6961 6962 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6963 SI::KernelInputOffsets::LOCAL_SIZE_X); 6964 case Intrinsic::r600_read_local_size_y: 6965 if (Subtarget->isAmdHsaOS()) 6966 return emitNonHSAIntrinsicError(DAG, DL, VT); 6967 6968 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6969 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6970 case Intrinsic::r600_read_local_size_z: 6971 if (Subtarget->isAmdHsaOS()) 6972 return emitNonHSAIntrinsicError(DAG, DL, VT); 6973 6974 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6975 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6976 case Intrinsic::amdgcn_workgroup_id_x: 6977 return getPreloadedValue(DAG, *MFI, VT, 6978 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6979 case Intrinsic::amdgcn_workgroup_id_y: 6980 return getPreloadedValue(DAG, *MFI, VT, 6981 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6982 case Intrinsic::amdgcn_workgroup_id_z: 6983 return getPreloadedValue(DAG, *MFI, VT, 6984 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6985 case Intrinsic::amdgcn_workitem_id_x: 6986 return lowerWorkitemID(DAG, Op, 0, MFI->getArgInfo().WorkItemIDX); 6987 case Intrinsic::amdgcn_workitem_id_y: 6988 return lowerWorkitemID(DAG, Op, 1, MFI->getArgInfo().WorkItemIDY); 6989 case Intrinsic::amdgcn_workitem_id_z: 6990 return lowerWorkitemID(DAG, Op, 2, MFI->getArgInfo().WorkItemIDZ); 6991 case Intrinsic::amdgcn_wavefrontsize: 6992 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6993 SDLoc(Op), MVT::i32); 6994 case Intrinsic::amdgcn_s_buffer_load: { 6995 unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 6996 if (CPol & ~AMDGPU::CPol::ALL) 6997 return Op; 6998 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6999 DAG); 7000 } 7001 case Intrinsic::amdgcn_fdiv_fast: 7002 return lowerFDIV_FAST(Op, DAG); 7003 case Intrinsic::amdgcn_sin: 7004 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 7005 7006 case Intrinsic::amdgcn_cos: 7007 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 7008 7009 case Intrinsic::amdgcn_mul_u24: 7010 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 7011 case Intrinsic::amdgcn_mul_i24: 7012 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 7013 7014 case Intrinsic::amdgcn_log_clamp: { 7015 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 7016 return SDValue(); 7017 7018 return emitRemovedIntrinsicError(DAG, DL, VT); 7019 } 7020 case Intrinsic::amdgcn_ldexp: 7021 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 7022 Op.getOperand(1), Op.getOperand(2)); 7023 7024 case Intrinsic::amdgcn_fract: 7025 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 7026 7027 case Intrinsic::amdgcn_class: 7028 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 7029 Op.getOperand(1), Op.getOperand(2)); 7030 case Intrinsic::amdgcn_div_fmas: 7031 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 7032 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 7033 Op.getOperand(4)); 7034 7035 case Intrinsic::amdgcn_div_fixup: 7036 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 7037 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 7038 7039 case Intrinsic::amdgcn_div_scale: { 7040 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 7041 7042 // Translate to the operands expected by the machine instruction. The 7043 // first parameter must be the same as the first instruction. 7044 SDValue Numerator = Op.getOperand(1); 7045 SDValue Denominator = Op.getOperand(2); 7046 7047 // Note this order is opposite of the machine instruction's operations, 7048 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 7049 // intrinsic has the numerator as the first operand to match a normal 7050 // division operation. 7051 7052 SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator; 7053 7054 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 7055 Denominator, Numerator); 7056 } 7057 case Intrinsic::amdgcn_icmp: { 7058 // There is a Pat that handles this variant, so return it as-is. 7059 if (Op.getOperand(1).getValueType() == MVT::i1 && 7060 Op.getConstantOperandVal(2) == 0 && 7061 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 7062 return Op; 7063 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 7064 } 7065 case Intrinsic::amdgcn_fcmp: { 7066 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 7067 } 7068 case Intrinsic::amdgcn_ballot: 7069 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 7070 case Intrinsic::amdgcn_fmed3: 7071 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 7072 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 7073 case Intrinsic::amdgcn_fdot2: 7074 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 7075 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 7076 Op.getOperand(4)); 7077 case Intrinsic::amdgcn_fmul_legacy: 7078 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 7079 Op.getOperand(1), Op.getOperand(2)); 7080 case Intrinsic::amdgcn_sffbh: 7081 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 7082 case Intrinsic::amdgcn_sbfe: 7083 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 7084 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 7085 case Intrinsic::amdgcn_ubfe: 7086 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 7087 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 7088 case Intrinsic::amdgcn_cvt_pkrtz: 7089 case Intrinsic::amdgcn_cvt_pknorm_i16: 7090 case Intrinsic::amdgcn_cvt_pknorm_u16: 7091 case Intrinsic::amdgcn_cvt_pk_i16: 7092 case Intrinsic::amdgcn_cvt_pk_u16: { 7093 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 7094 EVT VT = Op.getValueType(); 7095 unsigned Opcode; 7096 7097 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 7098 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 7099 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 7100 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 7101 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 7102 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 7103 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 7104 Opcode = AMDGPUISD::CVT_PK_I16_I32; 7105 else 7106 Opcode = AMDGPUISD::CVT_PK_U16_U32; 7107 7108 if (isTypeLegal(VT)) 7109 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 7110 7111 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 7112 Op.getOperand(1), Op.getOperand(2)); 7113 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 7114 } 7115 case Intrinsic::amdgcn_fmad_ftz: 7116 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 7117 Op.getOperand(2), Op.getOperand(3)); 7118 7119 case Intrinsic::amdgcn_if_break: 7120 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 7121 Op->getOperand(1), Op->getOperand(2)), 0); 7122 7123 case Intrinsic::amdgcn_groupstaticsize: { 7124 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 7125 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 7126 return Op; 7127 7128 const Module *M = MF.getFunction().getParent(); 7129 const GlobalValue *GV = 7130 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 7131 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 7132 SIInstrInfo::MO_ABS32_LO); 7133 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 7134 } 7135 case Intrinsic::amdgcn_is_shared: 7136 case Intrinsic::amdgcn_is_private: { 7137 SDLoc SL(Op); 7138 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 7139 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 7140 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 7141 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 7142 Op.getOperand(1)); 7143 7144 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 7145 DAG.getConstant(1, SL, MVT::i32)); 7146 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 7147 } 7148 case Intrinsic::amdgcn_perm: 7149 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1), 7150 Op.getOperand(2), Op.getOperand(3)); 7151 case Intrinsic::amdgcn_reloc_constant: { 7152 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 7153 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 7154 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 7155 auto RelocSymbol = cast<GlobalVariable>( 7156 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 7157 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 7158 SIInstrInfo::MO_ABS32_LO); 7159 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 7160 } 7161 default: 7162 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7163 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7164 return lowerImage(Op, ImageDimIntr, DAG, false); 7165 7166 return Op; 7167 } 7168 } 7169 7170 /// Update \p MMO based on the offset inputs to an intrinsic. 7171 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset, 7172 SDValue SOffset, SDValue Offset, 7173 SDValue VIndex = SDValue()) { 7174 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 7175 !isa<ConstantSDNode>(Offset)) { 7176 // The combined offset is not known to be constant, so we cannot represent 7177 // it in the MMO. Give up. 7178 MMO->setValue((Value *)nullptr); 7179 return; 7180 } 7181 7182 if (VIndex && (!isa<ConstantSDNode>(VIndex) || 7183 !cast<ConstantSDNode>(VIndex)->isZero())) { 7184 // The strided index component of the address is not known to be zero, so we 7185 // cannot represent it in the MMO. Give up. 7186 MMO->setValue((Value *)nullptr); 7187 return; 7188 } 7189 7190 MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() + 7191 cast<ConstantSDNode>(SOffset)->getSExtValue() + 7192 cast<ConstantSDNode>(Offset)->getSExtValue()); 7193 } 7194 7195 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 7196 SelectionDAG &DAG, 7197 unsigned NewOpcode) const { 7198 SDLoc DL(Op); 7199 7200 SDValue VData = Op.getOperand(2); 7201 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7202 SDValue Ops[] = { 7203 Op.getOperand(0), // Chain 7204 VData, // vdata 7205 Op.getOperand(3), // rsrc 7206 DAG.getConstant(0, DL, MVT::i32), // vindex 7207 Offsets.first, // voffset 7208 Op.getOperand(5), // soffset 7209 Offsets.second, // offset 7210 Op.getOperand(6), // cachepolicy 7211 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7212 }; 7213 7214 auto *M = cast<MemSDNode>(Op); 7215 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 7216 7217 EVT MemVT = VData.getValueType(); 7218 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 7219 M->getMemOperand()); 7220 } 7221 7222 // Return a value to use for the idxen operand by examining the vindex operand. 7223 static unsigned getIdxEn(SDValue VIndex) { 7224 if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex)) 7225 // No need to set idxen if vindex is known to be zero. 7226 return VIndexC->getZExtValue() != 0; 7227 return 1; 7228 } 7229 7230 SDValue 7231 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 7232 unsigned NewOpcode) const { 7233 SDLoc DL(Op); 7234 7235 SDValue VData = Op.getOperand(2); 7236 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7237 SDValue Ops[] = { 7238 Op.getOperand(0), // Chain 7239 VData, // vdata 7240 Op.getOperand(3), // rsrc 7241 Op.getOperand(4), // vindex 7242 Offsets.first, // voffset 7243 Op.getOperand(6), // soffset 7244 Offsets.second, // offset 7245 Op.getOperand(7), // cachepolicy 7246 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7247 }; 7248 7249 auto *M = cast<MemSDNode>(Op); 7250 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7251 7252 EVT MemVT = VData.getValueType(); 7253 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 7254 M->getMemOperand()); 7255 } 7256 7257 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 7258 SelectionDAG &DAG) const { 7259 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7260 SDLoc DL(Op); 7261 7262 switch (IntrID) { 7263 case Intrinsic::amdgcn_ds_ordered_add: 7264 case Intrinsic::amdgcn_ds_ordered_swap: { 7265 MemSDNode *M = cast<MemSDNode>(Op); 7266 SDValue Chain = M->getOperand(0); 7267 SDValue M0 = M->getOperand(2); 7268 SDValue Value = M->getOperand(3); 7269 unsigned IndexOperand = M->getConstantOperandVal(7); 7270 unsigned WaveRelease = M->getConstantOperandVal(8); 7271 unsigned WaveDone = M->getConstantOperandVal(9); 7272 7273 unsigned OrderedCountIndex = IndexOperand & 0x3f; 7274 IndexOperand &= ~0x3f; 7275 unsigned CountDw = 0; 7276 7277 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 7278 CountDw = (IndexOperand >> 24) & 0xf; 7279 IndexOperand &= ~(0xf << 24); 7280 7281 if (CountDw < 1 || CountDw > 4) { 7282 report_fatal_error( 7283 "ds_ordered_count: dword count must be between 1 and 4"); 7284 } 7285 } 7286 7287 if (IndexOperand) 7288 report_fatal_error("ds_ordered_count: bad index operand"); 7289 7290 if (WaveDone && !WaveRelease) 7291 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 7292 7293 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 7294 unsigned ShaderType = 7295 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 7296 unsigned Offset0 = OrderedCountIndex << 2; 7297 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 7298 (Instruction << 4); 7299 7300 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 7301 Offset1 |= (CountDw - 1) << 6; 7302 7303 unsigned Offset = Offset0 | (Offset1 << 8); 7304 7305 SDValue Ops[] = { 7306 Chain, 7307 Value, 7308 DAG.getTargetConstant(Offset, DL, MVT::i16), 7309 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 7310 }; 7311 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 7312 M->getVTList(), Ops, M->getMemoryVT(), 7313 M->getMemOperand()); 7314 } 7315 case Intrinsic::amdgcn_ds_fadd: { 7316 MemSDNode *M = cast<MemSDNode>(Op); 7317 unsigned Opc; 7318 switch (IntrID) { 7319 case Intrinsic::amdgcn_ds_fadd: 7320 Opc = ISD::ATOMIC_LOAD_FADD; 7321 break; 7322 } 7323 7324 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 7325 M->getOperand(0), M->getOperand(2), M->getOperand(3), 7326 M->getMemOperand()); 7327 } 7328 case Intrinsic::amdgcn_atomic_inc: 7329 case Intrinsic::amdgcn_atomic_dec: 7330 case Intrinsic::amdgcn_ds_fmin: 7331 case Intrinsic::amdgcn_ds_fmax: { 7332 MemSDNode *M = cast<MemSDNode>(Op); 7333 unsigned Opc; 7334 switch (IntrID) { 7335 case Intrinsic::amdgcn_atomic_inc: 7336 Opc = AMDGPUISD::ATOMIC_INC; 7337 break; 7338 case Intrinsic::amdgcn_atomic_dec: 7339 Opc = AMDGPUISD::ATOMIC_DEC; 7340 break; 7341 case Intrinsic::amdgcn_ds_fmin: 7342 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 7343 break; 7344 case Intrinsic::amdgcn_ds_fmax: 7345 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 7346 break; 7347 default: 7348 llvm_unreachable("Unknown intrinsic!"); 7349 } 7350 SDValue Ops[] = { 7351 M->getOperand(0), // Chain 7352 M->getOperand(2), // Ptr 7353 M->getOperand(3) // Value 7354 }; 7355 7356 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 7357 M->getMemoryVT(), M->getMemOperand()); 7358 } 7359 case Intrinsic::amdgcn_buffer_load: 7360 case Intrinsic::amdgcn_buffer_load_format: { 7361 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 7362 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7363 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7364 SDValue Ops[] = { 7365 Op.getOperand(0), // Chain 7366 Op.getOperand(2), // rsrc 7367 Op.getOperand(3), // vindex 7368 SDValue(), // voffset -- will be set by setBufferOffsets 7369 SDValue(), // soffset -- will be set by setBufferOffsets 7370 SDValue(), // offset -- will be set by setBufferOffsets 7371 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7372 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7373 }; 7374 setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 7375 7376 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 7377 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 7378 7379 EVT VT = Op.getValueType(); 7380 EVT IntVT = VT.changeTypeToInteger(); 7381 auto *M = cast<MemSDNode>(Op); 7382 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7383 EVT LoadVT = Op.getValueType(); 7384 7385 if (LoadVT.getScalarType() == MVT::f16) 7386 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 7387 M, DAG, Ops); 7388 7389 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 7390 if (LoadVT.getScalarType() == MVT::i8 || 7391 LoadVT.getScalarType() == MVT::i16) 7392 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 7393 7394 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 7395 M->getMemOperand(), DAG); 7396 } 7397 case Intrinsic::amdgcn_raw_buffer_load: 7398 case Intrinsic::amdgcn_raw_buffer_load_format: { 7399 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 7400 7401 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7402 SDValue Ops[] = { 7403 Op.getOperand(0), // Chain 7404 Op.getOperand(2), // rsrc 7405 DAG.getConstant(0, DL, MVT::i32), // vindex 7406 Offsets.first, // voffset 7407 Op.getOperand(4), // soffset 7408 Offsets.second, // offset 7409 Op.getOperand(5), // cachepolicy, swizzled buffer 7410 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7411 }; 7412 7413 auto *M = cast<MemSDNode>(Op); 7414 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]); 7415 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 7416 } 7417 case Intrinsic::amdgcn_struct_buffer_load: 7418 case Intrinsic::amdgcn_struct_buffer_load_format: { 7419 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 7420 7421 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7422 SDValue Ops[] = { 7423 Op.getOperand(0), // Chain 7424 Op.getOperand(2), // rsrc 7425 Op.getOperand(3), // vindex 7426 Offsets.first, // voffset 7427 Op.getOperand(5), // soffset 7428 Offsets.second, // offset 7429 Op.getOperand(6), // cachepolicy, swizzled buffer 7430 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7431 }; 7432 7433 auto *M = cast<MemSDNode>(Op); 7434 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7435 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 7436 } 7437 case Intrinsic::amdgcn_tbuffer_load: { 7438 MemSDNode *M = cast<MemSDNode>(Op); 7439 EVT LoadVT = Op.getValueType(); 7440 7441 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7442 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7443 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7444 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7445 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7446 SDValue Ops[] = { 7447 Op.getOperand(0), // Chain 7448 Op.getOperand(2), // rsrc 7449 Op.getOperand(3), // vindex 7450 Op.getOperand(4), // voffset 7451 Op.getOperand(5), // soffset 7452 Op.getOperand(6), // offset 7453 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7454 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7455 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 7456 }; 7457 7458 if (LoadVT.getScalarType() == MVT::f16) 7459 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7460 M, DAG, Ops); 7461 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7462 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7463 DAG); 7464 } 7465 case Intrinsic::amdgcn_raw_tbuffer_load: { 7466 MemSDNode *M = cast<MemSDNode>(Op); 7467 EVT LoadVT = Op.getValueType(); 7468 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7469 7470 SDValue Ops[] = { 7471 Op.getOperand(0), // Chain 7472 Op.getOperand(2), // rsrc 7473 DAG.getConstant(0, DL, MVT::i32), // vindex 7474 Offsets.first, // voffset 7475 Op.getOperand(4), // soffset 7476 Offsets.second, // offset 7477 Op.getOperand(5), // format 7478 Op.getOperand(6), // cachepolicy, swizzled buffer 7479 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7480 }; 7481 7482 if (LoadVT.getScalarType() == MVT::f16) 7483 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7484 M, DAG, Ops); 7485 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7486 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7487 DAG); 7488 } 7489 case Intrinsic::amdgcn_struct_tbuffer_load: { 7490 MemSDNode *M = cast<MemSDNode>(Op); 7491 EVT LoadVT = Op.getValueType(); 7492 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7493 7494 SDValue Ops[] = { 7495 Op.getOperand(0), // Chain 7496 Op.getOperand(2), // rsrc 7497 Op.getOperand(3), // vindex 7498 Offsets.first, // voffset 7499 Op.getOperand(5), // soffset 7500 Offsets.second, // offset 7501 Op.getOperand(6), // format 7502 Op.getOperand(7), // cachepolicy, swizzled buffer 7503 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7504 }; 7505 7506 if (LoadVT.getScalarType() == MVT::f16) 7507 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7508 M, DAG, Ops); 7509 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7510 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7511 DAG); 7512 } 7513 case Intrinsic::amdgcn_buffer_atomic_swap: 7514 case Intrinsic::amdgcn_buffer_atomic_add: 7515 case Intrinsic::amdgcn_buffer_atomic_sub: 7516 case Intrinsic::amdgcn_buffer_atomic_csub: 7517 case Intrinsic::amdgcn_buffer_atomic_smin: 7518 case Intrinsic::amdgcn_buffer_atomic_umin: 7519 case Intrinsic::amdgcn_buffer_atomic_smax: 7520 case Intrinsic::amdgcn_buffer_atomic_umax: 7521 case Intrinsic::amdgcn_buffer_atomic_and: 7522 case Intrinsic::amdgcn_buffer_atomic_or: 7523 case Intrinsic::amdgcn_buffer_atomic_xor: 7524 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7525 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7526 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7527 SDValue Ops[] = { 7528 Op.getOperand(0), // Chain 7529 Op.getOperand(2), // vdata 7530 Op.getOperand(3), // rsrc 7531 Op.getOperand(4), // vindex 7532 SDValue(), // voffset -- will be set by setBufferOffsets 7533 SDValue(), // soffset -- will be set by setBufferOffsets 7534 SDValue(), // offset -- will be set by setBufferOffsets 7535 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7536 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7537 }; 7538 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7539 7540 EVT VT = Op.getValueType(); 7541 7542 auto *M = cast<MemSDNode>(Op); 7543 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7544 unsigned Opcode = 0; 7545 7546 switch (IntrID) { 7547 case Intrinsic::amdgcn_buffer_atomic_swap: 7548 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7549 break; 7550 case Intrinsic::amdgcn_buffer_atomic_add: 7551 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7552 break; 7553 case Intrinsic::amdgcn_buffer_atomic_sub: 7554 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7555 break; 7556 case Intrinsic::amdgcn_buffer_atomic_csub: 7557 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7558 break; 7559 case Intrinsic::amdgcn_buffer_atomic_smin: 7560 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7561 break; 7562 case Intrinsic::amdgcn_buffer_atomic_umin: 7563 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7564 break; 7565 case Intrinsic::amdgcn_buffer_atomic_smax: 7566 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7567 break; 7568 case Intrinsic::amdgcn_buffer_atomic_umax: 7569 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7570 break; 7571 case Intrinsic::amdgcn_buffer_atomic_and: 7572 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7573 break; 7574 case Intrinsic::amdgcn_buffer_atomic_or: 7575 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7576 break; 7577 case Intrinsic::amdgcn_buffer_atomic_xor: 7578 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7579 break; 7580 case Intrinsic::amdgcn_buffer_atomic_fadd: 7581 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7582 DiagnosticInfoUnsupported 7583 NoFpRet(DAG.getMachineFunction().getFunction(), 7584 "return versions of fp atomics not supported", 7585 DL.getDebugLoc(), DS_Error); 7586 DAG.getContext()->diagnose(NoFpRet); 7587 return SDValue(); 7588 } 7589 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7590 break; 7591 default: 7592 llvm_unreachable("unhandled atomic opcode"); 7593 } 7594 7595 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7596 M->getMemOperand()); 7597 } 7598 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7599 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7600 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7601 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7602 case Intrinsic::amdgcn_raw_buffer_atomic_fmin: 7603 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7604 case Intrinsic::amdgcn_struct_buffer_atomic_fmin: 7605 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7606 case Intrinsic::amdgcn_raw_buffer_atomic_fmax: 7607 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7608 case Intrinsic::amdgcn_struct_buffer_atomic_fmax: 7609 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7610 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7611 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7612 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7613 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7614 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7615 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7616 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7617 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7618 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7619 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7620 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7621 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7622 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7623 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7624 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7625 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7626 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7627 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7628 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7629 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7630 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7631 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7632 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7633 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7634 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7635 return lowerStructBufferAtomicIntrin(Op, DAG, 7636 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7637 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7638 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7639 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7640 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7641 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7642 return lowerStructBufferAtomicIntrin(Op, DAG, 7643 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7644 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7645 return lowerStructBufferAtomicIntrin(Op, DAG, 7646 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7647 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7648 return lowerStructBufferAtomicIntrin(Op, DAG, 7649 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7650 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7651 return lowerStructBufferAtomicIntrin(Op, DAG, 7652 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7653 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7654 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7655 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7656 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7657 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7658 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7659 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7660 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7661 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7662 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7663 7664 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7665 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7666 unsigned IdxEn = getIdxEn(Op.getOperand(5)); 7667 SDValue Ops[] = { 7668 Op.getOperand(0), // Chain 7669 Op.getOperand(2), // src 7670 Op.getOperand(3), // cmp 7671 Op.getOperand(4), // rsrc 7672 Op.getOperand(5), // vindex 7673 SDValue(), // voffset -- will be set by setBufferOffsets 7674 SDValue(), // soffset -- will be set by setBufferOffsets 7675 SDValue(), // offset -- will be set by setBufferOffsets 7676 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7677 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7678 }; 7679 setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7680 7681 EVT VT = Op.getValueType(); 7682 auto *M = cast<MemSDNode>(Op); 7683 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7684 7685 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7686 Op->getVTList(), Ops, VT, M->getMemOperand()); 7687 } 7688 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7689 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7690 SDValue Ops[] = { 7691 Op.getOperand(0), // Chain 7692 Op.getOperand(2), // src 7693 Op.getOperand(3), // cmp 7694 Op.getOperand(4), // rsrc 7695 DAG.getConstant(0, DL, MVT::i32), // vindex 7696 Offsets.first, // voffset 7697 Op.getOperand(6), // soffset 7698 Offsets.second, // offset 7699 Op.getOperand(7), // cachepolicy 7700 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7701 }; 7702 EVT VT = Op.getValueType(); 7703 auto *M = cast<MemSDNode>(Op); 7704 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]); 7705 7706 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7707 Op->getVTList(), Ops, VT, M->getMemOperand()); 7708 } 7709 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7710 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7711 SDValue Ops[] = { 7712 Op.getOperand(0), // Chain 7713 Op.getOperand(2), // src 7714 Op.getOperand(3), // cmp 7715 Op.getOperand(4), // rsrc 7716 Op.getOperand(5), // vindex 7717 Offsets.first, // voffset 7718 Op.getOperand(7), // soffset 7719 Offsets.second, // offset 7720 Op.getOperand(8), // cachepolicy 7721 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7722 }; 7723 EVT VT = Op.getValueType(); 7724 auto *M = cast<MemSDNode>(Op); 7725 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7726 7727 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7728 Op->getVTList(), Ops, VT, M->getMemOperand()); 7729 } 7730 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 7731 MemSDNode *M = cast<MemSDNode>(Op); 7732 SDValue NodePtr = M->getOperand(2); 7733 SDValue RayExtent = M->getOperand(3); 7734 SDValue RayOrigin = M->getOperand(4); 7735 SDValue RayDir = M->getOperand(5); 7736 SDValue RayInvDir = M->getOperand(6); 7737 SDValue TDescr = M->getOperand(7); 7738 7739 assert(NodePtr.getValueType() == MVT::i32 || 7740 NodePtr.getValueType() == MVT::i64); 7741 assert(RayDir.getValueType() == MVT::v3f16 || 7742 RayDir.getValueType() == MVT::v3f32); 7743 7744 if (!Subtarget->hasGFX10_AEncoding()) { 7745 emitRemovedIntrinsicError(DAG, DL, Op.getValueType()); 7746 return SDValue(); 7747 } 7748 7749 const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16; 7750 const bool Is64 = NodePtr.getValueType() == MVT::i64; 7751 const unsigned NumVDataDwords = 4; 7752 const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11); 7753 const bool UseNSA = Subtarget->hasNSAEncoding() && 7754 NumVAddrDwords <= Subtarget->getNSAMaxSize(); 7755 const unsigned BaseOpcodes[2][2] = { 7756 {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16}, 7757 {AMDGPU::IMAGE_BVH64_INTERSECT_RAY, 7758 AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}}; 7759 int Opcode; 7760 if (UseNSA) { 7761 Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16], 7762 AMDGPU::MIMGEncGfx10NSA, NumVDataDwords, 7763 NumVAddrDwords); 7764 } else { 7765 Opcode = AMDGPU::getMIMGOpcode( 7766 BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords, 7767 PowerOf2Ceil(NumVAddrDwords)); 7768 } 7769 assert(Opcode != -1); 7770 7771 SmallVector<SDValue, 16> Ops; 7772 7773 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) { 7774 SmallVector<SDValue, 3> Lanes; 7775 DAG.ExtractVectorElements(Op, Lanes, 0, 3); 7776 if (Lanes[0].getValueSizeInBits() == 32) { 7777 for (unsigned I = 0; I < 3; ++I) 7778 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I])); 7779 } else { 7780 if (IsAligned) { 7781 Ops.push_back( 7782 DAG.getBitcast(MVT::i32, 7783 DAG.getBuildVector(MVT::v2f16, DL, 7784 { Lanes[0], Lanes[1] }))); 7785 Ops.push_back(Lanes[2]); 7786 } else { 7787 SDValue Elt0 = Ops.pop_back_val(); 7788 Ops.push_back( 7789 DAG.getBitcast(MVT::i32, 7790 DAG.getBuildVector(MVT::v2f16, DL, 7791 { Elt0, Lanes[0] }))); 7792 Ops.push_back( 7793 DAG.getBitcast(MVT::i32, 7794 DAG.getBuildVector(MVT::v2f16, DL, 7795 { Lanes[1], Lanes[2] }))); 7796 } 7797 } 7798 }; 7799 7800 if (Is64) 7801 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2); 7802 else 7803 Ops.push_back(NodePtr); 7804 7805 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7806 packLanes(RayOrigin, true); 7807 packLanes(RayDir, true); 7808 packLanes(RayInvDir, false); 7809 7810 if (!UseNSA) { 7811 // Build a single vector containing all the operands so far prepared. 7812 if (NumVAddrDwords > 8) { 7813 SDValue Undef = DAG.getUNDEF(MVT::i32); 7814 Ops.append(16 - Ops.size(), Undef); 7815 } 7816 assert(Ops.size() == 8 || Ops.size() == 16); 7817 SDValue MergedOps = DAG.getBuildVector( 7818 Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops); 7819 Ops.clear(); 7820 Ops.push_back(MergedOps); 7821 } 7822 7823 Ops.push_back(TDescr); 7824 if (IsA16) 7825 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1)); 7826 Ops.push_back(M->getChain()); 7827 7828 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops); 7829 MachineMemOperand *MemRef = M->getMemOperand(); 7830 DAG.setNodeMemRefs(NewNode, {MemRef}); 7831 return SDValue(NewNode, 0); 7832 } 7833 case Intrinsic::amdgcn_global_atomic_fadd: 7834 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7835 DiagnosticInfoUnsupported 7836 NoFpRet(DAG.getMachineFunction().getFunction(), 7837 "return versions of fp atomics not supported", 7838 DL.getDebugLoc(), DS_Error); 7839 DAG.getContext()->diagnose(NoFpRet); 7840 return SDValue(); 7841 } 7842 LLVM_FALLTHROUGH; 7843 case Intrinsic::amdgcn_global_atomic_fmin: 7844 case Intrinsic::amdgcn_global_atomic_fmax: 7845 case Intrinsic::amdgcn_flat_atomic_fadd: 7846 case Intrinsic::amdgcn_flat_atomic_fmin: 7847 case Intrinsic::amdgcn_flat_atomic_fmax: { 7848 MemSDNode *M = cast<MemSDNode>(Op); 7849 SDValue Ops[] = { 7850 M->getOperand(0), // Chain 7851 M->getOperand(2), // Ptr 7852 M->getOperand(3) // Value 7853 }; 7854 unsigned Opcode = 0; 7855 switch (IntrID) { 7856 case Intrinsic::amdgcn_global_atomic_fadd: 7857 case Intrinsic::amdgcn_flat_atomic_fadd: { 7858 EVT VT = Op.getOperand(3).getValueType(); 7859 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7860 DAG.getVTList(VT, MVT::Other), Ops, 7861 M->getMemOperand()); 7862 } 7863 case Intrinsic::amdgcn_global_atomic_fmin: 7864 case Intrinsic::amdgcn_flat_atomic_fmin: { 7865 Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN; 7866 break; 7867 } 7868 case Intrinsic::amdgcn_global_atomic_fmax: 7869 case Intrinsic::amdgcn_flat_atomic_fmax: { 7870 Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX; 7871 break; 7872 } 7873 default: 7874 llvm_unreachable("unhandled atomic opcode"); 7875 } 7876 return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op), 7877 M->getVTList(), Ops, M->getMemoryVT(), 7878 M->getMemOperand()); 7879 } 7880 default: 7881 7882 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7883 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7884 return lowerImage(Op, ImageDimIntr, DAG, true); 7885 7886 return SDValue(); 7887 } 7888 } 7889 7890 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7891 // dwordx4 if on SI. 7892 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7893 SDVTList VTList, 7894 ArrayRef<SDValue> Ops, EVT MemVT, 7895 MachineMemOperand *MMO, 7896 SelectionDAG &DAG) const { 7897 EVT VT = VTList.VTs[0]; 7898 EVT WidenedVT = VT; 7899 EVT WidenedMemVT = MemVT; 7900 if (!Subtarget->hasDwordx3LoadStores() && 7901 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7902 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7903 WidenedVT.getVectorElementType(), 4); 7904 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7905 WidenedMemVT.getVectorElementType(), 4); 7906 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7907 } 7908 7909 assert(VTList.NumVTs == 2); 7910 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7911 7912 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7913 WidenedMemVT, MMO); 7914 if (WidenedVT != VT) { 7915 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7916 DAG.getVectorIdxConstant(0, DL)); 7917 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7918 } 7919 return NewOp; 7920 } 7921 7922 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG, 7923 bool ImageStore) const { 7924 EVT StoreVT = VData.getValueType(); 7925 7926 // No change for f16 and legal vector D16 types. 7927 if (!StoreVT.isVector()) 7928 return VData; 7929 7930 SDLoc DL(VData); 7931 unsigned NumElements = StoreVT.getVectorNumElements(); 7932 7933 if (Subtarget->hasUnpackedD16VMem()) { 7934 // We need to unpack the packed data to store. 7935 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7936 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7937 7938 EVT EquivStoreVT = 7939 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements); 7940 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7941 return DAG.UnrollVectorOp(ZExt.getNode()); 7942 } 7943 7944 // The sq block of gfx8.1 does not estimate register use correctly for d16 7945 // image store instructions. The data operand is computed as if it were not a 7946 // d16 image instruction. 7947 if (ImageStore && Subtarget->hasImageStoreD16Bug()) { 7948 // Bitcast to i16 7949 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7950 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7951 7952 // Decompose into scalars 7953 SmallVector<SDValue, 4> Elts; 7954 DAG.ExtractVectorElements(IntVData, Elts); 7955 7956 // Group pairs of i16 into v2i16 and bitcast to i32 7957 SmallVector<SDValue, 4> PackedElts; 7958 for (unsigned I = 0; I < Elts.size() / 2; I += 1) { 7959 SDValue Pair = 7960 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]}); 7961 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7962 PackedElts.push_back(IntPair); 7963 } 7964 if ((NumElements % 2) == 1) { 7965 // Handle v3i16 7966 unsigned I = Elts.size() / 2; 7967 SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL, 7968 {Elts[I * 2], DAG.getUNDEF(MVT::i16)}); 7969 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7970 PackedElts.push_back(IntPair); 7971 } 7972 7973 // Pad using UNDEF 7974 PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32)); 7975 7976 // Build final vector 7977 EVT VecVT = 7978 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size()); 7979 return DAG.getBuildVector(VecVT, DL, PackedElts); 7980 } 7981 7982 if (NumElements == 3) { 7983 EVT IntStoreVT = 7984 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits()); 7985 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7986 7987 EVT WidenedStoreVT = EVT::getVectorVT( 7988 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1); 7989 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(), 7990 WidenedStoreVT.getStoreSizeInBits()); 7991 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData); 7992 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt); 7993 } 7994 7995 assert(isTypeLegal(StoreVT)); 7996 return VData; 7997 } 7998 7999 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 8000 SelectionDAG &DAG) const { 8001 SDLoc DL(Op); 8002 SDValue Chain = Op.getOperand(0); 8003 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 8004 MachineFunction &MF = DAG.getMachineFunction(); 8005 8006 switch (IntrinsicID) { 8007 case Intrinsic::amdgcn_exp_compr: { 8008 SDValue Src0 = Op.getOperand(4); 8009 SDValue Src1 = Op.getOperand(5); 8010 // Hack around illegal type on SI by directly selecting it. 8011 if (isTypeLegal(Src0.getValueType())) 8012 return SDValue(); 8013 8014 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 8015 SDValue Undef = DAG.getUNDEF(MVT::f32); 8016 const SDValue Ops[] = { 8017 Op.getOperand(2), // tgt 8018 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 8019 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 8020 Undef, // src2 8021 Undef, // src3 8022 Op.getOperand(7), // vm 8023 DAG.getTargetConstant(1, DL, MVT::i1), // compr 8024 Op.getOperand(3), // en 8025 Op.getOperand(0) // Chain 8026 }; 8027 8028 unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 8029 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 8030 } 8031 case Intrinsic::amdgcn_s_barrier: { 8032 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 8033 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 8034 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 8035 if (WGSize <= ST.getWavefrontSize()) 8036 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 8037 Op.getOperand(0)), 0); 8038 } 8039 return SDValue(); 8040 }; 8041 case Intrinsic::amdgcn_tbuffer_store: { 8042 SDValue VData = Op.getOperand(2); 8043 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 8044 if (IsD16) 8045 VData = handleD16VData(VData, DAG); 8046 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 8047 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 8048 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 8049 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 8050 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 8051 SDValue Ops[] = { 8052 Chain, 8053 VData, // vdata 8054 Op.getOperand(3), // rsrc 8055 Op.getOperand(4), // vindex 8056 Op.getOperand(5), // voffset 8057 Op.getOperand(6), // soffset 8058 Op.getOperand(7), // offset 8059 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 8060 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 8061 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 8062 }; 8063 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 8064 AMDGPUISD::TBUFFER_STORE_FORMAT; 8065 MemSDNode *M = cast<MemSDNode>(Op); 8066 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8067 M->getMemoryVT(), M->getMemOperand()); 8068 } 8069 8070 case Intrinsic::amdgcn_struct_tbuffer_store: { 8071 SDValue VData = Op.getOperand(2); 8072 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 8073 if (IsD16) 8074 VData = handleD16VData(VData, DAG); 8075 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 8076 SDValue Ops[] = { 8077 Chain, 8078 VData, // vdata 8079 Op.getOperand(3), // rsrc 8080 Op.getOperand(4), // vindex 8081 Offsets.first, // voffset 8082 Op.getOperand(6), // soffset 8083 Offsets.second, // offset 8084 Op.getOperand(7), // format 8085 Op.getOperand(8), // cachepolicy, swizzled buffer 8086 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 8087 }; 8088 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 8089 AMDGPUISD::TBUFFER_STORE_FORMAT; 8090 MemSDNode *M = cast<MemSDNode>(Op); 8091 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8092 M->getMemoryVT(), M->getMemOperand()); 8093 } 8094 8095 case Intrinsic::amdgcn_raw_tbuffer_store: { 8096 SDValue VData = Op.getOperand(2); 8097 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 8098 if (IsD16) 8099 VData = handleD16VData(VData, DAG); 8100 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 8101 SDValue Ops[] = { 8102 Chain, 8103 VData, // vdata 8104 Op.getOperand(3), // rsrc 8105 DAG.getConstant(0, DL, MVT::i32), // vindex 8106 Offsets.first, // voffset 8107 Op.getOperand(5), // soffset 8108 Offsets.second, // offset 8109 Op.getOperand(6), // format 8110 Op.getOperand(7), // cachepolicy, swizzled buffer 8111 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 8112 }; 8113 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 8114 AMDGPUISD::TBUFFER_STORE_FORMAT; 8115 MemSDNode *M = cast<MemSDNode>(Op); 8116 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8117 M->getMemoryVT(), M->getMemOperand()); 8118 } 8119 8120 case Intrinsic::amdgcn_buffer_store: 8121 case Intrinsic::amdgcn_buffer_store_format: { 8122 SDValue VData = Op.getOperand(2); 8123 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 8124 if (IsD16) 8125 VData = handleD16VData(VData, DAG); 8126 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 8127 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 8128 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 8129 SDValue Ops[] = { 8130 Chain, 8131 VData, 8132 Op.getOperand(3), // rsrc 8133 Op.getOperand(4), // vindex 8134 SDValue(), // voffset -- will be set by setBufferOffsets 8135 SDValue(), // soffset -- will be set by setBufferOffsets 8136 SDValue(), // offset -- will be set by setBufferOffsets 8137 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 8138 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 8139 }; 8140 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 8141 8142 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 8143 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 8144 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 8145 MemSDNode *M = cast<MemSDNode>(Op); 8146 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 8147 8148 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 8149 EVT VDataType = VData.getValueType().getScalarType(); 8150 if (VDataType == MVT::i8 || VDataType == MVT::i16) 8151 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 8152 8153 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8154 M->getMemoryVT(), M->getMemOperand()); 8155 } 8156 8157 case Intrinsic::amdgcn_raw_buffer_store: 8158 case Intrinsic::amdgcn_raw_buffer_store_format: { 8159 const bool IsFormat = 8160 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 8161 8162 SDValue VData = Op.getOperand(2); 8163 EVT VDataVT = VData.getValueType(); 8164 EVT EltType = VDataVT.getScalarType(); 8165 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 8166 if (IsD16) { 8167 VData = handleD16VData(VData, DAG); 8168 VDataVT = VData.getValueType(); 8169 } 8170 8171 if (!isTypeLegal(VDataVT)) { 8172 VData = 8173 DAG.getNode(ISD::BITCAST, DL, 8174 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 8175 } 8176 8177 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 8178 SDValue Ops[] = { 8179 Chain, 8180 VData, 8181 Op.getOperand(3), // rsrc 8182 DAG.getConstant(0, DL, MVT::i32), // vindex 8183 Offsets.first, // voffset 8184 Op.getOperand(5), // soffset 8185 Offsets.second, // offset 8186 Op.getOperand(6), // cachepolicy, swizzled buffer 8187 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 8188 }; 8189 unsigned Opc = 8190 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 8191 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 8192 MemSDNode *M = cast<MemSDNode>(Op); 8193 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 8194 8195 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 8196 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 8197 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 8198 8199 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8200 M->getMemoryVT(), M->getMemOperand()); 8201 } 8202 8203 case Intrinsic::amdgcn_struct_buffer_store: 8204 case Intrinsic::amdgcn_struct_buffer_store_format: { 8205 const bool IsFormat = 8206 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 8207 8208 SDValue VData = Op.getOperand(2); 8209 EVT VDataVT = VData.getValueType(); 8210 EVT EltType = VDataVT.getScalarType(); 8211 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 8212 8213 if (IsD16) { 8214 VData = handleD16VData(VData, DAG); 8215 VDataVT = VData.getValueType(); 8216 } 8217 8218 if (!isTypeLegal(VDataVT)) { 8219 VData = 8220 DAG.getNode(ISD::BITCAST, DL, 8221 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 8222 } 8223 8224 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 8225 SDValue Ops[] = { 8226 Chain, 8227 VData, 8228 Op.getOperand(3), // rsrc 8229 Op.getOperand(4), // vindex 8230 Offsets.first, // voffset 8231 Op.getOperand(6), // soffset 8232 Offsets.second, // offset 8233 Op.getOperand(7), // cachepolicy, swizzled buffer 8234 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 8235 }; 8236 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 8237 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 8238 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 8239 MemSDNode *M = cast<MemSDNode>(Op); 8240 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 8241 8242 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 8243 EVT VDataType = VData.getValueType().getScalarType(); 8244 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 8245 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 8246 8247 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8248 M->getMemoryVT(), M->getMemOperand()); 8249 } 8250 case Intrinsic::amdgcn_raw_buffer_load_lds: 8251 case Intrinsic::amdgcn_struct_buffer_load_lds: { 8252 unsigned Opc; 8253 bool HasVIndex = IntrinsicID == Intrinsic::amdgcn_struct_buffer_load_lds; 8254 unsigned OpOffset = HasVIndex ? 1 : 0; 8255 SDValue VOffset = Op.getOperand(5 + OpOffset); 8256 auto CVOffset = dyn_cast<ConstantSDNode>(VOffset); 8257 bool HasVOffset = !CVOffset || !CVOffset->isZero(); 8258 unsigned Size = Op->getConstantOperandVal(4); 8259 8260 switch (Size) { 8261 default: 8262 return SDValue(); 8263 case 1: 8264 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_UBYTE_LDS_BOTHEN 8265 : AMDGPU::BUFFER_LOAD_UBYTE_LDS_IDXEN 8266 : HasVOffset ? AMDGPU::BUFFER_LOAD_UBYTE_LDS_OFFEN 8267 : AMDGPU::BUFFER_LOAD_UBYTE_LDS_OFFSET; 8268 break; 8269 case 2: 8270 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_USHORT_LDS_BOTHEN 8271 : AMDGPU::BUFFER_LOAD_USHORT_LDS_IDXEN 8272 : HasVOffset ? AMDGPU::BUFFER_LOAD_USHORT_LDS_OFFEN 8273 : AMDGPU::BUFFER_LOAD_USHORT_LDS_OFFSET; 8274 break; 8275 case 4: 8276 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_DWORD_LDS_BOTHEN 8277 : AMDGPU::BUFFER_LOAD_DWORD_LDS_IDXEN 8278 : HasVOffset ? AMDGPU::BUFFER_LOAD_DWORD_LDS_OFFEN 8279 : AMDGPU::BUFFER_LOAD_DWORD_LDS_OFFSET; 8280 break; 8281 } 8282 8283 SDValue M0Val = copyToM0(DAG, Chain, DL, Op.getOperand(3)); 8284 8285 SmallVector<SDValue, 8> Ops; 8286 8287 if (HasVIndex && HasVOffset) 8288 Ops.push_back(DAG.getBuildVector(MVT::v2i32, DL, 8289 { Op.getOperand(5), // VIndex 8290 VOffset })); 8291 else if (HasVIndex) 8292 Ops.push_back(Op.getOperand(5)); 8293 else if (HasVOffset) 8294 Ops.push_back(VOffset); 8295 8296 Ops.push_back(Op.getOperand(2)); // rsrc 8297 Ops.push_back(Op.getOperand(6 + OpOffset)); // soffset 8298 Ops.push_back(Op.getOperand(7 + OpOffset)); // imm offset 8299 unsigned Aux = Op.getConstantOperandVal(8 + OpOffset); 8300 Ops.push_back( 8301 DAG.getTargetConstant(Aux & AMDGPU::CPol::ALL, DL, MVT::i8)); // cpol 8302 Ops.push_back( 8303 DAG.getTargetConstant((Aux >> 3) & 1, DL, MVT::i8)); // swz 8304 Ops.push_back(M0Val.getValue(0)); // Chain 8305 Ops.push_back(M0Val.getValue(1)); // Glue 8306 8307 auto *M = cast<MemSDNode>(Op); 8308 MachineMemOperand *LoadMMO = M->getMemOperand(); 8309 MachinePointerInfo LoadPtrI = LoadMMO->getPointerInfo(); 8310 LoadPtrI.Offset = Op->getConstantOperandVal(7 + OpOffset); 8311 MachinePointerInfo StorePtrI = LoadPtrI; 8312 StorePtrI.V = nullptr; 8313 StorePtrI.AddrSpace = AMDGPUAS::LOCAL_ADDRESS; 8314 8315 auto F = LoadMMO->getFlags() & 8316 ~(MachineMemOperand::MOStore | MachineMemOperand::MOLoad); 8317 LoadMMO = MF.getMachineMemOperand(LoadPtrI, F | MachineMemOperand::MOLoad, 8318 Size, LoadMMO->getBaseAlign()); 8319 8320 MachineMemOperand *StoreMMO = 8321 MF.getMachineMemOperand(StorePtrI, F | MachineMemOperand::MOStore, 8322 sizeof(int32_t), LoadMMO->getBaseAlign()); 8323 8324 auto Load = DAG.getMachineNode(Opc, DL, M->getVTList(), Ops); 8325 DAG.setNodeMemRefs(Load, {LoadMMO, StoreMMO}); 8326 8327 return SDValue(Load, 0); 8328 } 8329 case Intrinsic::amdgcn_global_load_lds: { 8330 unsigned Opc; 8331 unsigned Size = Op->getConstantOperandVal(4); 8332 switch (Size) { 8333 default: 8334 return SDValue(); 8335 case 1: 8336 Opc = AMDGPU::GLOBAL_LOAD_LDS_UBYTE; 8337 break; 8338 case 2: 8339 Opc = AMDGPU::GLOBAL_LOAD_LDS_USHORT; 8340 break; 8341 case 4: 8342 Opc = AMDGPU::GLOBAL_LOAD_LDS_DWORD; 8343 break; 8344 } 8345 8346 auto *M = cast<MemSDNode>(Op); 8347 SDValue M0Val = copyToM0(DAG, Chain, DL, Op.getOperand(3)); 8348 8349 SmallVector<SDValue, 6> Ops; 8350 8351 SDValue Addr = Op.getOperand(2); // Global ptr 8352 SDValue VOffset; 8353 // Try to split SAddr and VOffset. Global and LDS pointers share the same 8354 // immediate offset, so we cannot use a regular SelectGlobalSAddr(). 8355 if (Addr->isDivergent() && Addr.getOpcode() == ISD::ADD) { 8356 SDValue LHS = Addr.getOperand(0); 8357 SDValue RHS = Addr.getOperand(1); 8358 8359 if (LHS->isDivergent()) 8360 std::swap(LHS, RHS); 8361 8362 if (!LHS->isDivergent() && RHS.getOpcode() == ISD::ZERO_EXTEND && 8363 RHS.getOperand(0).getValueType() == MVT::i32) { 8364 // add (i64 sgpr), (zero_extend (i32 vgpr)) 8365 Addr = LHS; 8366 VOffset = RHS.getOperand(0); 8367 } 8368 } 8369 8370 Ops.push_back(Addr); 8371 if (!Addr->isDivergent()) { 8372 Opc = AMDGPU::getGlobalSaddrOp(Opc); 8373 if (!VOffset) 8374 VOffset = SDValue( 8375 DAG.getMachineNode(AMDGPU::V_MOV_B32_e32, DL, MVT::i32, 8376 DAG.getTargetConstant(0, DL, MVT::i32)), 0); 8377 Ops.push_back(VOffset); 8378 } 8379 8380 Ops.push_back(Op.getOperand(5)); // Offset 8381 Ops.push_back(Op.getOperand(6)); // CPol 8382 Ops.push_back(M0Val.getValue(0)); // Chain 8383 Ops.push_back(M0Val.getValue(1)); // Glue 8384 8385 MachineMemOperand *LoadMMO = M->getMemOperand(); 8386 MachinePointerInfo LoadPtrI = LoadMMO->getPointerInfo(); 8387 LoadPtrI.Offset = Op->getConstantOperandVal(5); 8388 MachinePointerInfo StorePtrI = LoadPtrI; 8389 LoadPtrI.AddrSpace = AMDGPUAS::GLOBAL_ADDRESS; 8390 StorePtrI.AddrSpace = AMDGPUAS::LOCAL_ADDRESS; 8391 auto F = LoadMMO->getFlags() & 8392 ~(MachineMemOperand::MOStore | MachineMemOperand::MOLoad); 8393 LoadMMO = MF.getMachineMemOperand(LoadPtrI, F | MachineMemOperand::MOLoad, 8394 Size, LoadMMO->getBaseAlign()); 8395 MachineMemOperand *StoreMMO = 8396 MF.getMachineMemOperand(StorePtrI, F | MachineMemOperand::MOStore, 8397 sizeof(int32_t), Align(4)); 8398 8399 auto Load = DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops); 8400 DAG.setNodeMemRefs(Load, {LoadMMO, StoreMMO}); 8401 8402 return SDValue(Load, 0); 8403 } 8404 case Intrinsic::amdgcn_end_cf: 8405 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 8406 Op->getOperand(2), Chain), 0); 8407 8408 default: { 8409 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 8410 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 8411 return lowerImage(Op, ImageDimIntr, DAG, true); 8412 8413 return Op; 8414 } 8415 } 8416 } 8417 8418 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 8419 // offset (the offset that is included in bounds checking and swizzling, to be 8420 // split between the instruction's voffset and immoffset fields) and soffset 8421 // (the offset that is excluded from bounds checking and swizzling, to go in 8422 // the instruction's soffset field). This function takes the first kind of 8423 // offset and figures out how to split it between voffset and immoffset. 8424 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 8425 SDValue Offset, SelectionDAG &DAG) const { 8426 SDLoc DL(Offset); 8427 const unsigned MaxImm = 4095; 8428 SDValue N0 = Offset; 8429 ConstantSDNode *C1 = nullptr; 8430 8431 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 8432 N0 = SDValue(); 8433 else if (DAG.isBaseWithConstantOffset(N0)) { 8434 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 8435 N0 = N0.getOperand(0); 8436 } 8437 8438 if (C1) { 8439 unsigned ImmOffset = C1->getZExtValue(); 8440 // If the immediate value is too big for the immoffset field, put the value 8441 // and -4096 into the immoffset field so that the value that is copied/added 8442 // for the voffset field is a multiple of 4096, and it stands more chance 8443 // of being CSEd with the copy/add for another similar load/store. 8444 // However, do not do that rounding down to a multiple of 4096 if that is a 8445 // negative number, as it appears to be illegal to have a negative offset 8446 // in the vgpr, even if adding the immediate offset makes it positive. 8447 unsigned Overflow = ImmOffset & ~MaxImm; 8448 ImmOffset -= Overflow; 8449 if ((int32_t)Overflow < 0) { 8450 Overflow += ImmOffset; 8451 ImmOffset = 0; 8452 } 8453 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 8454 if (Overflow) { 8455 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 8456 if (!N0) 8457 N0 = OverflowVal; 8458 else { 8459 SDValue Ops[] = { N0, OverflowVal }; 8460 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 8461 } 8462 } 8463 } 8464 if (!N0) 8465 N0 = DAG.getConstant(0, DL, MVT::i32); 8466 if (!C1) 8467 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 8468 return {N0, SDValue(C1, 0)}; 8469 } 8470 8471 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 8472 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 8473 // pointed to by Offsets. 8474 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 8475 SelectionDAG &DAG, SDValue *Offsets, 8476 Align Alignment) const { 8477 SDLoc DL(CombinedOffset); 8478 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 8479 uint32_t Imm = C->getZExtValue(); 8480 uint32_t SOffset, ImmOffset; 8481 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 8482 Alignment)) { 8483 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 8484 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 8485 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 8486 return; 8487 } 8488 } 8489 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 8490 SDValue N0 = CombinedOffset.getOperand(0); 8491 SDValue N1 = CombinedOffset.getOperand(1); 8492 uint32_t SOffset, ImmOffset; 8493 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 8494 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 8495 Subtarget, Alignment)) { 8496 Offsets[0] = N0; 8497 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 8498 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 8499 return; 8500 } 8501 } 8502 Offsets[0] = CombinedOffset; 8503 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 8504 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 8505 } 8506 8507 // Handle 8 bit and 16 bit buffer loads 8508 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 8509 EVT LoadVT, SDLoc DL, 8510 ArrayRef<SDValue> Ops, 8511 MemSDNode *M) const { 8512 EVT IntVT = LoadVT.changeTypeToInteger(); 8513 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 8514 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 8515 8516 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 8517 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 8518 Ops, IntVT, 8519 M->getMemOperand()); 8520 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 8521 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 8522 8523 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 8524 } 8525 8526 // Handle 8 bit and 16 bit buffer stores 8527 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 8528 EVT VDataType, SDLoc DL, 8529 SDValue Ops[], 8530 MemSDNode *M) const { 8531 if (VDataType == MVT::f16) 8532 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 8533 8534 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 8535 Ops[1] = BufferStoreExt; 8536 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 8537 AMDGPUISD::BUFFER_STORE_SHORT; 8538 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 8539 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 8540 M->getMemOperand()); 8541 } 8542 8543 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 8544 ISD::LoadExtType ExtType, SDValue Op, 8545 const SDLoc &SL, EVT VT) { 8546 if (VT.bitsLT(Op.getValueType())) 8547 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 8548 8549 switch (ExtType) { 8550 case ISD::SEXTLOAD: 8551 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 8552 case ISD::ZEXTLOAD: 8553 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 8554 case ISD::EXTLOAD: 8555 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 8556 case ISD::NON_EXTLOAD: 8557 return Op; 8558 } 8559 8560 llvm_unreachable("invalid ext type"); 8561 } 8562 8563 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 8564 SelectionDAG &DAG = DCI.DAG; 8565 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 8566 return SDValue(); 8567 8568 // FIXME: Constant loads should all be marked invariant. 8569 unsigned AS = Ld->getAddressSpace(); 8570 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 8571 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 8572 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 8573 return SDValue(); 8574 8575 // Don't do this early, since it may interfere with adjacent load merging for 8576 // illegal types. We can avoid losing alignment information for exotic types 8577 // pre-legalize. 8578 EVT MemVT = Ld->getMemoryVT(); 8579 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 8580 MemVT.getSizeInBits() >= 32) 8581 return SDValue(); 8582 8583 SDLoc SL(Ld); 8584 8585 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 8586 "unexpected vector extload"); 8587 8588 // TODO: Drop only high part of range. 8589 SDValue Ptr = Ld->getBasePtr(); 8590 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 8591 MVT::i32, SL, Ld->getChain(), Ptr, 8592 Ld->getOffset(), 8593 Ld->getPointerInfo(), MVT::i32, 8594 Ld->getAlignment(), 8595 Ld->getMemOperand()->getFlags(), 8596 Ld->getAAInfo(), 8597 nullptr); // Drop ranges 8598 8599 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 8600 if (MemVT.isFloatingPoint()) { 8601 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 8602 "unexpected fp extload"); 8603 TruncVT = MemVT.changeTypeToInteger(); 8604 } 8605 8606 SDValue Cvt = NewLoad; 8607 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 8608 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 8609 DAG.getValueType(TruncVT)); 8610 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 8611 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 8612 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 8613 } else { 8614 assert(Ld->getExtensionType() == ISD::EXTLOAD); 8615 } 8616 8617 EVT VT = Ld->getValueType(0); 8618 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 8619 8620 DCI.AddToWorklist(Cvt.getNode()); 8621 8622 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 8623 // the appropriate extension from the 32-bit load. 8624 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 8625 DCI.AddToWorklist(Cvt.getNode()); 8626 8627 // Handle conversion back to floating point if necessary. 8628 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 8629 8630 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 8631 } 8632 8633 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 8634 SDLoc DL(Op); 8635 LoadSDNode *Load = cast<LoadSDNode>(Op); 8636 ISD::LoadExtType ExtType = Load->getExtensionType(); 8637 EVT MemVT = Load->getMemoryVT(); 8638 8639 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 8640 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 8641 return SDValue(); 8642 8643 // FIXME: Copied from PPC 8644 // First, load into 32 bits, then truncate to 1 bit. 8645 8646 SDValue Chain = Load->getChain(); 8647 SDValue BasePtr = Load->getBasePtr(); 8648 MachineMemOperand *MMO = Load->getMemOperand(); 8649 8650 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 8651 8652 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 8653 BasePtr, RealMemVT, MMO); 8654 8655 if (!MemVT.isVector()) { 8656 SDValue Ops[] = { 8657 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 8658 NewLD.getValue(1) 8659 }; 8660 8661 return DAG.getMergeValues(Ops, DL); 8662 } 8663 8664 SmallVector<SDValue, 3> Elts; 8665 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 8666 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 8667 DAG.getConstant(I, DL, MVT::i32)); 8668 8669 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 8670 } 8671 8672 SDValue Ops[] = { 8673 DAG.getBuildVector(MemVT, DL, Elts), 8674 NewLD.getValue(1) 8675 }; 8676 8677 return DAG.getMergeValues(Ops, DL); 8678 } 8679 8680 if (!MemVT.isVector()) 8681 return SDValue(); 8682 8683 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 8684 "Custom lowering for non-i32 vectors hasn't been implemented."); 8685 8686 unsigned Alignment = Load->getAlignment(); 8687 unsigned AS = Load->getAddressSpace(); 8688 if (Subtarget->hasLDSMisalignedBug() && 8689 AS == AMDGPUAS::FLAT_ADDRESS && 8690 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 8691 return SplitVectorLoad(Op, DAG); 8692 } 8693 8694 MachineFunction &MF = DAG.getMachineFunction(); 8695 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8696 // If there is a possibility that flat instruction access scratch memory 8697 // then we need to use the same legalization rules we use for private. 8698 if (AS == AMDGPUAS::FLAT_ADDRESS && 8699 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8700 AS = MFI->hasFlatScratchInit() ? 8701 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8702 8703 unsigned NumElements = MemVT.getVectorNumElements(); 8704 8705 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8706 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 8707 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 8708 if (MemVT.isPow2VectorType()) 8709 return SDValue(); 8710 return WidenOrSplitVectorLoad(Op, DAG); 8711 } 8712 // Non-uniform loads will be selected to MUBUF instructions, so they 8713 // have the same legalization requirements as global and private 8714 // loads. 8715 // 8716 } 8717 8718 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8719 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8720 AS == AMDGPUAS::GLOBAL_ADDRESS) { 8721 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 8722 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 8723 Alignment >= 4 && NumElements < 32) { 8724 if (MemVT.isPow2VectorType()) 8725 return SDValue(); 8726 return WidenOrSplitVectorLoad(Op, DAG); 8727 } 8728 // Non-uniform loads will be selected to MUBUF instructions, so they 8729 // have the same legalization requirements as global and private 8730 // loads. 8731 // 8732 } 8733 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8734 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8735 AS == AMDGPUAS::GLOBAL_ADDRESS || 8736 AS == AMDGPUAS::FLAT_ADDRESS) { 8737 if (NumElements > 4) 8738 return SplitVectorLoad(Op, DAG); 8739 // v3 loads not supported on SI. 8740 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8741 return WidenOrSplitVectorLoad(Op, DAG); 8742 8743 // v3 and v4 loads are supported for private and global memory. 8744 return SDValue(); 8745 } 8746 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8747 // Depending on the setting of the private_element_size field in the 8748 // resource descriptor, we can only make private accesses up to a certain 8749 // size. 8750 switch (Subtarget->getMaxPrivateElementSize()) { 8751 case 4: { 8752 SDValue Ops[2]; 8753 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 8754 return DAG.getMergeValues(Ops, DL); 8755 } 8756 case 8: 8757 if (NumElements > 2) 8758 return SplitVectorLoad(Op, DAG); 8759 return SDValue(); 8760 case 16: 8761 // Same as global/flat 8762 if (NumElements > 4) 8763 return SplitVectorLoad(Op, DAG); 8764 // v3 loads not supported on SI. 8765 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8766 return WidenOrSplitVectorLoad(Op, DAG); 8767 8768 return SDValue(); 8769 default: 8770 llvm_unreachable("unsupported private_element_size"); 8771 } 8772 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8773 bool Fast = false; 8774 auto Flags = Load->getMemOperand()->getFlags(); 8775 if (allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 8776 Load->getAlign(), Flags, &Fast) && 8777 Fast) 8778 return SDValue(); 8779 8780 if (MemVT.isVector()) 8781 return SplitVectorLoad(Op, DAG); 8782 } 8783 8784 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8785 MemVT, *Load->getMemOperand())) { 8786 SDValue Ops[2]; 8787 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 8788 return DAG.getMergeValues(Ops, DL); 8789 } 8790 8791 return SDValue(); 8792 } 8793 8794 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8795 EVT VT = Op.getValueType(); 8796 if (VT.getSizeInBits() == 128) 8797 return splitTernaryVectorOp(Op, DAG); 8798 8799 assert(VT.getSizeInBits() == 64); 8800 8801 SDLoc DL(Op); 8802 SDValue Cond = Op.getOperand(0); 8803 8804 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8805 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8806 8807 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8808 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8809 8810 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8811 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8812 8813 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8814 8815 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8816 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8817 8818 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8819 8820 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8821 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8822 } 8823 8824 // Catch division cases where we can use shortcuts with rcp and rsq 8825 // instructions. 8826 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8827 SelectionDAG &DAG) const { 8828 SDLoc SL(Op); 8829 SDValue LHS = Op.getOperand(0); 8830 SDValue RHS = Op.getOperand(1); 8831 EVT VT = Op.getValueType(); 8832 const SDNodeFlags Flags = Op->getFlags(); 8833 8834 bool AllowInaccurateRcp = Flags.hasApproximateFuncs(); 8835 8836 // Without !fpmath accuracy information, we can't do more because we don't 8837 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8838 if (!AllowInaccurateRcp) 8839 return SDValue(); 8840 8841 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8842 if (CLHS->isExactlyValue(1.0)) { 8843 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8844 // the CI documentation has a worst case error of 1 ulp. 8845 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8846 // use it as long as we aren't trying to use denormals. 8847 // 8848 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8849 8850 // 1.0 / sqrt(x) -> rsq(x) 8851 8852 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8853 // error seems really high at 2^29 ULP. 8854 if (RHS.getOpcode() == ISD::FSQRT) 8855 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8856 8857 // 1.0 / x -> rcp(x) 8858 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8859 } 8860 8861 // Same as for 1.0, but expand the sign out of the constant. 8862 if (CLHS->isExactlyValue(-1.0)) { 8863 // -1.0 / x -> rcp (fneg x) 8864 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8865 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8866 } 8867 } 8868 8869 // Turn into multiply by the reciprocal. 8870 // x / y -> x * (1.0 / y) 8871 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8872 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8873 } 8874 8875 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op, 8876 SelectionDAG &DAG) const { 8877 SDLoc SL(Op); 8878 SDValue X = Op.getOperand(0); 8879 SDValue Y = Op.getOperand(1); 8880 EVT VT = Op.getValueType(); 8881 const SDNodeFlags Flags = Op->getFlags(); 8882 8883 bool AllowInaccurateDiv = Flags.hasApproximateFuncs() || 8884 DAG.getTarget().Options.UnsafeFPMath; 8885 if (!AllowInaccurateDiv) 8886 return SDValue(); 8887 8888 SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y); 8889 SDValue One = DAG.getConstantFP(1.0, SL, VT); 8890 8891 SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y); 8892 SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8893 8894 R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R); 8895 SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8896 R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R); 8897 SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R); 8898 SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X); 8899 return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret); 8900 } 8901 8902 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8903 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8904 SDNodeFlags Flags) { 8905 if (GlueChain->getNumValues() <= 1) { 8906 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8907 } 8908 8909 assert(GlueChain->getNumValues() == 3); 8910 8911 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8912 switch (Opcode) { 8913 default: llvm_unreachable("no chain equivalent for opcode"); 8914 case ISD::FMUL: 8915 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8916 break; 8917 } 8918 8919 return DAG.getNode(Opcode, SL, VTList, 8920 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8921 Flags); 8922 } 8923 8924 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8925 EVT VT, SDValue A, SDValue B, SDValue C, 8926 SDValue GlueChain, SDNodeFlags Flags) { 8927 if (GlueChain->getNumValues() <= 1) { 8928 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8929 } 8930 8931 assert(GlueChain->getNumValues() == 3); 8932 8933 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8934 switch (Opcode) { 8935 default: llvm_unreachable("no chain equivalent for opcode"); 8936 case ISD::FMA: 8937 Opcode = AMDGPUISD::FMA_W_CHAIN; 8938 break; 8939 } 8940 8941 return DAG.getNode(Opcode, SL, VTList, 8942 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8943 Flags); 8944 } 8945 8946 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8947 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8948 return FastLowered; 8949 8950 SDLoc SL(Op); 8951 SDValue Src0 = Op.getOperand(0); 8952 SDValue Src1 = Op.getOperand(1); 8953 8954 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8955 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8956 8957 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8958 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8959 8960 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8961 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8962 8963 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8964 } 8965 8966 // Faster 2.5 ULP division that does not support denormals. 8967 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8968 SDLoc SL(Op); 8969 SDValue LHS = Op.getOperand(1); 8970 SDValue RHS = Op.getOperand(2); 8971 8972 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8973 8974 const APFloat K0Val(BitsToFloat(0x6f800000)); 8975 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8976 8977 const APFloat K1Val(BitsToFloat(0x2f800000)); 8978 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8979 8980 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8981 8982 EVT SetCCVT = 8983 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8984 8985 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8986 8987 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8988 8989 // TODO: Should this propagate fast-math-flags? 8990 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8991 8992 // rcp does not support denormals. 8993 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8994 8995 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8996 8997 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8998 } 8999 9000 // Returns immediate value for setting the F32 denorm mode when using the 9001 // S_DENORM_MODE instruction. 9002 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 9003 const SDLoc &SL, const GCNSubtarget *ST) { 9004 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 9005 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 9006 ? FP_DENORM_FLUSH_NONE 9007 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 9008 9009 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 9010 return DAG.getTargetConstant(Mode, SL, MVT::i32); 9011 } 9012 9013 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 9014 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 9015 return FastLowered; 9016 9017 // The selection matcher assumes anything with a chain selecting to a 9018 // mayRaiseFPException machine instruction. Since we're introducing a chain 9019 // here, we need to explicitly report nofpexcept for the regular fdiv 9020 // lowering. 9021 SDNodeFlags Flags = Op->getFlags(); 9022 Flags.setNoFPExcept(true); 9023 9024 SDLoc SL(Op); 9025 SDValue LHS = Op.getOperand(0); 9026 SDValue RHS = Op.getOperand(1); 9027 9028 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 9029 9030 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 9031 9032 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 9033 {RHS, RHS, LHS}, Flags); 9034 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 9035 {LHS, RHS, LHS}, Flags); 9036 9037 // Denominator is scaled to not be denormal, so using rcp is ok. 9038 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 9039 DenominatorScaled, Flags); 9040 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 9041 DenominatorScaled, Flags); 9042 9043 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 9044 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 9045 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 9046 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 9047 9048 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 9049 9050 if (!HasFP32Denormals) { 9051 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 9052 // lowering. The chain dependence is insufficient, and we need glue. We do 9053 // not need the glue variants in a strictfp function. 9054 9055 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 9056 9057 SDNode *EnableDenorm; 9058 if (Subtarget->hasDenormModeInst()) { 9059 const SDValue EnableDenormValue = 9060 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 9061 9062 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 9063 DAG.getEntryNode(), EnableDenormValue).getNode(); 9064 } else { 9065 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 9066 SL, MVT::i32); 9067 EnableDenorm = 9068 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 9069 {EnableDenormValue, BitField, DAG.getEntryNode()}); 9070 } 9071 9072 SDValue Ops[3] = { 9073 NegDivScale0, 9074 SDValue(EnableDenorm, 0), 9075 SDValue(EnableDenorm, 1) 9076 }; 9077 9078 NegDivScale0 = DAG.getMergeValues(Ops, SL); 9079 } 9080 9081 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 9082 ApproxRcp, One, NegDivScale0, Flags); 9083 9084 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 9085 ApproxRcp, Fma0, Flags); 9086 9087 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 9088 Fma1, Fma1, Flags); 9089 9090 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 9091 NumeratorScaled, Mul, Flags); 9092 9093 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 9094 Fma2, Fma1, Mul, Fma2, Flags); 9095 9096 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 9097 NumeratorScaled, Fma3, Flags); 9098 9099 if (!HasFP32Denormals) { 9100 SDNode *DisableDenorm; 9101 if (Subtarget->hasDenormModeInst()) { 9102 const SDValue DisableDenormValue = 9103 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 9104 9105 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 9106 Fma4.getValue(1), DisableDenormValue, 9107 Fma4.getValue(2)).getNode(); 9108 } else { 9109 const SDValue DisableDenormValue = 9110 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 9111 9112 DisableDenorm = DAG.getMachineNode( 9113 AMDGPU::S_SETREG_B32, SL, MVT::Other, 9114 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 9115 } 9116 9117 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 9118 SDValue(DisableDenorm, 0), DAG.getRoot()); 9119 DAG.setRoot(OutputChain); 9120 } 9121 9122 SDValue Scale = NumeratorScaled.getValue(1); 9123 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 9124 {Fma4, Fma1, Fma3, Scale}, Flags); 9125 9126 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 9127 } 9128 9129 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 9130 if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG)) 9131 return FastLowered; 9132 9133 SDLoc SL(Op); 9134 SDValue X = Op.getOperand(0); 9135 SDValue Y = Op.getOperand(1); 9136 9137 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 9138 9139 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 9140 9141 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 9142 9143 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 9144 9145 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 9146 9147 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 9148 9149 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 9150 9151 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 9152 9153 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 9154 9155 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 9156 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 9157 9158 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 9159 NegDivScale0, Mul, DivScale1); 9160 9161 SDValue Scale; 9162 9163 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 9164 // Workaround a hardware bug on SI where the condition output from div_scale 9165 // is not usable. 9166 9167 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 9168 9169 // Figure out if the scale to use for div_fmas. 9170 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 9171 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 9172 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 9173 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 9174 9175 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 9176 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 9177 9178 SDValue Scale0Hi 9179 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 9180 SDValue Scale1Hi 9181 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 9182 9183 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 9184 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 9185 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 9186 } else { 9187 Scale = DivScale1.getValue(1); 9188 } 9189 9190 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 9191 Fma4, Fma3, Mul, Scale); 9192 9193 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 9194 } 9195 9196 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 9197 EVT VT = Op.getValueType(); 9198 9199 if (VT == MVT::f32) 9200 return LowerFDIV32(Op, DAG); 9201 9202 if (VT == MVT::f64) 9203 return LowerFDIV64(Op, DAG); 9204 9205 if (VT == MVT::f16) 9206 return LowerFDIV16(Op, DAG); 9207 9208 llvm_unreachable("Unexpected type for fdiv"); 9209 } 9210 9211 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 9212 SDLoc DL(Op); 9213 StoreSDNode *Store = cast<StoreSDNode>(Op); 9214 EVT VT = Store->getMemoryVT(); 9215 9216 if (VT == MVT::i1) { 9217 return DAG.getTruncStore(Store->getChain(), DL, 9218 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 9219 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 9220 } 9221 9222 assert(VT.isVector() && 9223 Store->getValue().getValueType().getScalarType() == MVT::i32); 9224 9225 unsigned AS = Store->getAddressSpace(); 9226 if (Subtarget->hasLDSMisalignedBug() && 9227 AS == AMDGPUAS::FLAT_ADDRESS && 9228 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 9229 return SplitVectorStore(Op, DAG); 9230 } 9231 9232 MachineFunction &MF = DAG.getMachineFunction(); 9233 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 9234 // If there is a possibility that flat instruction access scratch memory 9235 // then we need to use the same legalization rules we use for private. 9236 if (AS == AMDGPUAS::FLAT_ADDRESS && 9237 !Subtarget->hasMultiDwordFlatScratchAddressing()) 9238 AS = MFI->hasFlatScratchInit() ? 9239 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 9240 9241 unsigned NumElements = VT.getVectorNumElements(); 9242 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 9243 AS == AMDGPUAS::FLAT_ADDRESS) { 9244 if (NumElements > 4) 9245 return SplitVectorStore(Op, DAG); 9246 // v3 stores not supported on SI. 9247 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 9248 return SplitVectorStore(Op, DAG); 9249 9250 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 9251 VT, *Store->getMemOperand())) 9252 return expandUnalignedStore(Store, DAG); 9253 9254 return SDValue(); 9255 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 9256 switch (Subtarget->getMaxPrivateElementSize()) { 9257 case 4: 9258 return scalarizeVectorStore(Store, DAG); 9259 case 8: 9260 if (NumElements > 2) 9261 return SplitVectorStore(Op, DAG); 9262 return SDValue(); 9263 case 16: 9264 if (NumElements > 4 || 9265 (NumElements == 3 && !Subtarget->enableFlatScratch())) 9266 return SplitVectorStore(Op, DAG); 9267 return SDValue(); 9268 default: 9269 llvm_unreachable("unsupported private_element_size"); 9270 } 9271 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 9272 bool Fast = false; 9273 auto Flags = Store->getMemOperand()->getFlags(); 9274 if (allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 9275 Store->getAlign(), Flags, &Fast) && 9276 Fast) 9277 return SDValue(); 9278 9279 if (VT.isVector()) 9280 return SplitVectorStore(Op, DAG); 9281 9282 return expandUnalignedStore(Store, DAG); 9283 } 9284 9285 // Probably an invalid store. If so we'll end up emitting a selection error. 9286 return SDValue(); 9287 } 9288 9289 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 9290 SDLoc DL(Op); 9291 EVT VT = Op.getValueType(); 9292 SDValue Arg = Op.getOperand(0); 9293 SDValue TrigVal; 9294 9295 // Propagate fast-math flags so that the multiply we introduce can be folded 9296 // if Arg is already the result of a multiply by constant. 9297 auto Flags = Op->getFlags(); 9298 9299 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 9300 9301 if (Subtarget->hasTrigReducedRange()) { 9302 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 9303 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 9304 } else { 9305 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 9306 } 9307 9308 switch (Op.getOpcode()) { 9309 case ISD::FCOS: 9310 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 9311 case ISD::FSIN: 9312 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 9313 default: 9314 llvm_unreachable("Wrong trig opcode"); 9315 } 9316 } 9317 9318 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 9319 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 9320 assert(AtomicNode->isCompareAndSwap()); 9321 unsigned AS = AtomicNode->getAddressSpace(); 9322 9323 // No custom lowering required for local address space 9324 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 9325 return Op; 9326 9327 // Non-local address space requires custom lowering for atomic compare 9328 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 9329 SDLoc DL(Op); 9330 SDValue ChainIn = Op.getOperand(0); 9331 SDValue Addr = Op.getOperand(1); 9332 SDValue Old = Op.getOperand(2); 9333 SDValue New = Op.getOperand(3); 9334 EVT VT = Op.getValueType(); 9335 MVT SimpleVT = VT.getSimpleVT(); 9336 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 9337 9338 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 9339 SDValue Ops[] = { ChainIn, Addr, NewOld }; 9340 9341 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 9342 Ops, VT, AtomicNode->getMemOperand()); 9343 } 9344 9345 //===----------------------------------------------------------------------===// 9346 // Custom DAG optimizations 9347 //===----------------------------------------------------------------------===// 9348 9349 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 9350 DAGCombinerInfo &DCI) const { 9351 EVT VT = N->getValueType(0); 9352 EVT ScalarVT = VT.getScalarType(); 9353 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 9354 return SDValue(); 9355 9356 SelectionDAG &DAG = DCI.DAG; 9357 SDLoc DL(N); 9358 9359 SDValue Src = N->getOperand(0); 9360 EVT SrcVT = Src.getValueType(); 9361 9362 // TODO: We could try to match extracting the higher bytes, which would be 9363 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 9364 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 9365 // about in practice. 9366 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 9367 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 9368 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 9369 DCI.AddToWorklist(Cvt.getNode()); 9370 9371 // For the f16 case, fold to a cast to f32 and then cast back to f16. 9372 if (ScalarVT != MVT::f32) { 9373 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 9374 DAG.getTargetConstant(0, DL, MVT::i32)); 9375 } 9376 return Cvt; 9377 } 9378 } 9379 9380 return SDValue(); 9381 } 9382 9383 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 9384 9385 // This is a variant of 9386 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 9387 // 9388 // The normal DAG combiner will do this, but only if the add has one use since 9389 // that would increase the number of instructions. 9390 // 9391 // This prevents us from seeing a constant offset that can be folded into a 9392 // memory instruction's addressing mode. If we know the resulting add offset of 9393 // a pointer can be folded into an addressing offset, we can replace the pointer 9394 // operand with the add of new constant offset. This eliminates one of the uses, 9395 // and may allow the remaining use to also be simplified. 9396 // 9397 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 9398 unsigned AddrSpace, 9399 EVT MemVT, 9400 DAGCombinerInfo &DCI) const { 9401 SDValue N0 = N->getOperand(0); 9402 SDValue N1 = N->getOperand(1); 9403 9404 // We only do this to handle cases where it's profitable when there are 9405 // multiple uses of the add, so defer to the standard combine. 9406 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 9407 N0->hasOneUse()) 9408 return SDValue(); 9409 9410 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 9411 if (!CN1) 9412 return SDValue(); 9413 9414 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 9415 if (!CAdd) 9416 return SDValue(); 9417 9418 // If the resulting offset is too large, we can't fold it into the addressing 9419 // mode offset. 9420 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 9421 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 9422 9423 AddrMode AM; 9424 AM.HasBaseReg = true; 9425 AM.BaseOffs = Offset.getSExtValue(); 9426 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 9427 return SDValue(); 9428 9429 SelectionDAG &DAG = DCI.DAG; 9430 SDLoc SL(N); 9431 EVT VT = N->getValueType(0); 9432 9433 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 9434 SDValue COffset = DAG.getConstant(Offset, SL, VT); 9435 9436 SDNodeFlags Flags; 9437 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 9438 (N0.getOpcode() == ISD::OR || 9439 N0->getFlags().hasNoUnsignedWrap())); 9440 9441 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 9442 } 9443 9444 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 9445 /// by the chain and intrinsic ID. Theoretically we would also need to check the 9446 /// specific intrinsic, but they all place the pointer operand first. 9447 static unsigned getBasePtrIndex(const MemSDNode *N) { 9448 switch (N->getOpcode()) { 9449 case ISD::STORE: 9450 case ISD::INTRINSIC_W_CHAIN: 9451 case ISD::INTRINSIC_VOID: 9452 return 2; 9453 default: 9454 return 1; 9455 } 9456 } 9457 9458 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 9459 DAGCombinerInfo &DCI) const { 9460 SelectionDAG &DAG = DCI.DAG; 9461 SDLoc SL(N); 9462 9463 unsigned PtrIdx = getBasePtrIndex(N); 9464 SDValue Ptr = N->getOperand(PtrIdx); 9465 9466 // TODO: We could also do this for multiplies. 9467 if (Ptr.getOpcode() == ISD::SHL) { 9468 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 9469 N->getMemoryVT(), DCI); 9470 if (NewPtr) { 9471 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 9472 9473 NewOps[PtrIdx] = NewPtr; 9474 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 9475 } 9476 } 9477 9478 return SDValue(); 9479 } 9480 9481 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 9482 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 9483 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 9484 (Opc == ISD::XOR && Val == 0); 9485 } 9486 9487 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 9488 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 9489 // integer combine opportunities since most 64-bit operations are decomposed 9490 // this way. TODO: We won't want this for SALU especially if it is an inline 9491 // immediate. 9492 SDValue SITargetLowering::splitBinaryBitConstantOp( 9493 DAGCombinerInfo &DCI, 9494 const SDLoc &SL, 9495 unsigned Opc, SDValue LHS, 9496 const ConstantSDNode *CRHS) const { 9497 uint64_t Val = CRHS->getZExtValue(); 9498 uint32_t ValLo = Lo_32(Val); 9499 uint32_t ValHi = Hi_32(Val); 9500 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9501 9502 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 9503 bitOpWithConstantIsReducible(Opc, ValHi)) || 9504 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 9505 // If we need to materialize a 64-bit immediate, it will be split up later 9506 // anyway. Avoid creating the harder to understand 64-bit immediate 9507 // materialization. 9508 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 9509 } 9510 9511 return SDValue(); 9512 } 9513 9514 // Returns true if argument is a boolean value which is not serialized into 9515 // memory or argument and does not require v_cndmask_b32 to be deserialized. 9516 static bool isBoolSGPR(SDValue V) { 9517 if (V.getValueType() != MVT::i1) 9518 return false; 9519 switch (V.getOpcode()) { 9520 default: 9521 break; 9522 case ISD::SETCC: 9523 case AMDGPUISD::FP_CLASS: 9524 return true; 9525 case ISD::AND: 9526 case ISD::OR: 9527 case ISD::XOR: 9528 return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1)); 9529 } 9530 return false; 9531 } 9532 9533 // If a constant has all zeroes or all ones within each byte return it. 9534 // Otherwise return 0. 9535 static uint32_t getConstantPermuteMask(uint32_t C) { 9536 // 0xff for any zero byte in the mask 9537 uint32_t ZeroByteMask = 0; 9538 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 9539 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 9540 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 9541 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 9542 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 9543 if ((NonZeroByteMask & C) != NonZeroByteMask) 9544 return 0; // Partial bytes selected. 9545 return C; 9546 } 9547 9548 // Check if a node selects whole bytes from its operand 0 starting at a byte 9549 // boundary while masking the rest. Returns select mask as in the v_perm_b32 9550 // or -1 if not succeeded. 9551 // Note byte select encoding: 9552 // value 0-3 selects corresponding source byte; 9553 // value 0xc selects zero; 9554 // value 0xff selects 0xff. 9555 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 9556 assert(V.getValueSizeInBits() == 32); 9557 9558 if (V.getNumOperands() != 2) 9559 return ~0; 9560 9561 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 9562 if (!N1) 9563 return ~0; 9564 9565 uint32_t C = N1->getZExtValue(); 9566 9567 switch (V.getOpcode()) { 9568 default: 9569 break; 9570 case ISD::AND: 9571 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9572 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 9573 } 9574 break; 9575 9576 case ISD::OR: 9577 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9578 return (0x03020100 & ~ConstMask) | ConstMask; 9579 } 9580 break; 9581 9582 case ISD::SHL: 9583 if (C % 8) 9584 return ~0; 9585 9586 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 9587 9588 case ISD::SRL: 9589 if (C % 8) 9590 return ~0; 9591 9592 return uint32_t(0x0c0c0c0c03020100ull >> C); 9593 } 9594 9595 return ~0; 9596 } 9597 9598 SDValue SITargetLowering::performAndCombine(SDNode *N, 9599 DAGCombinerInfo &DCI) const { 9600 if (DCI.isBeforeLegalize()) 9601 return SDValue(); 9602 9603 SelectionDAG &DAG = DCI.DAG; 9604 EVT VT = N->getValueType(0); 9605 SDValue LHS = N->getOperand(0); 9606 SDValue RHS = N->getOperand(1); 9607 9608 9609 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9610 if (VT == MVT::i64 && CRHS) { 9611 if (SDValue Split 9612 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 9613 return Split; 9614 } 9615 9616 if (CRHS && VT == MVT::i32) { 9617 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 9618 // nb = number of trailing zeroes in mask 9619 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 9620 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 9621 uint64_t Mask = CRHS->getZExtValue(); 9622 unsigned Bits = countPopulation(Mask); 9623 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 9624 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 9625 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 9626 unsigned Shift = CShift->getZExtValue(); 9627 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 9628 unsigned Offset = NB + Shift; 9629 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 9630 SDLoc SL(N); 9631 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 9632 LHS->getOperand(0), 9633 DAG.getConstant(Offset, SL, MVT::i32), 9634 DAG.getConstant(Bits, SL, MVT::i32)); 9635 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9636 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 9637 DAG.getValueType(NarrowVT)); 9638 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 9639 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 9640 return Shl; 9641 } 9642 } 9643 } 9644 9645 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9646 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 9647 isa<ConstantSDNode>(LHS.getOperand(2))) { 9648 uint32_t Sel = getConstantPermuteMask(Mask); 9649 if (!Sel) 9650 return SDValue(); 9651 9652 // Select 0xc for all zero bytes 9653 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 9654 SDLoc DL(N); 9655 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9656 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9657 } 9658 } 9659 9660 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 9661 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 9662 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 9663 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9664 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 9665 9666 SDValue X = LHS.getOperand(0); 9667 SDValue Y = RHS.getOperand(0); 9668 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 9669 return SDValue(); 9670 9671 if (LCC == ISD::SETO) { 9672 if (X != LHS.getOperand(1)) 9673 return SDValue(); 9674 9675 if (RCC == ISD::SETUNE) { 9676 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 9677 if (!C1 || !C1->isInfinity() || C1->isNegative()) 9678 return SDValue(); 9679 9680 const uint32_t Mask = SIInstrFlags::N_NORMAL | 9681 SIInstrFlags::N_SUBNORMAL | 9682 SIInstrFlags::N_ZERO | 9683 SIInstrFlags::P_ZERO | 9684 SIInstrFlags::P_SUBNORMAL | 9685 SIInstrFlags::P_NORMAL; 9686 9687 static_assert(((~(SIInstrFlags::S_NAN | 9688 SIInstrFlags::Q_NAN | 9689 SIInstrFlags::N_INFINITY | 9690 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 9691 "mask not equal"); 9692 9693 SDLoc DL(N); 9694 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9695 X, DAG.getConstant(Mask, DL, MVT::i32)); 9696 } 9697 } 9698 } 9699 9700 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 9701 std::swap(LHS, RHS); 9702 9703 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 9704 RHS.hasOneUse()) { 9705 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9706 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 9707 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 9708 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9709 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 9710 (RHS.getOperand(0) == LHS.getOperand(0) && 9711 LHS.getOperand(0) == LHS.getOperand(1))) { 9712 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 9713 unsigned NewMask = LCC == ISD::SETO ? 9714 Mask->getZExtValue() & ~OrdMask : 9715 Mask->getZExtValue() & OrdMask; 9716 9717 SDLoc DL(N); 9718 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 9719 DAG.getConstant(NewMask, DL, MVT::i32)); 9720 } 9721 } 9722 9723 if (VT == MVT::i32 && 9724 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 9725 // and x, (sext cc from i1) => select cc, x, 0 9726 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 9727 std::swap(LHS, RHS); 9728 if (isBoolSGPR(RHS.getOperand(0))) 9729 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 9730 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 9731 } 9732 9733 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9734 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9735 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9736 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9737 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9738 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9739 if (LHSMask != ~0u && RHSMask != ~0u) { 9740 // Canonicalize the expression in an attempt to have fewer unique masks 9741 // and therefore fewer registers used to hold the masks. 9742 if (LHSMask > RHSMask) { 9743 std::swap(LHSMask, RHSMask); 9744 std::swap(LHS, RHS); 9745 } 9746 9747 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9748 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9749 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9750 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9751 9752 // Check of we need to combine values from two sources within a byte. 9753 if (!(LHSUsedLanes & RHSUsedLanes) && 9754 // If we select high and lower word keep it for SDWA. 9755 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9756 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9757 // Each byte in each mask is either selector mask 0-3, or has higher 9758 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 9759 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 9760 // mask which is not 0xff wins. By anding both masks we have a correct 9761 // result except that 0x0c shall be corrected to give 0x0c only. 9762 uint32_t Mask = LHSMask & RHSMask; 9763 for (unsigned I = 0; I < 32; I += 8) { 9764 uint32_t ByteSel = 0xff << I; 9765 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 9766 Mask &= (0x0c << I) & 0xffffffff; 9767 } 9768 9769 // Add 4 to each active LHS lane. It will not affect any existing 0xff 9770 // or 0x0c. 9771 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 9772 SDLoc DL(N); 9773 9774 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9775 LHS.getOperand(0), RHS.getOperand(0), 9776 DAG.getConstant(Sel, DL, MVT::i32)); 9777 } 9778 } 9779 } 9780 9781 return SDValue(); 9782 } 9783 9784 SDValue SITargetLowering::performOrCombine(SDNode *N, 9785 DAGCombinerInfo &DCI) const { 9786 SelectionDAG &DAG = DCI.DAG; 9787 SDValue LHS = N->getOperand(0); 9788 SDValue RHS = N->getOperand(1); 9789 9790 EVT VT = N->getValueType(0); 9791 if (VT == MVT::i1) { 9792 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 9793 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 9794 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 9795 SDValue Src = LHS.getOperand(0); 9796 if (Src != RHS.getOperand(0)) 9797 return SDValue(); 9798 9799 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9800 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9801 if (!CLHS || !CRHS) 9802 return SDValue(); 9803 9804 // Only 10 bits are used. 9805 static const uint32_t MaxMask = 0x3ff; 9806 9807 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 9808 SDLoc DL(N); 9809 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9810 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 9811 } 9812 9813 return SDValue(); 9814 } 9815 9816 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9817 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 9818 LHS.getOpcode() == AMDGPUISD::PERM && 9819 isa<ConstantSDNode>(LHS.getOperand(2))) { 9820 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 9821 if (!Sel) 9822 return SDValue(); 9823 9824 Sel |= LHS.getConstantOperandVal(2); 9825 SDLoc DL(N); 9826 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9827 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9828 } 9829 9830 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9831 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9832 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9833 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9834 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9835 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9836 if (LHSMask != ~0u && RHSMask != ~0u) { 9837 // Canonicalize the expression in an attempt to have fewer unique masks 9838 // and therefore fewer registers used to hold the masks. 9839 if (LHSMask > RHSMask) { 9840 std::swap(LHSMask, RHSMask); 9841 std::swap(LHS, RHS); 9842 } 9843 9844 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9845 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9846 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9847 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9848 9849 // Check of we need to combine values from two sources within a byte. 9850 if (!(LHSUsedLanes & RHSUsedLanes) && 9851 // If we select high and lower word keep it for SDWA. 9852 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9853 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9854 // Kill zero bytes selected by other mask. Zero value is 0xc. 9855 LHSMask &= ~RHSUsedLanes; 9856 RHSMask &= ~LHSUsedLanes; 9857 // Add 4 to each active LHS lane 9858 LHSMask |= LHSUsedLanes & 0x04040404; 9859 // Combine masks 9860 uint32_t Sel = LHSMask | RHSMask; 9861 SDLoc DL(N); 9862 9863 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9864 LHS.getOperand(0), RHS.getOperand(0), 9865 DAG.getConstant(Sel, DL, MVT::i32)); 9866 } 9867 } 9868 } 9869 9870 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9871 return SDValue(); 9872 9873 // TODO: This could be a generic combine with a predicate for extracting the 9874 // high half of an integer being free. 9875 9876 // (or i64:x, (zero_extend i32:y)) -> 9877 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9878 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9879 RHS.getOpcode() != ISD::ZERO_EXTEND) 9880 std::swap(LHS, RHS); 9881 9882 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9883 SDValue ExtSrc = RHS.getOperand(0); 9884 EVT SrcVT = ExtSrc.getValueType(); 9885 if (SrcVT == MVT::i32) { 9886 SDLoc SL(N); 9887 SDValue LowLHS, HiBits; 9888 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9889 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9890 9891 DCI.AddToWorklist(LowOr.getNode()); 9892 DCI.AddToWorklist(HiBits.getNode()); 9893 9894 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9895 LowOr, HiBits); 9896 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9897 } 9898 } 9899 9900 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9901 if (CRHS) { 9902 if (SDValue Split 9903 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, 9904 N->getOperand(0), CRHS)) 9905 return Split; 9906 } 9907 9908 return SDValue(); 9909 } 9910 9911 SDValue SITargetLowering::performXorCombine(SDNode *N, 9912 DAGCombinerInfo &DCI) const { 9913 if (SDValue RV = reassociateScalarOps(N, DCI.DAG)) 9914 return RV; 9915 9916 EVT VT = N->getValueType(0); 9917 if (VT != MVT::i64) 9918 return SDValue(); 9919 9920 SDValue LHS = N->getOperand(0); 9921 SDValue RHS = N->getOperand(1); 9922 9923 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9924 if (CRHS) { 9925 if (SDValue Split 9926 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9927 return Split; 9928 } 9929 9930 return SDValue(); 9931 } 9932 9933 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9934 DAGCombinerInfo &DCI) const { 9935 if (!Subtarget->has16BitInsts() || 9936 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9937 return SDValue(); 9938 9939 EVT VT = N->getValueType(0); 9940 if (VT != MVT::i32) 9941 return SDValue(); 9942 9943 SDValue Src = N->getOperand(0); 9944 if (Src.getValueType() != MVT::i16) 9945 return SDValue(); 9946 9947 return SDValue(); 9948 } 9949 9950 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9951 DAGCombinerInfo &DCI) 9952 const { 9953 SDValue Src = N->getOperand(0); 9954 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9955 9956 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9957 VTSign->getVT() == MVT::i8) || 9958 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9959 VTSign->getVT() == MVT::i16)) && 9960 Src.hasOneUse()) { 9961 auto *M = cast<MemSDNode>(Src); 9962 SDValue Ops[] = { 9963 Src.getOperand(0), // Chain 9964 Src.getOperand(1), // rsrc 9965 Src.getOperand(2), // vindex 9966 Src.getOperand(3), // voffset 9967 Src.getOperand(4), // soffset 9968 Src.getOperand(5), // offset 9969 Src.getOperand(6), 9970 Src.getOperand(7) 9971 }; 9972 // replace with BUFFER_LOAD_BYTE/SHORT 9973 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9974 Src.getOperand(0).getValueType()); 9975 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9976 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9977 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9978 ResList, 9979 Ops, M->getMemoryVT(), 9980 M->getMemOperand()); 9981 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9982 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9983 } 9984 return SDValue(); 9985 } 9986 9987 SDValue SITargetLowering::performClassCombine(SDNode *N, 9988 DAGCombinerInfo &DCI) const { 9989 SelectionDAG &DAG = DCI.DAG; 9990 SDValue Mask = N->getOperand(1); 9991 9992 // fp_class x, 0 -> false 9993 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9994 if (CMask->isZero()) 9995 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9996 } 9997 9998 if (N->getOperand(0).isUndef()) 9999 return DAG.getUNDEF(MVT::i1); 10000 10001 return SDValue(); 10002 } 10003 10004 SDValue SITargetLowering::performRcpCombine(SDNode *N, 10005 DAGCombinerInfo &DCI) const { 10006 EVT VT = N->getValueType(0); 10007 SDValue N0 = N->getOperand(0); 10008 10009 if (N0.isUndef()) 10010 return N0; 10011 10012 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 10013 N0.getOpcode() == ISD::SINT_TO_FP)) { 10014 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 10015 N->getFlags()); 10016 } 10017 10018 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 10019 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 10020 N0.getOperand(0), N->getFlags()); 10021 } 10022 10023 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 10024 } 10025 10026 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 10027 unsigned MaxDepth) const { 10028 unsigned Opcode = Op.getOpcode(); 10029 if (Opcode == ISD::FCANONICALIZE) 10030 return true; 10031 10032 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 10033 auto F = CFP->getValueAPF(); 10034 if (F.isNaN() && F.isSignaling()) 10035 return false; 10036 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 10037 } 10038 10039 // If source is a result of another standard FP operation it is already in 10040 // canonical form. 10041 if (MaxDepth == 0) 10042 return false; 10043 10044 switch (Opcode) { 10045 // These will flush denorms if required. 10046 case ISD::FADD: 10047 case ISD::FSUB: 10048 case ISD::FMUL: 10049 case ISD::FCEIL: 10050 case ISD::FFLOOR: 10051 case ISD::FMA: 10052 case ISD::FMAD: 10053 case ISD::FSQRT: 10054 case ISD::FDIV: 10055 case ISD::FREM: 10056 case ISD::FP_ROUND: 10057 case ISD::FP_EXTEND: 10058 case AMDGPUISD::FMUL_LEGACY: 10059 case AMDGPUISD::FMAD_FTZ: 10060 case AMDGPUISD::RCP: 10061 case AMDGPUISD::RSQ: 10062 case AMDGPUISD::RSQ_CLAMP: 10063 case AMDGPUISD::RCP_LEGACY: 10064 case AMDGPUISD::RCP_IFLAG: 10065 case AMDGPUISD::DIV_SCALE: 10066 case AMDGPUISD::DIV_FMAS: 10067 case AMDGPUISD::DIV_FIXUP: 10068 case AMDGPUISD::FRACT: 10069 case AMDGPUISD::LDEXP: 10070 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10071 case AMDGPUISD::CVT_F32_UBYTE0: 10072 case AMDGPUISD::CVT_F32_UBYTE1: 10073 case AMDGPUISD::CVT_F32_UBYTE2: 10074 case AMDGPUISD::CVT_F32_UBYTE3: 10075 return true; 10076 10077 // It can/will be lowered or combined as a bit operation. 10078 // Need to check their input recursively to handle. 10079 case ISD::FNEG: 10080 case ISD::FABS: 10081 case ISD::FCOPYSIGN: 10082 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 10083 10084 case ISD::FSIN: 10085 case ISD::FCOS: 10086 case ISD::FSINCOS: 10087 return Op.getValueType().getScalarType() != MVT::f16; 10088 10089 case ISD::FMINNUM: 10090 case ISD::FMAXNUM: 10091 case ISD::FMINNUM_IEEE: 10092 case ISD::FMAXNUM_IEEE: 10093 case AMDGPUISD::CLAMP: 10094 case AMDGPUISD::FMED3: 10095 case AMDGPUISD::FMAX3: 10096 case AMDGPUISD::FMIN3: { 10097 // FIXME: Shouldn't treat the generic operations different based these. 10098 // However, we aren't really required to flush the result from 10099 // minnum/maxnum.. 10100 10101 // snans will be quieted, so we only need to worry about denormals. 10102 if (Subtarget->supportsMinMaxDenormModes() || 10103 denormalsEnabledForType(DAG, Op.getValueType())) 10104 return true; 10105 10106 // Flushing may be required. 10107 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 10108 // targets need to check their input recursively. 10109 10110 // FIXME: Does this apply with clamp? It's implemented with max. 10111 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 10112 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 10113 return false; 10114 } 10115 10116 return true; 10117 } 10118 case ISD::SELECT: { 10119 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 10120 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 10121 } 10122 case ISD::BUILD_VECTOR: { 10123 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 10124 SDValue SrcOp = Op.getOperand(i); 10125 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 10126 return false; 10127 } 10128 10129 return true; 10130 } 10131 case ISD::EXTRACT_VECTOR_ELT: 10132 case ISD::EXTRACT_SUBVECTOR: { 10133 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 10134 } 10135 case ISD::INSERT_VECTOR_ELT: { 10136 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 10137 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 10138 } 10139 case ISD::UNDEF: 10140 // Could be anything. 10141 return false; 10142 10143 case ISD::BITCAST: 10144 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 10145 case ISD::TRUNCATE: { 10146 // Hack round the mess we make when legalizing extract_vector_elt 10147 if (Op.getValueType() == MVT::i16) { 10148 SDValue TruncSrc = Op.getOperand(0); 10149 if (TruncSrc.getValueType() == MVT::i32 && 10150 TruncSrc.getOpcode() == ISD::BITCAST && 10151 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 10152 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 10153 } 10154 } 10155 return false; 10156 } 10157 case ISD::INTRINSIC_WO_CHAIN: { 10158 unsigned IntrinsicID 10159 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10160 // TODO: Handle more intrinsics 10161 switch (IntrinsicID) { 10162 case Intrinsic::amdgcn_cvt_pkrtz: 10163 case Intrinsic::amdgcn_cubeid: 10164 case Intrinsic::amdgcn_frexp_mant: 10165 case Intrinsic::amdgcn_fdot2: 10166 case Intrinsic::amdgcn_rcp: 10167 case Intrinsic::amdgcn_rsq: 10168 case Intrinsic::amdgcn_rsq_clamp: 10169 case Intrinsic::amdgcn_rcp_legacy: 10170 case Intrinsic::amdgcn_rsq_legacy: 10171 case Intrinsic::amdgcn_trig_preop: 10172 return true; 10173 default: 10174 break; 10175 } 10176 10177 LLVM_FALLTHROUGH; 10178 } 10179 default: 10180 return denormalsEnabledForType(DAG, Op.getValueType()) && 10181 DAG.isKnownNeverSNaN(Op); 10182 } 10183 10184 llvm_unreachable("invalid operation"); 10185 } 10186 10187 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF, 10188 unsigned MaxDepth) const { 10189 MachineRegisterInfo &MRI = MF.getRegInfo(); 10190 MachineInstr *MI = MRI.getVRegDef(Reg); 10191 unsigned Opcode = MI->getOpcode(); 10192 10193 if (Opcode == AMDGPU::G_FCANONICALIZE) 10194 return true; 10195 10196 Optional<FPValueAndVReg> FCR; 10197 // Constant splat (can be padded with undef) or scalar constant. 10198 if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) { 10199 if (FCR->Value.isSignaling()) 10200 return false; 10201 return !FCR->Value.isDenormal() || 10202 denormalsEnabledForType(MRI.getType(FCR->VReg), MF); 10203 } 10204 10205 if (MaxDepth == 0) 10206 return false; 10207 10208 switch (Opcode) { 10209 case AMDGPU::G_FMINNUM_IEEE: 10210 case AMDGPU::G_FMAXNUM_IEEE: { 10211 if (Subtarget->supportsMinMaxDenormModes() || 10212 denormalsEnabledForType(MRI.getType(Reg), MF)) 10213 return true; 10214 for (const MachineOperand &MO : llvm::drop_begin(MI->operands())) 10215 if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1)) 10216 return false; 10217 return true; 10218 } 10219 default: 10220 return denormalsEnabledForType(MRI.getType(Reg), MF) && 10221 isKnownNeverSNaN(Reg, MRI); 10222 } 10223 10224 llvm_unreachable("invalid operation"); 10225 } 10226 10227 // Constant fold canonicalize. 10228 SDValue SITargetLowering::getCanonicalConstantFP( 10229 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 10230 // Flush denormals to 0 if not enabled. 10231 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 10232 return DAG.getConstantFP(0.0, SL, VT); 10233 10234 if (C.isNaN()) { 10235 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 10236 if (C.isSignaling()) { 10237 // Quiet a signaling NaN. 10238 // FIXME: Is this supposed to preserve payload bits? 10239 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 10240 } 10241 10242 // Make sure it is the canonical NaN bitpattern. 10243 // 10244 // TODO: Can we use -1 as the canonical NaN value since it's an inline 10245 // immediate? 10246 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 10247 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 10248 } 10249 10250 // Already canonical. 10251 return DAG.getConstantFP(C, SL, VT); 10252 } 10253 10254 static bool vectorEltWillFoldAway(SDValue Op) { 10255 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 10256 } 10257 10258 SDValue SITargetLowering::performFCanonicalizeCombine( 10259 SDNode *N, 10260 DAGCombinerInfo &DCI) const { 10261 SelectionDAG &DAG = DCI.DAG; 10262 SDValue N0 = N->getOperand(0); 10263 EVT VT = N->getValueType(0); 10264 10265 // fcanonicalize undef -> qnan 10266 if (N0.isUndef()) { 10267 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 10268 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 10269 } 10270 10271 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 10272 EVT VT = N->getValueType(0); 10273 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 10274 } 10275 10276 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 10277 // (fcanonicalize k) 10278 // 10279 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 10280 10281 // TODO: This could be better with wider vectors that will be split to v2f16, 10282 // and to consider uses since there aren't that many packed operations. 10283 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 10284 isTypeLegal(MVT::v2f16)) { 10285 SDLoc SL(N); 10286 SDValue NewElts[2]; 10287 SDValue Lo = N0.getOperand(0); 10288 SDValue Hi = N0.getOperand(1); 10289 EVT EltVT = Lo.getValueType(); 10290 10291 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 10292 for (unsigned I = 0; I != 2; ++I) { 10293 SDValue Op = N0.getOperand(I); 10294 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 10295 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 10296 CFP->getValueAPF()); 10297 } else if (Op.isUndef()) { 10298 // Handled below based on what the other operand is. 10299 NewElts[I] = Op; 10300 } else { 10301 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 10302 } 10303 } 10304 10305 // If one half is undef, and one is constant, prefer a splat vector rather 10306 // than the normal qNaN. If it's a register, prefer 0.0 since that's 10307 // cheaper to use and may be free with a packed operation. 10308 if (NewElts[0].isUndef()) { 10309 if (isa<ConstantFPSDNode>(NewElts[1])) 10310 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 10311 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 10312 } 10313 10314 if (NewElts[1].isUndef()) { 10315 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 10316 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 10317 } 10318 10319 return DAG.getBuildVector(VT, SL, NewElts); 10320 } 10321 } 10322 10323 unsigned SrcOpc = N0.getOpcode(); 10324 10325 // If it's free to do so, push canonicalizes further up the source, which may 10326 // find a canonical source. 10327 // 10328 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 10329 // sNaNs. 10330 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 10331 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 10332 if (CRHS && N0.hasOneUse()) { 10333 SDLoc SL(N); 10334 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 10335 N0.getOperand(0)); 10336 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 10337 DCI.AddToWorklist(Canon0.getNode()); 10338 10339 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 10340 } 10341 } 10342 10343 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 10344 } 10345 10346 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 10347 switch (Opc) { 10348 case ISD::FMAXNUM: 10349 case ISD::FMAXNUM_IEEE: 10350 return AMDGPUISD::FMAX3; 10351 case ISD::SMAX: 10352 return AMDGPUISD::SMAX3; 10353 case ISD::UMAX: 10354 return AMDGPUISD::UMAX3; 10355 case ISD::FMINNUM: 10356 case ISD::FMINNUM_IEEE: 10357 return AMDGPUISD::FMIN3; 10358 case ISD::SMIN: 10359 return AMDGPUISD::SMIN3; 10360 case ISD::UMIN: 10361 return AMDGPUISD::UMIN3; 10362 default: 10363 llvm_unreachable("Not a min/max opcode"); 10364 } 10365 } 10366 10367 SDValue SITargetLowering::performIntMed3ImmCombine( 10368 SelectionDAG &DAG, const SDLoc &SL, 10369 SDValue Op0, SDValue Op1, bool Signed) const { 10370 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 10371 if (!K1) 10372 return SDValue(); 10373 10374 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 10375 if (!K0) 10376 return SDValue(); 10377 10378 if (Signed) { 10379 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 10380 return SDValue(); 10381 } else { 10382 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 10383 return SDValue(); 10384 } 10385 10386 EVT VT = K0->getValueType(0); 10387 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 10388 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 10389 return DAG.getNode(Med3Opc, SL, VT, 10390 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 10391 } 10392 10393 // If there isn't a 16-bit med3 operation, convert to 32-bit. 10394 if (VT == MVT::i16) { 10395 MVT NVT = MVT::i32; 10396 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 10397 10398 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 10399 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 10400 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 10401 10402 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 10403 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 10404 } 10405 10406 return SDValue(); 10407 } 10408 10409 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 10410 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 10411 return C; 10412 10413 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 10414 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 10415 return C; 10416 } 10417 10418 return nullptr; 10419 } 10420 10421 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 10422 const SDLoc &SL, 10423 SDValue Op0, 10424 SDValue Op1) const { 10425 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 10426 if (!K1) 10427 return SDValue(); 10428 10429 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 10430 if (!K0) 10431 return SDValue(); 10432 10433 // Ordered >= (although NaN inputs should have folded away by now). 10434 if (K0->getValueAPF() > K1->getValueAPF()) 10435 return SDValue(); 10436 10437 const MachineFunction &MF = DAG.getMachineFunction(); 10438 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10439 10440 // TODO: Check IEEE bit enabled? 10441 EVT VT = Op0.getValueType(); 10442 if (Info->getMode().DX10Clamp) { 10443 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 10444 // hardware fmed3 behavior converting to a min. 10445 // FIXME: Should this be allowing -0.0? 10446 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 10447 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 10448 } 10449 10450 // med3 for f16 is only available on gfx9+, and not available for v2f16. 10451 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 10452 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 10453 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 10454 // then give the other result, which is different from med3 with a NaN 10455 // input. 10456 SDValue Var = Op0.getOperand(0); 10457 if (!DAG.isKnownNeverSNaN(Var)) 10458 return SDValue(); 10459 10460 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10461 10462 if ((!K0->hasOneUse() || 10463 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 10464 (!K1->hasOneUse() || 10465 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 10466 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 10467 Var, SDValue(K0, 0), SDValue(K1, 0)); 10468 } 10469 } 10470 10471 return SDValue(); 10472 } 10473 10474 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 10475 DAGCombinerInfo &DCI) const { 10476 SelectionDAG &DAG = DCI.DAG; 10477 10478 EVT VT = N->getValueType(0); 10479 unsigned Opc = N->getOpcode(); 10480 SDValue Op0 = N->getOperand(0); 10481 SDValue Op1 = N->getOperand(1); 10482 10483 // Only do this if the inner op has one use since this will just increases 10484 // register pressure for no benefit. 10485 10486 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 10487 !VT.isVector() && 10488 (VT == MVT::i32 || VT == MVT::f32 || 10489 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 10490 // max(max(a, b), c) -> max3(a, b, c) 10491 // min(min(a, b), c) -> min3(a, b, c) 10492 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 10493 SDLoc DL(N); 10494 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10495 DL, 10496 N->getValueType(0), 10497 Op0.getOperand(0), 10498 Op0.getOperand(1), 10499 Op1); 10500 } 10501 10502 // Try commuted. 10503 // max(a, max(b, c)) -> max3(a, b, c) 10504 // min(a, min(b, c)) -> min3(a, b, c) 10505 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 10506 SDLoc DL(N); 10507 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10508 DL, 10509 N->getValueType(0), 10510 Op0, 10511 Op1.getOperand(0), 10512 Op1.getOperand(1)); 10513 } 10514 } 10515 10516 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 10517 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 10518 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 10519 return Med3; 10520 } 10521 10522 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 10523 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 10524 return Med3; 10525 } 10526 10527 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 10528 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 10529 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 10530 (Opc == AMDGPUISD::FMIN_LEGACY && 10531 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 10532 (VT == MVT::f32 || VT == MVT::f64 || 10533 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 10534 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 10535 Op0.hasOneUse()) { 10536 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 10537 return Res; 10538 } 10539 10540 return SDValue(); 10541 } 10542 10543 static bool isClampZeroToOne(SDValue A, SDValue B) { 10544 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 10545 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 10546 // FIXME: Should this be allowing -0.0? 10547 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 10548 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 10549 } 10550 } 10551 10552 return false; 10553 } 10554 10555 // FIXME: Should only worry about snans for version with chain. 10556 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 10557 DAGCombinerInfo &DCI) const { 10558 EVT VT = N->getValueType(0); 10559 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 10560 // NaNs. With a NaN input, the order of the operands may change the result. 10561 10562 SelectionDAG &DAG = DCI.DAG; 10563 SDLoc SL(N); 10564 10565 SDValue Src0 = N->getOperand(0); 10566 SDValue Src1 = N->getOperand(1); 10567 SDValue Src2 = N->getOperand(2); 10568 10569 if (isClampZeroToOne(Src0, Src1)) { 10570 // const_a, const_b, x -> clamp is safe in all cases including signaling 10571 // nans. 10572 // FIXME: Should this be allowing -0.0? 10573 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 10574 } 10575 10576 const MachineFunction &MF = DAG.getMachineFunction(); 10577 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10578 10579 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 10580 // handling no dx10-clamp? 10581 if (Info->getMode().DX10Clamp) { 10582 // If NaNs is clamped to 0, we are free to reorder the inputs. 10583 10584 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10585 std::swap(Src0, Src1); 10586 10587 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 10588 std::swap(Src1, Src2); 10589 10590 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10591 std::swap(Src0, Src1); 10592 10593 if (isClampZeroToOne(Src1, Src2)) 10594 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 10595 } 10596 10597 return SDValue(); 10598 } 10599 10600 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 10601 DAGCombinerInfo &DCI) const { 10602 SDValue Src0 = N->getOperand(0); 10603 SDValue Src1 = N->getOperand(1); 10604 if (Src0.isUndef() && Src1.isUndef()) 10605 return DCI.DAG.getUNDEF(N->getValueType(0)); 10606 return SDValue(); 10607 } 10608 10609 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 10610 // expanded into a set of cmp/select instructions. 10611 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 10612 unsigned NumElem, 10613 bool IsDivergentIdx) { 10614 if (UseDivergentRegisterIndexing) 10615 return false; 10616 10617 unsigned VecSize = EltSize * NumElem; 10618 10619 // Sub-dword vectors of size 2 dword or less have better implementation. 10620 if (VecSize <= 64 && EltSize < 32) 10621 return false; 10622 10623 // Always expand the rest of sub-dword instructions, otherwise it will be 10624 // lowered via memory. 10625 if (EltSize < 32) 10626 return true; 10627 10628 // Always do this if var-idx is divergent, otherwise it will become a loop. 10629 if (IsDivergentIdx) 10630 return true; 10631 10632 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 10633 unsigned NumInsts = NumElem /* Number of compares */ + 10634 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 10635 return NumInsts <= 16; 10636 } 10637 10638 static bool shouldExpandVectorDynExt(SDNode *N) { 10639 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 10640 if (isa<ConstantSDNode>(Idx)) 10641 return false; 10642 10643 SDValue Vec = N->getOperand(0); 10644 EVT VecVT = Vec.getValueType(); 10645 EVT EltVT = VecVT.getVectorElementType(); 10646 unsigned EltSize = EltVT.getSizeInBits(); 10647 unsigned NumElem = VecVT.getVectorNumElements(); 10648 10649 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 10650 Idx->isDivergent()); 10651 } 10652 10653 SDValue SITargetLowering::performExtractVectorEltCombine( 10654 SDNode *N, DAGCombinerInfo &DCI) const { 10655 SDValue Vec = N->getOperand(0); 10656 SelectionDAG &DAG = DCI.DAG; 10657 10658 EVT VecVT = Vec.getValueType(); 10659 EVT EltVT = VecVT.getVectorElementType(); 10660 10661 if ((Vec.getOpcode() == ISD::FNEG || 10662 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 10663 SDLoc SL(N); 10664 EVT EltVT = N->getValueType(0); 10665 SDValue Idx = N->getOperand(1); 10666 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10667 Vec.getOperand(0), Idx); 10668 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 10669 } 10670 10671 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 10672 // => 10673 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 10674 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 10675 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 10676 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 10677 SDLoc SL(N); 10678 EVT EltVT = N->getValueType(0); 10679 SDValue Idx = N->getOperand(1); 10680 unsigned Opc = Vec.getOpcode(); 10681 10682 switch(Opc) { 10683 default: 10684 break; 10685 // TODO: Support other binary operations. 10686 case ISD::FADD: 10687 case ISD::FSUB: 10688 case ISD::FMUL: 10689 case ISD::ADD: 10690 case ISD::UMIN: 10691 case ISD::UMAX: 10692 case ISD::SMIN: 10693 case ISD::SMAX: 10694 case ISD::FMAXNUM: 10695 case ISD::FMINNUM: 10696 case ISD::FMAXNUM_IEEE: 10697 case ISD::FMINNUM_IEEE: { 10698 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10699 Vec.getOperand(0), Idx); 10700 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10701 Vec.getOperand(1), Idx); 10702 10703 DCI.AddToWorklist(Elt0.getNode()); 10704 DCI.AddToWorklist(Elt1.getNode()); 10705 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 10706 } 10707 } 10708 } 10709 10710 unsigned VecSize = VecVT.getSizeInBits(); 10711 unsigned EltSize = EltVT.getSizeInBits(); 10712 10713 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 10714 if (::shouldExpandVectorDynExt(N)) { 10715 SDLoc SL(N); 10716 SDValue Idx = N->getOperand(1); 10717 SDValue V; 10718 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10719 SDValue IC = DAG.getVectorIdxConstant(I, SL); 10720 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10721 if (I == 0) 10722 V = Elt; 10723 else 10724 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 10725 } 10726 return V; 10727 } 10728 10729 if (!DCI.isBeforeLegalize()) 10730 return SDValue(); 10731 10732 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 10733 // elements. This exposes more load reduction opportunities by replacing 10734 // multiple small extract_vector_elements with a single 32-bit extract. 10735 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10736 if (isa<MemSDNode>(Vec) && 10737 EltSize <= 16 && 10738 EltVT.isByteSized() && 10739 VecSize > 32 && 10740 VecSize % 32 == 0 && 10741 Idx) { 10742 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 10743 10744 unsigned BitIndex = Idx->getZExtValue() * EltSize; 10745 unsigned EltIdx = BitIndex / 32; 10746 unsigned LeftoverBitIdx = BitIndex % 32; 10747 SDLoc SL(N); 10748 10749 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 10750 DCI.AddToWorklist(Cast.getNode()); 10751 10752 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 10753 DAG.getConstant(EltIdx, SL, MVT::i32)); 10754 DCI.AddToWorklist(Elt.getNode()); 10755 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 10756 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 10757 DCI.AddToWorklist(Srl.getNode()); 10758 10759 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 10760 DCI.AddToWorklist(Trunc.getNode()); 10761 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 10762 } 10763 10764 return SDValue(); 10765 } 10766 10767 SDValue 10768 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 10769 DAGCombinerInfo &DCI) const { 10770 SDValue Vec = N->getOperand(0); 10771 SDValue Idx = N->getOperand(2); 10772 EVT VecVT = Vec.getValueType(); 10773 EVT EltVT = VecVT.getVectorElementType(); 10774 10775 // INSERT_VECTOR_ELT (<n x e>, var-idx) 10776 // => BUILD_VECTOR n x select (e, const-idx) 10777 if (!::shouldExpandVectorDynExt(N)) 10778 return SDValue(); 10779 10780 SelectionDAG &DAG = DCI.DAG; 10781 SDLoc SL(N); 10782 SDValue Ins = N->getOperand(1); 10783 EVT IdxVT = Idx.getValueType(); 10784 10785 SmallVector<SDValue, 16> Ops; 10786 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10787 SDValue IC = DAG.getConstant(I, SL, IdxVT); 10788 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10789 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 10790 Ops.push_back(V); 10791 } 10792 10793 return DAG.getBuildVector(VecVT, SL, Ops); 10794 } 10795 10796 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 10797 const SDNode *N0, 10798 const SDNode *N1) const { 10799 EVT VT = N0->getValueType(0); 10800 10801 // Only do this if we are not trying to support denormals. v_mad_f32 does not 10802 // support denormals ever. 10803 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 10804 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 10805 getSubtarget()->hasMadF16())) && 10806 isOperationLegal(ISD::FMAD, VT)) 10807 return ISD::FMAD; 10808 10809 const TargetOptions &Options = DAG.getTarget().Options; 10810 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10811 (N0->getFlags().hasAllowContract() && 10812 N1->getFlags().hasAllowContract())) && 10813 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10814 return ISD::FMA; 10815 } 10816 10817 return 0; 10818 } 10819 10820 // For a reassociatable opcode perform: 10821 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10822 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10823 SelectionDAG &DAG) const { 10824 EVT VT = N->getValueType(0); 10825 if (VT != MVT::i32 && VT != MVT::i64) 10826 return SDValue(); 10827 10828 if (DAG.isBaseWithConstantOffset(SDValue(N, 0))) 10829 return SDValue(); 10830 10831 unsigned Opc = N->getOpcode(); 10832 SDValue Op0 = N->getOperand(0); 10833 SDValue Op1 = N->getOperand(1); 10834 10835 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10836 return SDValue(); 10837 10838 if (Op0->isDivergent()) 10839 std::swap(Op0, Op1); 10840 10841 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10842 return SDValue(); 10843 10844 SDValue Op2 = Op1.getOperand(1); 10845 Op1 = Op1.getOperand(0); 10846 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10847 return SDValue(); 10848 10849 if (Op1->isDivergent()) 10850 std::swap(Op1, Op2); 10851 10852 SDLoc SL(N); 10853 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10854 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10855 } 10856 10857 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10858 EVT VT, 10859 SDValue N0, SDValue N1, SDValue N2, 10860 bool Signed) { 10861 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10862 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10863 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10864 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10865 } 10866 10867 // Fold (add (mul x, y), z) --> (mad_[iu]64_[iu]32 x, y, z) plus high 10868 // multiplies, if any. 10869 // 10870 // Full 64-bit multiplies that feed into an addition are lowered here instead 10871 // of using the generic expansion. The generic expansion ends up with 10872 // a tree of ADD nodes that prevents us from using the "add" part of the 10873 // MAD instruction. The expansion produced here results in a chain of ADDs 10874 // instead of a tree. 10875 SDValue SITargetLowering::tryFoldToMad64_32(SDNode *N, 10876 DAGCombinerInfo &DCI) const { 10877 assert(N->getOpcode() == ISD::ADD); 10878 10879 SelectionDAG &DAG = DCI.DAG; 10880 EVT VT = N->getValueType(0); 10881 SDLoc SL(N); 10882 SDValue LHS = N->getOperand(0); 10883 SDValue RHS = N->getOperand(1); 10884 10885 if (VT.isVector()) 10886 return SDValue(); 10887 10888 // S_MUL_HI_[IU]32 was added in gfx9, which allows us to keep the overall 10889 // result in scalar registers for uniform values. 10890 if (!N->isDivergent() && Subtarget->hasSMulHi()) 10891 return SDValue(); 10892 10893 unsigned NumBits = VT.getScalarSizeInBits(); 10894 if (NumBits <= 32 || NumBits > 64) 10895 return SDValue(); 10896 10897 if (LHS.getOpcode() != ISD::MUL) { 10898 assert(RHS.getOpcode() == ISD::MUL); 10899 std::swap(LHS, RHS); 10900 } 10901 10902 // Avoid the fold if it would unduly increase the number of multiplies due to 10903 // multiple uses, except on hardware with full-rate multiply-add (which is 10904 // part of full-rate 64-bit ops). 10905 if (!Subtarget->hasFullRate64Ops()) { 10906 unsigned NumUsers = 0; 10907 for (SDNode *Use : LHS->uses()) { 10908 // There is a use that does not feed into addition, so the multiply can't 10909 // be removed. We prefer MUL + ADD + ADDC over MAD + MUL. 10910 if (Use->getOpcode() != ISD::ADD) 10911 return SDValue(); 10912 10913 // We prefer 2xMAD over MUL + 2xADD + 2xADDC (code density), and prefer 10914 // MUL + 3xADD + 3xADDC over 3xMAD. 10915 ++NumUsers; 10916 if (NumUsers >= 3) 10917 return SDValue(); 10918 } 10919 } 10920 10921 SDValue MulLHS = LHS.getOperand(0); 10922 SDValue MulRHS = LHS.getOperand(1); 10923 SDValue AddRHS = RHS; 10924 10925 // Always check whether operands are small unsigned values, since that 10926 // knowledge is useful in more cases. Check for small signed values only if 10927 // doing so can unlock a shorter code sequence. 10928 bool MulLHSUnsigned32 = numBitsUnsigned(MulLHS, DAG) <= 32; 10929 bool MulRHSUnsigned32 = numBitsUnsigned(MulRHS, DAG) <= 32; 10930 10931 bool MulSignedLo = false; 10932 if (!MulLHSUnsigned32 || !MulRHSUnsigned32) { 10933 MulSignedLo = numBitsSigned(MulLHS, DAG) <= 32 && 10934 numBitsSigned(MulRHS, DAG) <= 32; 10935 } 10936 10937 // The operands and final result all have the same number of bits. If 10938 // operands need to be extended, they can be extended with garbage. The 10939 // resulting garbage in the high bits of the mad_[iu]64_[iu]32 result is 10940 // truncated away in the end. 10941 if (VT != MVT::i64) { 10942 MulLHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, MulLHS); 10943 MulRHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, MulRHS); 10944 AddRHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, AddRHS); 10945 } 10946 10947 // The basic code generated is conceptually straightforward. Pseudo code: 10948 // 10949 // accum = mad_64_32 lhs.lo, rhs.lo, accum 10950 // accum.hi = add (mul lhs.hi, rhs.lo), accum.hi 10951 // accum.hi = add (mul lhs.lo, rhs.hi), accum.hi 10952 // 10953 // The second and third lines are optional, depending on whether the factors 10954 // are {sign,zero}-extended or not. 10955 // 10956 // The actual DAG is noisier than the pseudo code, but only due to 10957 // instructions that disassemble values into low and high parts, and 10958 // assemble the final result. 10959 SDValue Zero = DAG.getConstant(0, SL, MVT::i32); 10960 SDValue One = DAG.getConstant(1, SL, MVT::i32); 10961 10962 auto MulLHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulLHS); 10963 auto MulRHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulRHS); 10964 SDValue Accum = 10965 getMad64_32(DAG, SL, MVT::i64, MulLHSLo, MulRHSLo, AddRHS, MulSignedLo); 10966 10967 if (!MulSignedLo && (!MulLHSUnsigned32 || !MulRHSUnsigned32)) { 10968 auto AccumLo = DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, Accum, Zero); 10969 auto AccumHi = DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, Accum, One); 10970 10971 if (!MulLHSUnsigned32) { 10972 auto MulLHSHi = 10973 DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, MulLHS, One); 10974 SDValue MulHi = DAG.getNode(ISD::MUL, SL, MVT::i32, MulLHSHi, MulRHSLo); 10975 AccumHi = DAG.getNode(ISD::ADD, SL, MVT::i32, MulHi, AccumHi); 10976 } 10977 10978 if (!MulRHSUnsigned32) { 10979 auto MulRHSHi = 10980 DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, MulRHS, One); 10981 SDValue MulHi = DAG.getNode(ISD::MUL, SL, MVT::i32, MulLHSLo, MulRHSHi); 10982 AccumHi = DAG.getNode(ISD::ADD, SL, MVT::i32, MulHi, AccumHi); 10983 } 10984 10985 Accum = DAG.getBuildVector(MVT::v2i32, SL, {AccumLo, AccumHi}); 10986 Accum = DAG.getBitcast(MVT::i64, Accum); 10987 } 10988 10989 if (VT != MVT::i64) 10990 Accum = DAG.getNode(ISD::TRUNCATE, SL, VT, Accum); 10991 return Accum; 10992 } 10993 10994 SDValue SITargetLowering::performAddCombine(SDNode *N, 10995 DAGCombinerInfo &DCI) const { 10996 SelectionDAG &DAG = DCI.DAG; 10997 EVT VT = N->getValueType(0); 10998 SDLoc SL(N); 10999 SDValue LHS = N->getOperand(0); 11000 SDValue RHS = N->getOperand(1); 11001 11002 if (LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) { 11003 if (Subtarget->hasMad64_32()) { 11004 if (SDValue Folded = tryFoldToMad64_32(N, DCI)) 11005 return Folded; 11006 } 11007 11008 return SDValue(); 11009 } 11010 11011 if (SDValue V = reassociateScalarOps(N, DAG)) { 11012 return V; 11013 } 11014 11015 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 11016 return SDValue(); 11017 11018 // add x, zext (setcc) => addcarry x, 0, setcc 11019 // add x, sext (setcc) => subcarry x, 0, setcc 11020 unsigned Opc = LHS.getOpcode(); 11021 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 11022 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 11023 std::swap(RHS, LHS); 11024 11025 Opc = RHS.getOpcode(); 11026 switch (Opc) { 11027 default: break; 11028 case ISD::ZERO_EXTEND: 11029 case ISD::SIGN_EXTEND: 11030 case ISD::ANY_EXTEND: { 11031 auto Cond = RHS.getOperand(0); 11032 // If this won't be a real VOPC output, we would still need to insert an 11033 // extra instruction anyway. 11034 if (!isBoolSGPR(Cond)) 11035 break; 11036 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 11037 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 11038 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 11039 return DAG.getNode(Opc, SL, VTList, Args); 11040 } 11041 case ISD::ADDCARRY: { 11042 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 11043 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 11044 if (!C || C->getZExtValue() != 0) break; 11045 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 11046 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 11047 } 11048 } 11049 return SDValue(); 11050 } 11051 11052 SDValue SITargetLowering::performSubCombine(SDNode *N, 11053 DAGCombinerInfo &DCI) const { 11054 SelectionDAG &DAG = DCI.DAG; 11055 EVT VT = N->getValueType(0); 11056 11057 if (VT != MVT::i32) 11058 return SDValue(); 11059 11060 SDLoc SL(N); 11061 SDValue LHS = N->getOperand(0); 11062 SDValue RHS = N->getOperand(1); 11063 11064 // sub x, zext (setcc) => subcarry x, 0, setcc 11065 // sub x, sext (setcc) => addcarry x, 0, setcc 11066 unsigned Opc = RHS.getOpcode(); 11067 switch (Opc) { 11068 default: break; 11069 case ISD::ZERO_EXTEND: 11070 case ISD::SIGN_EXTEND: 11071 case ISD::ANY_EXTEND: { 11072 auto Cond = RHS.getOperand(0); 11073 // If this won't be a real VOPC output, we would still need to insert an 11074 // extra instruction anyway. 11075 if (!isBoolSGPR(Cond)) 11076 break; 11077 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 11078 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 11079 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 11080 return DAG.getNode(Opc, SL, VTList, Args); 11081 } 11082 } 11083 11084 if (LHS.getOpcode() == ISD::SUBCARRY) { 11085 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 11086 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 11087 if (!C || !C->isZero()) 11088 return SDValue(); 11089 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 11090 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 11091 } 11092 return SDValue(); 11093 } 11094 11095 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 11096 DAGCombinerInfo &DCI) const { 11097 11098 if (N->getValueType(0) != MVT::i32) 11099 return SDValue(); 11100 11101 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11102 if (!C || C->getZExtValue() != 0) 11103 return SDValue(); 11104 11105 SelectionDAG &DAG = DCI.DAG; 11106 SDValue LHS = N->getOperand(0); 11107 11108 // addcarry (add x, y), 0, cc => addcarry x, y, cc 11109 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 11110 unsigned LHSOpc = LHS.getOpcode(); 11111 unsigned Opc = N->getOpcode(); 11112 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 11113 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 11114 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 11115 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 11116 } 11117 return SDValue(); 11118 } 11119 11120 SDValue SITargetLowering::performFAddCombine(SDNode *N, 11121 DAGCombinerInfo &DCI) const { 11122 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 11123 return SDValue(); 11124 11125 SelectionDAG &DAG = DCI.DAG; 11126 EVT VT = N->getValueType(0); 11127 11128 SDLoc SL(N); 11129 SDValue LHS = N->getOperand(0); 11130 SDValue RHS = N->getOperand(1); 11131 11132 // These should really be instruction patterns, but writing patterns with 11133 // source modifiers is a pain. 11134 11135 // fadd (fadd (a, a), b) -> mad 2.0, a, b 11136 if (LHS.getOpcode() == ISD::FADD) { 11137 SDValue A = LHS.getOperand(0); 11138 if (A == LHS.getOperand(1)) { 11139 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 11140 if (FusedOp != 0) { 11141 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 11142 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 11143 } 11144 } 11145 } 11146 11147 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 11148 if (RHS.getOpcode() == ISD::FADD) { 11149 SDValue A = RHS.getOperand(0); 11150 if (A == RHS.getOperand(1)) { 11151 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 11152 if (FusedOp != 0) { 11153 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 11154 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 11155 } 11156 } 11157 } 11158 11159 return SDValue(); 11160 } 11161 11162 SDValue SITargetLowering::performFSubCombine(SDNode *N, 11163 DAGCombinerInfo &DCI) const { 11164 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 11165 return SDValue(); 11166 11167 SelectionDAG &DAG = DCI.DAG; 11168 SDLoc SL(N); 11169 EVT VT = N->getValueType(0); 11170 assert(!VT.isVector()); 11171 11172 // Try to get the fneg to fold into the source modifier. This undoes generic 11173 // DAG combines and folds them into the mad. 11174 // 11175 // Only do this if we are not trying to support denormals. v_mad_f32 does 11176 // not support denormals ever. 11177 SDValue LHS = N->getOperand(0); 11178 SDValue RHS = N->getOperand(1); 11179 if (LHS.getOpcode() == ISD::FADD) { 11180 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 11181 SDValue A = LHS.getOperand(0); 11182 if (A == LHS.getOperand(1)) { 11183 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 11184 if (FusedOp != 0){ 11185 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 11186 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 11187 11188 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 11189 } 11190 } 11191 } 11192 11193 if (RHS.getOpcode() == ISD::FADD) { 11194 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 11195 11196 SDValue A = RHS.getOperand(0); 11197 if (A == RHS.getOperand(1)) { 11198 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 11199 if (FusedOp != 0){ 11200 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 11201 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 11202 } 11203 } 11204 } 11205 11206 return SDValue(); 11207 } 11208 11209 SDValue SITargetLowering::performFMACombine(SDNode *N, 11210 DAGCombinerInfo &DCI) const { 11211 SelectionDAG &DAG = DCI.DAG; 11212 EVT VT = N->getValueType(0); 11213 SDLoc SL(N); 11214 11215 if (!Subtarget->hasDot7Insts() || VT != MVT::f32) 11216 return SDValue(); 11217 11218 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 11219 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 11220 SDValue Op1 = N->getOperand(0); 11221 SDValue Op2 = N->getOperand(1); 11222 SDValue FMA = N->getOperand(2); 11223 11224 if (FMA.getOpcode() != ISD::FMA || 11225 Op1.getOpcode() != ISD::FP_EXTEND || 11226 Op2.getOpcode() != ISD::FP_EXTEND) 11227 return SDValue(); 11228 11229 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 11230 // regardless of the denorm mode setting. Therefore, 11231 // unsafe-fp-math/fp-contract is sufficient to allow generating fdot2. 11232 const TargetOptions &Options = DAG.getTarget().Options; 11233 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 11234 (N->getFlags().hasAllowContract() && 11235 FMA->getFlags().hasAllowContract())) { 11236 Op1 = Op1.getOperand(0); 11237 Op2 = Op2.getOperand(0); 11238 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 11239 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11240 return SDValue(); 11241 11242 SDValue Vec1 = Op1.getOperand(0); 11243 SDValue Idx1 = Op1.getOperand(1); 11244 SDValue Vec2 = Op2.getOperand(0); 11245 11246 SDValue FMAOp1 = FMA.getOperand(0); 11247 SDValue FMAOp2 = FMA.getOperand(1); 11248 SDValue FMAAcc = FMA.getOperand(2); 11249 11250 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 11251 FMAOp2.getOpcode() != ISD::FP_EXTEND) 11252 return SDValue(); 11253 11254 FMAOp1 = FMAOp1.getOperand(0); 11255 FMAOp2 = FMAOp2.getOperand(0); 11256 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 11257 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11258 return SDValue(); 11259 11260 SDValue Vec3 = FMAOp1.getOperand(0); 11261 SDValue Vec4 = FMAOp2.getOperand(0); 11262 SDValue Idx2 = FMAOp1.getOperand(1); 11263 11264 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 11265 // Idx1 and Idx2 cannot be the same. 11266 Idx1 == Idx2) 11267 return SDValue(); 11268 11269 if (Vec1 == Vec2 || Vec3 == Vec4) 11270 return SDValue(); 11271 11272 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 11273 return SDValue(); 11274 11275 if ((Vec1 == Vec3 && Vec2 == Vec4) || 11276 (Vec1 == Vec4 && Vec2 == Vec3)) { 11277 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 11278 DAG.getTargetConstant(0, SL, MVT::i1)); 11279 } 11280 } 11281 return SDValue(); 11282 } 11283 11284 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 11285 DAGCombinerInfo &DCI) const { 11286 SelectionDAG &DAG = DCI.DAG; 11287 SDLoc SL(N); 11288 11289 SDValue LHS = N->getOperand(0); 11290 SDValue RHS = N->getOperand(1); 11291 EVT VT = LHS.getValueType(); 11292 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 11293 11294 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 11295 if (!CRHS) { 11296 CRHS = dyn_cast<ConstantSDNode>(LHS); 11297 if (CRHS) { 11298 std::swap(LHS, RHS); 11299 CC = getSetCCSwappedOperands(CC); 11300 } 11301 } 11302 11303 if (CRHS) { 11304 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 11305 isBoolSGPR(LHS.getOperand(0))) { 11306 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 11307 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 11308 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 11309 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 11310 if ((CRHS->isAllOnes() && 11311 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 11312 (CRHS->isZero() && 11313 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 11314 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 11315 DAG.getConstant(-1, SL, MVT::i1)); 11316 if ((CRHS->isAllOnes() && 11317 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 11318 (CRHS->isZero() && 11319 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 11320 return LHS.getOperand(0); 11321 } 11322 11323 const APInt &CRHSVal = CRHS->getAPIntValue(); 11324 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 11325 LHS.getOpcode() == ISD::SELECT && 11326 isa<ConstantSDNode>(LHS.getOperand(1)) && 11327 isa<ConstantSDNode>(LHS.getOperand(2)) && 11328 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 11329 isBoolSGPR(LHS.getOperand(0))) { 11330 // Given CT != FT: 11331 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 11332 // setcc (select cc, CT, CF), CF, ne => cc 11333 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 11334 // setcc (select cc, CT, CF), CT, eq => cc 11335 const APInt &CT = LHS.getConstantOperandAPInt(1); 11336 const APInt &CF = LHS.getConstantOperandAPInt(2); 11337 11338 if ((CF == CRHSVal && CC == ISD::SETEQ) || 11339 (CT == CRHSVal && CC == ISD::SETNE)) 11340 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 11341 DAG.getConstant(-1, SL, MVT::i1)); 11342 if ((CF == CRHSVal && CC == ISD::SETNE) || 11343 (CT == CRHSVal && CC == ISD::SETEQ)) 11344 return LHS.getOperand(0); 11345 } 11346 } 11347 11348 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 11349 VT != MVT::f16)) 11350 return SDValue(); 11351 11352 // Match isinf/isfinite pattern 11353 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 11354 // (fcmp one (fabs x), inf) -> (fp_class x, 11355 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 11356 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 11357 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 11358 if (!CRHS) 11359 return SDValue(); 11360 11361 const APFloat &APF = CRHS->getValueAPF(); 11362 if (APF.isInfinity() && !APF.isNegative()) { 11363 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 11364 SIInstrFlags::N_INFINITY; 11365 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 11366 SIInstrFlags::P_ZERO | 11367 SIInstrFlags::N_NORMAL | 11368 SIInstrFlags::P_NORMAL | 11369 SIInstrFlags::N_SUBNORMAL | 11370 SIInstrFlags::P_SUBNORMAL; 11371 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 11372 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 11373 DAG.getConstant(Mask, SL, MVT::i32)); 11374 } 11375 } 11376 11377 return SDValue(); 11378 } 11379 11380 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 11381 DAGCombinerInfo &DCI) const { 11382 SelectionDAG &DAG = DCI.DAG; 11383 SDLoc SL(N); 11384 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 11385 11386 SDValue Src = N->getOperand(0); 11387 SDValue Shift = N->getOperand(0); 11388 11389 // TODO: Extend type shouldn't matter (assuming legal types). 11390 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 11391 Shift = Shift.getOperand(0); 11392 11393 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 11394 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 11395 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 11396 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 11397 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 11398 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 11399 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 11400 SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0), 11401 SDLoc(Shift.getOperand(0)), MVT::i32); 11402 11403 unsigned ShiftOffset = 8 * Offset; 11404 if (Shift.getOpcode() == ISD::SHL) 11405 ShiftOffset -= C->getZExtValue(); 11406 else 11407 ShiftOffset += C->getZExtValue(); 11408 11409 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 11410 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 11411 MVT::f32, Shifted); 11412 } 11413 } 11414 } 11415 11416 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11417 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 11418 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 11419 // We simplified Src. If this node is not dead, visit it again so it is 11420 // folded properly. 11421 if (N->getOpcode() != ISD::DELETED_NODE) 11422 DCI.AddToWorklist(N); 11423 return SDValue(N, 0); 11424 } 11425 11426 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 11427 if (SDValue DemandedSrc = 11428 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 11429 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 11430 11431 return SDValue(); 11432 } 11433 11434 SDValue SITargetLowering::performClampCombine(SDNode *N, 11435 DAGCombinerInfo &DCI) const { 11436 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 11437 if (!CSrc) 11438 return SDValue(); 11439 11440 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 11441 const APFloat &F = CSrc->getValueAPF(); 11442 APFloat Zero = APFloat::getZero(F.getSemantics()); 11443 if (F < Zero || 11444 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 11445 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 11446 } 11447 11448 APFloat One(F.getSemantics(), "1.0"); 11449 if (F > One) 11450 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 11451 11452 return SDValue(CSrc, 0); 11453 } 11454 11455 11456 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 11457 DAGCombinerInfo &DCI) const { 11458 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 11459 return SDValue(); 11460 switch (N->getOpcode()) { 11461 case ISD::ADD: 11462 return performAddCombine(N, DCI); 11463 case ISD::SUB: 11464 return performSubCombine(N, DCI); 11465 case ISD::ADDCARRY: 11466 case ISD::SUBCARRY: 11467 return performAddCarrySubCarryCombine(N, DCI); 11468 case ISD::FADD: 11469 return performFAddCombine(N, DCI); 11470 case ISD::FSUB: 11471 return performFSubCombine(N, DCI); 11472 case ISD::SETCC: 11473 return performSetCCCombine(N, DCI); 11474 case ISD::FMAXNUM: 11475 case ISD::FMINNUM: 11476 case ISD::FMAXNUM_IEEE: 11477 case ISD::FMINNUM_IEEE: 11478 case ISD::SMAX: 11479 case ISD::SMIN: 11480 case ISD::UMAX: 11481 case ISD::UMIN: 11482 case AMDGPUISD::FMIN_LEGACY: 11483 case AMDGPUISD::FMAX_LEGACY: 11484 return performMinMaxCombine(N, DCI); 11485 case ISD::FMA: 11486 return performFMACombine(N, DCI); 11487 case ISD::AND: 11488 return performAndCombine(N, DCI); 11489 case ISD::OR: 11490 return performOrCombine(N, DCI); 11491 case ISD::XOR: 11492 return performXorCombine(N, DCI); 11493 case ISD::ZERO_EXTEND: 11494 return performZeroExtendCombine(N, DCI); 11495 case ISD::SIGN_EXTEND_INREG: 11496 return performSignExtendInRegCombine(N , DCI); 11497 case AMDGPUISD::FP_CLASS: 11498 return performClassCombine(N, DCI); 11499 case ISD::FCANONICALIZE: 11500 return performFCanonicalizeCombine(N, DCI); 11501 case AMDGPUISD::RCP: 11502 return performRcpCombine(N, DCI); 11503 case AMDGPUISD::FRACT: 11504 case AMDGPUISD::RSQ: 11505 case AMDGPUISD::RCP_LEGACY: 11506 case AMDGPUISD::RCP_IFLAG: 11507 case AMDGPUISD::RSQ_CLAMP: 11508 case AMDGPUISD::LDEXP: { 11509 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 11510 SDValue Src = N->getOperand(0); 11511 if (Src.isUndef()) 11512 return Src; 11513 break; 11514 } 11515 case ISD::SINT_TO_FP: 11516 case ISD::UINT_TO_FP: 11517 return performUCharToFloatCombine(N, DCI); 11518 case AMDGPUISD::CVT_F32_UBYTE0: 11519 case AMDGPUISD::CVT_F32_UBYTE1: 11520 case AMDGPUISD::CVT_F32_UBYTE2: 11521 case AMDGPUISD::CVT_F32_UBYTE3: 11522 return performCvtF32UByteNCombine(N, DCI); 11523 case AMDGPUISD::FMED3: 11524 return performFMed3Combine(N, DCI); 11525 case AMDGPUISD::CVT_PKRTZ_F16_F32: 11526 return performCvtPkRTZCombine(N, DCI); 11527 case AMDGPUISD::CLAMP: 11528 return performClampCombine(N, DCI); 11529 case ISD::SCALAR_TO_VECTOR: { 11530 SelectionDAG &DAG = DCI.DAG; 11531 EVT VT = N->getValueType(0); 11532 11533 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 11534 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 11535 SDLoc SL(N); 11536 SDValue Src = N->getOperand(0); 11537 EVT EltVT = Src.getValueType(); 11538 if (EltVT == MVT::f16) 11539 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 11540 11541 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 11542 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 11543 } 11544 11545 break; 11546 } 11547 case ISD::EXTRACT_VECTOR_ELT: 11548 return performExtractVectorEltCombine(N, DCI); 11549 case ISD::INSERT_VECTOR_ELT: 11550 return performInsertVectorEltCombine(N, DCI); 11551 case ISD::LOAD: { 11552 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 11553 return Widended; 11554 LLVM_FALLTHROUGH; 11555 } 11556 default: { 11557 if (!DCI.isBeforeLegalize()) { 11558 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 11559 return performMemSDNodeCombine(MemNode, DCI); 11560 } 11561 11562 break; 11563 } 11564 } 11565 11566 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 11567 } 11568 11569 /// Helper function for adjustWritemask 11570 static unsigned SubIdx2Lane(unsigned Idx) { 11571 switch (Idx) { 11572 default: return ~0u; 11573 case AMDGPU::sub0: return 0; 11574 case AMDGPU::sub1: return 1; 11575 case AMDGPU::sub2: return 2; 11576 case AMDGPU::sub3: return 3; 11577 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 11578 } 11579 } 11580 11581 /// Adjust the writemask of MIMG instructions 11582 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 11583 SelectionDAG &DAG) const { 11584 unsigned Opcode = Node->getMachineOpcode(); 11585 11586 // Subtract 1 because the vdata output is not a MachineSDNode operand. 11587 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 11588 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 11589 return Node; // not implemented for D16 11590 11591 SDNode *Users[5] = { nullptr }; 11592 unsigned Lane = 0; 11593 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 11594 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 11595 unsigned NewDmask = 0; 11596 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 11597 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 11598 bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) || 11599 Node->getConstantOperandVal(LWEIdx)) 11600 ? true 11601 : false; 11602 unsigned TFCLane = 0; 11603 bool HasChain = Node->getNumValues() > 1; 11604 11605 if (OldDmask == 0) { 11606 // These are folded out, but on the chance it happens don't assert. 11607 return Node; 11608 } 11609 11610 unsigned OldBitsSet = countPopulation(OldDmask); 11611 // Work out which is the TFE/LWE lane if that is enabled. 11612 if (UsesTFC) { 11613 TFCLane = OldBitsSet; 11614 } 11615 11616 // Try to figure out the used register components 11617 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 11618 I != E; ++I) { 11619 11620 // Don't look at users of the chain. 11621 if (I.getUse().getResNo() != 0) 11622 continue; 11623 11624 // Abort if we can't understand the usage 11625 if (!I->isMachineOpcode() || 11626 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 11627 return Node; 11628 11629 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 11630 // Note that subregs are packed, i.e. Lane==0 is the first bit set 11631 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 11632 // set, etc. 11633 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 11634 if (Lane == ~0u) 11635 return Node; 11636 11637 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 11638 if (UsesTFC && Lane == TFCLane) { 11639 Users[Lane] = *I; 11640 } else { 11641 // Set which texture component corresponds to the lane. 11642 unsigned Comp; 11643 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 11644 Comp = countTrailingZeros(Dmask); 11645 Dmask &= ~(1 << Comp); 11646 } 11647 11648 // Abort if we have more than one user per component. 11649 if (Users[Lane]) 11650 return Node; 11651 11652 Users[Lane] = *I; 11653 NewDmask |= 1 << Comp; 11654 } 11655 } 11656 11657 // Don't allow 0 dmask, as hardware assumes one channel enabled. 11658 bool NoChannels = !NewDmask; 11659 if (NoChannels) { 11660 if (!UsesTFC) { 11661 // No uses of the result and not using TFC. Then do nothing. 11662 return Node; 11663 } 11664 // If the original dmask has one channel - then nothing to do 11665 if (OldBitsSet == 1) 11666 return Node; 11667 // Use an arbitrary dmask - required for the instruction to work 11668 NewDmask = 1; 11669 } 11670 // Abort if there's no change 11671 if (NewDmask == OldDmask) 11672 return Node; 11673 11674 unsigned BitsSet = countPopulation(NewDmask); 11675 11676 // Check for TFE or LWE - increase the number of channels by one to account 11677 // for the extra return value 11678 // This will need adjustment for D16 if this is also included in 11679 // adjustWriteMask (this function) but at present D16 are excluded. 11680 unsigned NewChannels = BitsSet + UsesTFC; 11681 11682 int NewOpcode = 11683 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 11684 assert(NewOpcode != -1 && 11685 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 11686 "failed to find equivalent MIMG op"); 11687 11688 // Adjust the writemask in the node 11689 SmallVector<SDValue, 12> Ops; 11690 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 11691 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 11692 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 11693 11694 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 11695 11696 MVT ResultVT = NewChannels == 1 ? 11697 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 11698 NewChannels == 5 ? 8 : NewChannels); 11699 SDVTList NewVTList = HasChain ? 11700 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 11701 11702 11703 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 11704 NewVTList, Ops); 11705 11706 if (HasChain) { 11707 // Update chain. 11708 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 11709 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 11710 } 11711 11712 if (NewChannels == 1) { 11713 assert(Node->hasNUsesOfValue(1, 0)); 11714 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 11715 SDLoc(Node), Users[Lane]->getValueType(0), 11716 SDValue(NewNode, 0)); 11717 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 11718 return nullptr; 11719 } 11720 11721 // Update the users of the node with the new indices 11722 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 11723 SDNode *User = Users[i]; 11724 if (!User) { 11725 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 11726 // Users[0] is still nullptr because channel 0 doesn't really have a use. 11727 if (i || !NoChannels) 11728 continue; 11729 } else { 11730 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 11731 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 11732 } 11733 11734 switch (Idx) { 11735 default: break; 11736 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 11737 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 11738 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 11739 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 11740 } 11741 } 11742 11743 DAG.RemoveDeadNode(Node); 11744 return nullptr; 11745 } 11746 11747 static bool isFrameIndexOp(SDValue Op) { 11748 if (Op.getOpcode() == ISD::AssertZext) 11749 Op = Op.getOperand(0); 11750 11751 return isa<FrameIndexSDNode>(Op); 11752 } 11753 11754 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 11755 /// with frame index operands. 11756 /// LLVM assumes that inputs are to these instructions are registers. 11757 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 11758 SelectionDAG &DAG) const { 11759 if (Node->getOpcode() == ISD::CopyToReg) { 11760 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 11761 SDValue SrcVal = Node->getOperand(2); 11762 11763 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 11764 // to try understanding copies to physical registers. 11765 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 11766 SDLoc SL(Node); 11767 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11768 SDValue VReg = DAG.getRegister( 11769 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 11770 11771 SDNode *Glued = Node->getGluedNode(); 11772 SDValue ToVReg 11773 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 11774 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 11775 SDValue ToResultReg 11776 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 11777 VReg, ToVReg.getValue(1)); 11778 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 11779 DAG.RemoveDeadNode(Node); 11780 return ToResultReg.getNode(); 11781 } 11782 } 11783 11784 SmallVector<SDValue, 8> Ops; 11785 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 11786 if (!isFrameIndexOp(Node->getOperand(i))) { 11787 Ops.push_back(Node->getOperand(i)); 11788 continue; 11789 } 11790 11791 SDLoc DL(Node); 11792 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 11793 Node->getOperand(i).getValueType(), 11794 Node->getOperand(i)), 0)); 11795 } 11796 11797 return DAG.UpdateNodeOperands(Node, Ops); 11798 } 11799 11800 /// Fold the instructions after selecting them. 11801 /// Returns null if users were already updated. 11802 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 11803 SelectionDAG &DAG) const { 11804 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11805 unsigned Opcode = Node->getMachineOpcode(); 11806 11807 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 11808 !TII->isGather4(Opcode) && 11809 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) { 11810 return adjustWritemask(Node, DAG); 11811 } 11812 11813 if (Opcode == AMDGPU::INSERT_SUBREG || 11814 Opcode == AMDGPU::REG_SEQUENCE) { 11815 legalizeTargetIndependentNode(Node, DAG); 11816 return Node; 11817 } 11818 11819 switch (Opcode) { 11820 case AMDGPU::V_DIV_SCALE_F32_e64: 11821 case AMDGPU::V_DIV_SCALE_F64_e64: { 11822 // Satisfy the operand register constraint when one of the inputs is 11823 // undefined. Ordinarily each undef value will have its own implicit_def of 11824 // a vreg, so force these to use a single register. 11825 SDValue Src0 = Node->getOperand(1); 11826 SDValue Src1 = Node->getOperand(3); 11827 SDValue Src2 = Node->getOperand(5); 11828 11829 if ((Src0.isMachineOpcode() && 11830 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 11831 (Src0 == Src1 || Src0 == Src2)) 11832 break; 11833 11834 MVT VT = Src0.getValueType().getSimpleVT(); 11835 const TargetRegisterClass *RC = 11836 getRegClassFor(VT, Src0.getNode()->isDivergent()); 11837 11838 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11839 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 11840 11841 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 11842 UndefReg, Src0, SDValue()); 11843 11844 // src0 must be the same register as src1 or src2, even if the value is 11845 // undefined, so make sure we don't violate this constraint. 11846 if (Src0.isMachineOpcode() && 11847 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 11848 if (Src1.isMachineOpcode() && 11849 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11850 Src0 = Src1; 11851 else if (Src2.isMachineOpcode() && 11852 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11853 Src0 = Src2; 11854 else { 11855 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 11856 Src0 = UndefReg; 11857 Src1 = UndefReg; 11858 } 11859 } else 11860 break; 11861 11862 SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end()); 11863 Ops[1] = Src0; 11864 Ops[3] = Src1; 11865 Ops[5] = Src2; 11866 Ops.push_back(ImpDef.getValue(1)); 11867 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 11868 } 11869 default: 11870 break; 11871 } 11872 11873 return Node; 11874 } 11875 11876 // Any MIMG instructions that use tfe or lwe require an initialization of the 11877 // result register that will be written in the case of a memory access failure. 11878 // The required code is also added to tie this init code to the result of the 11879 // img instruction. 11880 void SITargetLowering::AddIMGInit(MachineInstr &MI) const { 11881 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11882 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 11883 MachineRegisterInfo &MRI = MI.getMF()->getRegInfo(); 11884 MachineBasicBlock &MBB = *MI.getParent(); 11885 11886 MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe); 11887 MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe); 11888 MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16); 11889 11890 if (!TFE && !LWE) // intersect_ray 11891 return; 11892 11893 unsigned TFEVal = TFE ? TFE->getImm() : 0; 11894 unsigned LWEVal = LWE->getImm(); 11895 unsigned D16Val = D16 ? D16->getImm() : 0; 11896 11897 if (!TFEVal && !LWEVal) 11898 return; 11899 11900 // At least one of TFE or LWE are non-zero 11901 // We have to insert a suitable initialization of the result value and 11902 // tie this to the dest of the image instruction. 11903 11904 const DebugLoc &DL = MI.getDebugLoc(); 11905 11906 int DstIdx = 11907 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata); 11908 11909 // Calculate which dword we have to initialize to 0. 11910 MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask); 11911 11912 // check that dmask operand is found. 11913 assert(MO_Dmask && "Expected dmask operand in instruction"); 11914 11915 unsigned dmask = MO_Dmask->getImm(); 11916 // Determine the number of active lanes taking into account the 11917 // Gather4 special case 11918 unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask); 11919 11920 bool Packed = !Subtarget->hasUnpackedD16VMem(); 11921 11922 unsigned InitIdx = 11923 D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1; 11924 11925 // Abandon attempt if the dst size isn't large enough 11926 // - this is in fact an error but this is picked up elsewhere and 11927 // reported correctly. 11928 uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32; 11929 if (DstSize < InitIdx) 11930 return; 11931 11932 // Create a register for the initialization value. 11933 Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11934 unsigned NewDst = 0; // Final initialized value will be in here 11935 11936 // If PRTStrictNull feature is enabled (the default) then initialize 11937 // all the result registers to 0, otherwise just the error indication 11938 // register (VGPRn+1) 11939 unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1; 11940 unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1); 11941 11942 BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst); 11943 for (; SizeLeft; SizeLeft--, CurrIdx++) { 11944 NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11945 // Initialize dword 11946 Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 11947 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg) 11948 .addImm(0); 11949 // Insert into the super-reg 11950 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst) 11951 .addReg(PrevDst) 11952 .addReg(SubReg) 11953 .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx)); 11954 11955 PrevDst = NewDst; 11956 } 11957 11958 // Add as an implicit operand 11959 MI.addOperand(MachineOperand::CreateReg(NewDst, false, true)); 11960 11961 // Tie the just added implicit operand to the dst 11962 MI.tieOperands(DstIdx, MI.getNumOperands() - 1); 11963 } 11964 11965 /// Assign the register class depending on the number of 11966 /// bits set in the writemask 11967 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11968 SDNode *Node) const { 11969 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11970 11971 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 11972 11973 if (TII->isVOP3(MI.getOpcode())) { 11974 // Make sure constant bus requirements are respected. 11975 TII->legalizeOperandsVOP3(MRI, MI); 11976 11977 // Prefer VGPRs over AGPRs in mAI instructions where possible. 11978 // This saves a chain-copy of registers and better balance register 11979 // use between vgpr and agpr as agpr tuples tend to be big. 11980 if (MI.getDesc().OpInfo) { 11981 unsigned Opc = MI.getOpcode(); 11982 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11983 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 11984 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 11985 if (I == -1) 11986 break; 11987 MachineOperand &Op = MI.getOperand(I); 11988 if (!Op.isReg() || !Op.getReg().isVirtual()) 11989 continue; 11990 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11991 if (!TRI->hasAGPRs(RC)) 11992 continue; 11993 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11994 if (!Src || !Src->isCopy() || 11995 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11996 continue; 11997 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11998 // All uses of agpr64 and agpr32 can also accept vgpr except for 11999 // v_accvgpr_read, but we do not produce agpr reads during selection, 12000 // so no use checks are needed. 12001 MRI.setRegClass(Op.getReg(), NewRC); 12002 } 12003 12004 // Resolve the rest of AV operands to AGPRs. 12005 if (auto *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2)) { 12006 if (Src2->isReg() && Src2->getReg().isVirtual()) { 12007 auto *RC = TRI->getRegClassForReg(MRI, Src2->getReg()); 12008 if (TRI->isVectorSuperClass(RC)) { 12009 auto *NewRC = TRI->getEquivalentAGPRClass(RC); 12010 MRI.setRegClass(Src2->getReg(), NewRC); 12011 if (Src2->isTied()) 12012 MRI.setRegClass(MI.getOperand(0).getReg(), NewRC); 12013 } 12014 } 12015 } 12016 } 12017 12018 return; 12019 } 12020 12021 if (TII->isMIMG(MI) && !MI.mayStore()) 12022 AddIMGInit(MI); 12023 } 12024 12025 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 12026 uint64_t Val) { 12027 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 12028 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 12029 } 12030 12031 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 12032 const SDLoc &DL, 12033 SDValue Ptr) const { 12034 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 12035 12036 // Build the half of the subregister with the constants before building the 12037 // full 128-bit register. If we are building multiple resource descriptors, 12038 // this will allow CSEing of the 2-component register. 12039 const SDValue Ops0[] = { 12040 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 12041 buildSMovImm32(DAG, DL, 0), 12042 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 12043 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 12044 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 12045 }; 12046 12047 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 12048 MVT::v2i32, Ops0), 0); 12049 12050 // Combine the constants and the pointer. 12051 const SDValue Ops1[] = { 12052 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 12053 Ptr, 12054 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 12055 SubRegHi, 12056 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 12057 }; 12058 12059 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 12060 } 12061 12062 /// Return a resource descriptor with the 'Add TID' bit enabled 12063 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 12064 /// of the resource descriptor) to create an offset, which is added to 12065 /// the resource pointer. 12066 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 12067 SDValue Ptr, uint32_t RsrcDword1, 12068 uint64_t RsrcDword2And3) const { 12069 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 12070 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 12071 if (RsrcDword1) { 12072 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 12073 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 12074 0); 12075 } 12076 12077 SDValue DataLo = buildSMovImm32(DAG, DL, 12078 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 12079 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 12080 12081 const SDValue Ops[] = { 12082 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 12083 PtrLo, 12084 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 12085 PtrHi, 12086 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 12087 DataLo, 12088 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 12089 DataHi, 12090 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 12091 }; 12092 12093 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 12094 } 12095 12096 //===----------------------------------------------------------------------===// 12097 // SI Inline Assembly Support 12098 //===----------------------------------------------------------------------===// 12099 12100 std::pair<unsigned, const TargetRegisterClass *> 12101 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_, 12102 StringRef Constraint, 12103 MVT VT) const { 12104 const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_); 12105 12106 const TargetRegisterClass *RC = nullptr; 12107 if (Constraint.size() == 1) { 12108 const unsigned BitWidth = VT.getSizeInBits(); 12109 switch (Constraint[0]) { 12110 default: 12111 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 12112 case 's': 12113 case 'r': 12114 switch (BitWidth) { 12115 case 16: 12116 RC = &AMDGPU::SReg_32RegClass; 12117 break; 12118 case 64: 12119 RC = &AMDGPU::SGPR_64RegClass; 12120 break; 12121 default: 12122 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 12123 if (!RC) 12124 return std::make_pair(0U, nullptr); 12125 break; 12126 } 12127 break; 12128 case 'v': 12129 switch (BitWidth) { 12130 case 16: 12131 RC = &AMDGPU::VGPR_32RegClass; 12132 break; 12133 default: 12134 RC = TRI->getVGPRClassForBitWidth(BitWidth); 12135 if (!RC) 12136 return std::make_pair(0U, nullptr); 12137 break; 12138 } 12139 break; 12140 case 'a': 12141 if (!Subtarget->hasMAIInsts()) 12142 break; 12143 switch (BitWidth) { 12144 case 16: 12145 RC = &AMDGPU::AGPR_32RegClass; 12146 break; 12147 default: 12148 RC = TRI->getAGPRClassForBitWidth(BitWidth); 12149 if (!RC) 12150 return std::make_pair(0U, nullptr); 12151 break; 12152 } 12153 break; 12154 } 12155 // We actually support i128, i16 and f16 as inline parameters 12156 // even if they are not reported as legal 12157 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 12158 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 12159 return std::make_pair(0U, RC); 12160 } 12161 12162 if (Constraint.startswith("{") && Constraint.endswith("}")) { 12163 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2); 12164 if (RegName.consume_front("v")) { 12165 RC = &AMDGPU::VGPR_32RegClass; 12166 } else if (RegName.consume_front("s")) { 12167 RC = &AMDGPU::SGPR_32RegClass; 12168 } else if (RegName.consume_front("a")) { 12169 RC = &AMDGPU::AGPR_32RegClass; 12170 } 12171 12172 if (RC) { 12173 uint32_t Idx; 12174 if (RegName.consume_front("[")) { 12175 uint32_t End; 12176 bool Failed = RegName.consumeInteger(10, Idx); 12177 Failed |= !RegName.consume_front(":"); 12178 Failed |= RegName.consumeInteger(10, End); 12179 Failed |= !RegName.consume_back("]"); 12180 if (!Failed) { 12181 uint32_t Width = (End - Idx + 1) * 32; 12182 MCRegister Reg = RC->getRegister(Idx); 12183 if (SIRegisterInfo::isVGPRClass(RC)) 12184 RC = TRI->getVGPRClassForBitWidth(Width); 12185 else if (SIRegisterInfo::isSGPRClass(RC)) 12186 RC = TRI->getSGPRClassForBitWidth(Width); 12187 else if (SIRegisterInfo::isAGPRClass(RC)) 12188 RC = TRI->getAGPRClassForBitWidth(Width); 12189 if (RC) { 12190 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC); 12191 return std::make_pair(Reg, RC); 12192 } 12193 } 12194 } else { 12195 bool Failed = RegName.getAsInteger(10, Idx); 12196 if (!Failed && Idx < RC->getNumRegs()) 12197 return std::make_pair(RC->getRegister(Idx), RC); 12198 } 12199 } 12200 } 12201 12202 auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 12203 if (Ret.first) 12204 Ret.second = TRI->getPhysRegClass(Ret.first); 12205 12206 return Ret; 12207 } 12208 12209 static bool isImmConstraint(StringRef Constraint) { 12210 if (Constraint.size() == 1) { 12211 switch (Constraint[0]) { 12212 default: break; 12213 case 'I': 12214 case 'J': 12215 case 'A': 12216 case 'B': 12217 case 'C': 12218 return true; 12219 } 12220 } else if (Constraint == "DA" || 12221 Constraint == "DB") { 12222 return true; 12223 } 12224 return false; 12225 } 12226 12227 SITargetLowering::ConstraintType 12228 SITargetLowering::getConstraintType(StringRef Constraint) const { 12229 if (Constraint.size() == 1) { 12230 switch (Constraint[0]) { 12231 default: break; 12232 case 's': 12233 case 'v': 12234 case 'a': 12235 return C_RegisterClass; 12236 } 12237 } 12238 if (isImmConstraint(Constraint)) { 12239 return C_Other; 12240 } 12241 return TargetLowering::getConstraintType(Constraint); 12242 } 12243 12244 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 12245 if (!AMDGPU::isInlinableIntLiteral(Val)) { 12246 Val = Val & maskTrailingOnes<uint64_t>(Size); 12247 } 12248 return Val; 12249 } 12250 12251 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 12252 std::string &Constraint, 12253 std::vector<SDValue> &Ops, 12254 SelectionDAG &DAG) const { 12255 if (isImmConstraint(Constraint)) { 12256 uint64_t Val; 12257 if (getAsmOperandConstVal(Op, Val) && 12258 checkAsmConstraintVal(Op, Constraint, Val)) { 12259 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 12260 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 12261 } 12262 } else { 12263 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 12264 } 12265 } 12266 12267 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 12268 unsigned Size = Op.getScalarValueSizeInBits(); 12269 if (Size > 64) 12270 return false; 12271 12272 if (Size == 16 && !Subtarget->has16BitInsts()) 12273 return false; 12274 12275 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 12276 Val = C->getSExtValue(); 12277 return true; 12278 } 12279 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 12280 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 12281 return true; 12282 } 12283 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 12284 if (Size != 16 || Op.getNumOperands() != 2) 12285 return false; 12286 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 12287 return false; 12288 if (ConstantSDNode *C = V->getConstantSplatNode()) { 12289 Val = C->getSExtValue(); 12290 return true; 12291 } 12292 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 12293 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 12294 return true; 12295 } 12296 } 12297 12298 return false; 12299 } 12300 12301 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 12302 const std::string &Constraint, 12303 uint64_t Val) const { 12304 if (Constraint.size() == 1) { 12305 switch (Constraint[0]) { 12306 case 'I': 12307 return AMDGPU::isInlinableIntLiteral(Val); 12308 case 'J': 12309 return isInt<16>(Val); 12310 case 'A': 12311 return checkAsmConstraintValA(Op, Val); 12312 case 'B': 12313 return isInt<32>(Val); 12314 case 'C': 12315 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 12316 AMDGPU::isInlinableIntLiteral(Val); 12317 default: 12318 break; 12319 } 12320 } else if (Constraint.size() == 2) { 12321 if (Constraint == "DA") { 12322 int64_t HiBits = static_cast<int32_t>(Val >> 32); 12323 int64_t LoBits = static_cast<int32_t>(Val); 12324 return checkAsmConstraintValA(Op, HiBits, 32) && 12325 checkAsmConstraintValA(Op, LoBits, 32); 12326 } 12327 if (Constraint == "DB") { 12328 return true; 12329 } 12330 } 12331 llvm_unreachable("Invalid asm constraint"); 12332 } 12333 12334 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 12335 uint64_t Val, 12336 unsigned MaxSize) const { 12337 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 12338 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 12339 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 12340 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 12341 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 12342 return true; 12343 } 12344 return false; 12345 } 12346 12347 static int getAlignedAGPRClassID(unsigned UnalignedClassID) { 12348 switch (UnalignedClassID) { 12349 case AMDGPU::VReg_64RegClassID: 12350 return AMDGPU::VReg_64_Align2RegClassID; 12351 case AMDGPU::VReg_96RegClassID: 12352 return AMDGPU::VReg_96_Align2RegClassID; 12353 case AMDGPU::VReg_128RegClassID: 12354 return AMDGPU::VReg_128_Align2RegClassID; 12355 case AMDGPU::VReg_160RegClassID: 12356 return AMDGPU::VReg_160_Align2RegClassID; 12357 case AMDGPU::VReg_192RegClassID: 12358 return AMDGPU::VReg_192_Align2RegClassID; 12359 case AMDGPU::VReg_224RegClassID: 12360 return AMDGPU::VReg_224_Align2RegClassID; 12361 case AMDGPU::VReg_256RegClassID: 12362 return AMDGPU::VReg_256_Align2RegClassID; 12363 case AMDGPU::VReg_512RegClassID: 12364 return AMDGPU::VReg_512_Align2RegClassID; 12365 case AMDGPU::VReg_1024RegClassID: 12366 return AMDGPU::VReg_1024_Align2RegClassID; 12367 case AMDGPU::AReg_64RegClassID: 12368 return AMDGPU::AReg_64_Align2RegClassID; 12369 case AMDGPU::AReg_96RegClassID: 12370 return AMDGPU::AReg_96_Align2RegClassID; 12371 case AMDGPU::AReg_128RegClassID: 12372 return AMDGPU::AReg_128_Align2RegClassID; 12373 case AMDGPU::AReg_160RegClassID: 12374 return AMDGPU::AReg_160_Align2RegClassID; 12375 case AMDGPU::AReg_192RegClassID: 12376 return AMDGPU::AReg_192_Align2RegClassID; 12377 case AMDGPU::AReg_256RegClassID: 12378 return AMDGPU::AReg_256_Align2RegClassID; 12379 case AMDGPU::AReg_512RegClassID: 12380 return AMDGPU::AReg_512_Align2RegClassID; 12381 case AMDGPU::AReg_1024RegClassID: 12382 return AMDGPU::AReg_1024_Align2RegClassID; 12383 default: 12384 return -1; 12385 } 12386 } 12387 12388 // Figure out which registers should be reserved for stack access. Only after 12389 // the function is legalized do we know all of the non-spill stack objects or if 12390 // calls are present. 12391 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 12392 MachineRegisterInfo &MRI = MF.getRegInfo(); 12393 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 12394 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 12395 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12396 const SIInstrInfo *TII = ST.getInstrInfo(); 12397 12398 if (Info->isEntryFunction()) { 12399 // Callable functions have fixed registers used for stack access. 12400 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 12401 } 12402 12403 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 12404 Info->getStackPtrOffsetReg())); 12405 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 12406 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 12407 12408 // We need to worry about replacing the default register with itself in case 12409 // of MIR testcases missing the MFI. 12410 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 12411 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 12412 12413 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 12414 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 12415 12416 Info->limitOccupancy(MF); 12417 12418 if (ST.isWave32() && !MF.empty()) { 12419 for (auto &MBB : MF) { 12420 for (auto &MI : MBB) { 12421 TII->fixImplicitOperands(MI); 12422 } 12423 } 12424 } 12425 12426 // FIXME: This is a hack to fixup AGPR classes to use the properly aligned 12427 // classes if required. Ideally the register class constraints would differ 12428 // per-subtarget, but there's no easy way to achieve that right now. This is 12429 // not a problem for VGPRs because the correctly aligned VGPR class is implied 12430 // from using them as the register class for legal types. 12431 if (ST.needsAlignedVGPRs()) { 12432 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) { 12433 const Register Reg = Register::index2VirtReg(I); 12434 const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg); 12435 if (!RC) 12436 continue; 12437 int NewClassID = getAlignedAGPRClassID(RC->getID()); 12438 if (NewClassID != -1) 12439 MRI.setRegClass(Reg, TRI->getRegClass(NewClassID)); 12440 } 12441 } 12442 12443 TargetLoweringBase::finalizeLowering(MF); 12444 } 12445 12446 void SITargetLowering::computeKnownBitsForFrameIndex( 12447 const int FI, KnownBits &Known, const MachineFunction &MF) const { 12448 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 12449 12450 // Set the high bits to zero based on the maximum allowed scratch size per 12451 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 12452 // calculation won't overflow, so assume the sign bit is never set. 12453 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 12454 } 12455 12456 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 12457 KnownBits &Known, unsigned Dim) { 12458 unsigned MaxValue = 12459 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 12460 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 12461 } 12462 12463 void SITargetLowering::computeKnownBitsForTargetInstr( 12464 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 12465 const MachineRegisterInfo &MRI, unsigned Depth) const { 12466 const MachineInstr *MI = MRI.getVRegDef(R); 12467 switch (MI->getOpcode()) { 12468 case AMDGPU::G_INTRINSIC: { 12469 switch (MI->getIntrinsicID()) { 12470 case Intrinsic::amdgcn_workitem_id_x: 12471 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 12472 break; 12473 case Intrinsic::amdgcn_workitem_id_y: 12474 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 12475 break; 12476 case Intrinsic::amdgcn_workitem_id_z: 12477 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 12478 break; 12479 case Intrinsic::amdgcn_mbcnt_lo: 12480 case Intrinsic::amdgcn_mbcnt_hi: { 12481 // These return at most the wavefront size - 1. 12482 unsigned Size = MRI.getType(R).getSizeInBits(); 12483 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 12484 break; 12485 } 12486 case Intrinsic::amdgcn_groupstaticsize: { 12487 // We can report everything over the maximum size as 0. We can't report 12488 // based on the actual size because we don't know if it's accurate or not 12489 // at any given point. 12490 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 12491 break; 12492 } 12493 } 12494 break; 12495 } 12496 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE: 12497 Known.Zero.setHighBits(24); 12498 break; 12499 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT: 12500 Known.Zero.setHighBits(16); 12501 break; 12502 } 12503 } 12504 12505 Align SITargetLowering::computeKnownAlignForTargetInstr( 12506 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 12507 unsigned Depth) const { 12508 const MachineInstr *MI = MRI.getVRegDef(R); 12509 switch (MI->getOpcode()) { 12510 case AMDGPU::G_INTRINSIC: 12511 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 12512 // FIXME: Can this move to generic code? What about the case where the call 12513 // site specifies a lower alignment? 12514 Intrinsic::ID IID = MI->getIntrinsicID(); 12515 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 12516 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 12517 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 12518 return *RetAlign; 12519 return Align(1); 12520 } 12521 default: 12522 return Align(1); 12523 } 12524 } 12525 12526 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 12527 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 12528 const Align CacheLineAlign = Align(64); 12529 12530 // Pre-GFX10 target did not benefit from loop alignment 12531 if (!ML || DisableLoopAlignment || 12532 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 12533 getSubtarget()->hasInstFwdPrefetchBug()) 12534 return PrefAlign; 12535 12536 // On GFX10 I$ is 4 x 64 bytes cache lines. 12537 // By default prefetcher keeps one cache line behind and reads two ahead. 12538 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 12539 // behind and one ahead. 12540 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 12541 // If loop fits 64 bytes it always spans no more than two cache lines and 12542 // does not need an alignment. 12543 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 12544 // Else if loop is less or equal 192 bytes we need two lines behind. 12545 12546 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 12547 const MachineBasicBlock *Header = ML->getHeader(); 12548 if (Header->getAlignment() != PrefAlign) 12549 return Header->getAlignment(); // Already processed. 12550 12551 unsigned LoopSize = 0; 12552 for (const MachineBasicBlock *MBB : ML->blocks()) { 12553 // If inner loop block is aligned assume in average half of the alignment 12554 // size to be added as nops. 12555 if (MBB != Header) 12556 LoopSize += MBB->getAlignment().value() / 2; 12557 12558 for (const MachineInstr &MI : *MBB) { 12559 LoopSize += TII->getInstSizeInBytes(MI); 12560 if (LoopSize > 192) 12561 return PrefAlign; 12562 } 12563 } 12564 12565 if (LoopSize <= 64) 12566 return PrefAlign; 12567 12568 if (LoopSize <= 128) 12569 return CacheLineAlign; 12570 12571 // If any of parent loops is surrounded by prefetch instructions do not 12572 // insert new for inner loop, which would reset parent's settings. 12573 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 12574 if (MachineBasicBlock *Exit = P->getExitBlock()) { 12575 auto I = Exit->getFirstNonDebugInstr(); 12576 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 12577 return CacheLineAlign; 12578 } 12579 } 12580 12581 MachineBasicBlock *Pre = ML->getLoopPreheader(); 12582 MachineBasicBlock *Exit = ML->getExitBlock(); 12583 12584 if (Pre && Exit) { 12585 auto PreTerm = Pre->getFirstTerminator(); 12586 if (PreTerm == Pre->begin() || 12587 std::prev(PreTerm)->getOpcode() != AMDGPU::S_INST_PREFETCH) 12588 BuildMI(*Pre, PreTerm, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH)) 12589 .addImm(1); // prefetch 2 lines behind PC 12590 12591 auto ExitHead = Exit->getFirstNonDebugInstr(); 12592 if (ExitHead == Exit->end() || 12593 ExitHead->getOpcode() != AMDGPU::S_INST_PREFETCH) 12594 BuildMI(*Exit, ExitHead, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH)) 12595 .addImm(2); // prefetch 1 line behind PC 12596 } 12597 12598 return CacheLineAlign; 12599 } 12600 12601 LLVM_ATTRIBUTE_UNUSED 12602 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 12603 assert(N->getOpcode() == ISD::CopyFromReg); 12604 do { 12605 // Follow the chain until we find an INLINEASM node. 12606 N = N->getOperand(0).getNode(); 12607 if (N->getOpcode() == ISD::INLINEASM || 12608 N->getOpcode() == ISD::INLINEASM_BR) 12609 return true; 12610 } while (N->getOpcode() == ISD::CopyFromReg); 12611 return false; 12612 } 12613 12614 bool SITargetLowering::isSDNodeSourceOfDivergence( 12615 const SDNode *N, FunctionLoweringInfo *FLI, 12616 LegacyDivergenceAnalysis *KDA) const { 12617 switch (N->getOpcode()) { 12618 case ISD::CopyFromReg: { 12619 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 12620 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 12621 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12622 Register Reg = R->getReg(); 12623 12624 // FIXME: Why does this need to consider isLiveIn? 12625 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 12626 return !TRI->isSGPRReg(MRI, Reg); 12627 12628 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 12629 return KDA->isDivergent(V); 12630 12631 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 12632 return !TRI->isSGPRReg(MRI, Reg); 12633 } 12634 case ISD::LOAD: { 12635 const LoadSDNode *L = cast<LoadSDNode>(N); 12636 unsigned AS = L->getAddressSpace(); 12637 // A flat load may access private memory. 12638 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 12639 } 12640 case ISD::CALLSEQ_END: 12641 return true; 12642 case ISD::INTRINSIC_WO_CHAIN: 12643 return AMDGPU::isIntrinsicSourceOfDivergence( 12644 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 12645 case ISD::INTRINSIC_W_CHAIN: 12646 return AMDGPU::isIntrinsicSourceOfDivergence( 12647 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 12648 case AMDGPUISD::ATOMIC_CMP_SWAP: 12649 case AMDGPUISD::ATOMIC_INC: 12650 case AMDGPUISD::ATOMIC_DEC: 12651 case AMDGPUISD::ATOMIC_LOAD_FMIN: 12652 case AMDGPUISD::ATOMIC_LOAD_FMAX: 12653 case AMDGPUISD::BUFFER_ATOMIC_SWAP: 12654 case AMDGPUISD::BUFFER_ATOMIC_ADD: 12655 case AMDGPUISD::BUFFER_ATOMIC_SUB: 12656 case AMDGPUISD::BUFFER_ATOMIC_SMIN: 12657 case AMDGPUISD::BUFFER_ATOMIC_UMIN: 12658 case AMDGPUISD::BUFFER_ATOMIC_SMAX: 12659 case AMDGPUISD::BUFFER_ATOMIC_UMAX: 12660 case AMDGPUISD::BUFFER_ATOMIC_AND: 12661 case AMDGPUISD::BUFFER_ATOMIC_OR: 12662 case AMDGPUISD::BUFFER_ATOMIC_XOR: 12663 case AMDGPUISD::BUFFER_ATOMIC_INC: 12664 case AMDGPUISD::BUFFER_ATOMIC_DEC: 12665 case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP: 12666 case AMDGPUISD::BUFFER_ATOMIC_CSUB: 12667 case AMDGPUISD::BUFFER_ATOMIC_FADD: 12668 case AMDGPUISD::BUFFER_ATOMIC_FMIN: 12669 case AMDGPUISD::BUFFER_ATOMIC_FMAX: 12670 // Target-specific read-modify-write atomics are sources of divergence. 12671 return true; 12672 default: 12673 if (auto *A = dyn_cast<AtomicSDNode>(N)) { 12674 // Generic read-modify-write atomics are sources of divergence. 12675 return A->readMem() && A->writeMem(); 12676 } 12677 return false; 12678 } 12679 } 12680 12681 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 12682 EVT VT) const { 12683 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 12684 case MVT::f32: 12685 return hasFP32Denormals(DAG.getMachineFunction()); 12686 case MVT::f64: 12687 case MVT::f16: 12688 return hasFP64FP16Denormals(DAG.getMachineFunction()); 12689 default: 12690 return false; 12691 } 12692 } 12693 12694 bool SITargetLowering::denormalsEnabledForType(LLT Ty, 12695 MachineFunction &MF) const { 12696 switch (Ty.getScalarSizeInBits()) { 12697 case 32: 12698 return hasFP32Denormals(MF); 12699 case 64: 12700 case 16: 12701 return hasFP64FP16Denormals(MF); 12702 default: 12703 return false; 12704 } 12705 } 12706 12707 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 12708 const SelectionDAG &DAG, 12709 bool SNaN, 12710 unsigned Depth) const { 12711 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 12712 const MachineFunction &MF = DAG.getMachineFunction(); 12713 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 12714 12715 if (Info->getMode().DX10Clamp) 12716 return true; // Clamped to 0. 12717 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 12718 } 12719 12720 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 12721 SNaN, Depth); 12722 } 12723 12724 // Global FP atomic instructions have a hardcoded FP mode and do not support 12725 // FP32 denormals, and only support v2f16 denormals. 12726 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) { 12727 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics(); 12728 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt); 12729 if (&Flt == &APFloat::IEEEsingle()) 12730 return DenormMode == DenormalMode::getPreserveSign(); 12731 return DenormMode == DenormalMode::getIEEE(); 12732 } 12733 12734 TargetLowering::AtomicExpansionKind 12735 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 12736 unsigned AS = RMW->getPointerAddressSpace(); 12737 if (AS == AMDGPUAS::PRIVATE_ADDRESS) 12738 return AtomicExpansionKind::NotAtomic; 12739 12740 auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) { 12741 OptimizationRemarkEmitter ORE(RMW->getFunction()); 12742 LLVMContext &Ctx = RMW->getFunction()->getContext(); 12743 SmallVector<StringRef> SSNs; 12744 Ctx.getSyncScopeNames(SSNs); 12745 auto MemScope = SSNs[RMW->getSyncScopeID()].empty() 12746 ? "system" 12747 : SSNs[RMW->getSyncScopeID()]; 12748 ORE.emit([&]() { 12749 return OptimizationRemark(DEBUG_TYPE, "Passed", RMW) 12750 << "Hardware instruction generated for atomic " 12751 << RMW->getOperationName(RMW->getOperation()) 12752 << " operation at memory scope " << MemScope 12753 << " due to an unsafe request."; 12754 }); 12755 return Kind; 12756 }; 12757 12758 switch (RMW->getOperation()) { 12759 case AtomicRMWInst::FAdd: { 12760 Type *Ty = RMW->getType(); 12761 12762 // We don't have a way to support 16-bit atomics now, so just leave them 12763 // as-is. 12764 if (Ty->isHalfTy()) 12765 return AtomicExpansionKind::None; 12766 12767 if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy())) 12768 return AtomicExpansionKind::CmpXChg; 12769 12770 if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) && 12771 Subtarget->hasAtomicFaddInsts()) { 12772 if (Subtarget->hasGFX940Insts()) 12773 return AtomicExpansionKind::None; 12774 12775 // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe 12776 // floating point atomic instructions. May generate more efficient code, 12777 // but may not respect rounding and denormal modes, and may give incorrect 12778 // results for certain memory destinations. 12779 if (RMW->getFunction() 12780 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12781 .getValueAsString() != "true") 12782 return AtomicExpansionKind::CmpXChg; 12783 12784 if (Subtarget->hasGFX90AInsts()) { 12785 if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS) 12786 return AtomicExpansionKind::CmpXChg; 12787 12788 auto SSID = RMW->getSyncScopeID(); 12789 if (SSID == SyncScope::System || 12790 SSID == RMW->getContext().getOrInsertSyncScopeID("one-as")) 12791 return AtomicExpansionKind::CmpXChg; 12792 12793 return ReportUnsafeHWInst(AtomicExpansionKind::None); 12794 } 12795 12796 if (AS == AMDGPUAS::FLAT_ADDRESS) 12797 return AtomicExpansionKind::CmpXChg; 12798 12799 return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None) 12800 : AtomicExpansionKind::CmpXChg; 12801 } 12802 12803 // DS FP atomics do respect the denormal mode, but the rounding mode is 12804 // fixed to round-to-nearest-even. 12805 // The only exception is DS_ADD_F64 which never flushes regardless of mode. 12806 if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) { 12807 if (!Ty->isDoubleTy()) 12808 return AtomicExpansionKind::None; 12809 12810 if (fpModeMatchesGlobalFPAtomicMode(RMW)) 12811 return AtomicExpansionKind::None; 12812 12813 return RMW->getFunction() 12814 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12815 .getValueAsString() == "true" 12816 ? ReportUnsafeHWInst(AtomicExpansionKind::None) 12817 : AtomicExpansionKind::CmpXChg; 12818 } 12819 12820 return AtomicExpansionKind::CmpXChg; 12821 } 12822 default: 12823 break; 12824 } 12825 12826 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 12827 } 12828 12829 TargetLowering::AtomicExpansionKind 12830 SITargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 12831 return LI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS 12832 ? AtomicExpansionKind::NotAtomic 12833 : AtomicExpansionKind::None; 12834 } 12835 12836 TargetLowering::AtomicExpansionKind 12837 SITargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 12838 return SI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS 12839 ? AtomicExpansionKind::NotAtomic 12840 : AtomicExpansionKind::None; 12841 } 12842 12843 TargetLowering::AtomicExpansionKind 12844 SITargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *CmpX) const { 12845 return CmpX->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS 12846 ? AtomicExpansionKind::NotAtomic 12847 : AtomicExpansionKind::None; 12848 } 12849 12850 const TargetRegisterClass * 12851 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 12852 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 12853 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12854 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 12855 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 12856 : &AMDGPU::SReg_32RegClass; 12857 if (!TRI->isSGPRClass(RC) && !isDivergent) 12858 return TRI->getEquivalentSGPRClass(RC); 12859 else if (TRI->isSGPRClass(RC) && isDivergent) 12860 return TRI->getEquivalentVGPRClass(RC); 12861 12862 return RC; 12863 } 12864 12865 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 12866 // uniform values (as produced by the mask results of control flow intrinsics) 12867 // used outside of divergent blocks. The phi users need to also be treated as 12868 // always uniform. 12869 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 12870 unsigned WaveSize) { 12871 // FIXME: We assume we never cast the mask results of a control flow 12872 // intrinsic. 12873 // Early exit if the type won't be consistent as a compile time hack. 12874 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 12875 if (!IT || IT->getBitWidth() != WaveSize) 12876 return false; 12877 12878 if (!isa<Instruction>(V)) 12879 return false; 12880 if (!Visited.insert(V).second) 12881 return false; 12882 bool Result = false; 12883 for (auto U : V->users()) { 12884 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 12885 if (V == U->getOperand(1)) { 12886 switch (Intrinsic->getIntrinsicID()) { 12887 default: 12888 Result = false; 12889 break; 12890 case Intrinsic::amdgcn_if_break: 12891 case Intrinsic::amdgcn_if: 12892 case Intrinsic::amdgcn_else: 12893 Result = true; 12894 break; 12895 } 12896 } 12897 if (V == U->getOperand(0)) { 12898 switch (Intrinsic->getIntrinsicID()) { 12899 default: 12900 Result = false; 12901 break; 12902 case Intrinsic::amdgcn_end_cf: 12903 case Intrinsic::amdgcn_loop: 12904 Result = true; 12905 break; 12906 } 12907 } 12908 } else { 12909 Result = hasCFUser(U, Visited, WaveSize); 12910 } 12911 if (Result) 12912 break; 12913 } 12914 return Result; 12915 } 12916 12917 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 12918 const Value *V) const { 12919 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 12920 if (CI->isInlineAsm()) { 12921 // FIXME: This cannot give a correct answer. This should only trigger in 12922 // the case where inline asm returns mixed SGPR and VGPR results, used 12923 // outside the defining block. We don't have a specific result to 12924 // consider, so this assumes if any value is SGPR, the overall register 12925 // also needs to be SGPR. 12926 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 12927 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 12928 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 12929 for (auto &TC : TargetConstraints) { 12930 if (TC.Type == InlineAsm::isOutput) { 12931 ComputeConstraintToUse(TC, SDValue()); 12932 const TargetRegisterClass *RC = getRegForInlineAsmConstraint( 12933 SIRI, TC.ConstraintCode, TC.ConstraintVT).second; 12934 if (RC && SIRI->isSGPRClass(RC)) 12935 return true; 12936 } 12937 } 12938 } 12939 } 12940 SmallPtrSet<const Value *, 16> Visited; 12941 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 12942 } 12943 12944 std::pair<InstructionCost, MVT> 12945 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 12946 Type *Ty) const { 12947 std::pair<InstructionCost, MVT> Cost = 12948 TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 12949 auto Size = DL.getTypeSizeInBits(Ty); 12950 // Maximum load or store can handle 8 dwords for scalar and 4 for 12951 // vector ALU. Let's assume anything above 8 dwords is expensive 12952 // even if legal. 12953 if (Size <= 256) 12954 return Cost; 12955 12956 Cost.first += (Size + 255) / 256; 12957 return Cost; 12958 } 12959 12960 bool SITargetLowering::hasMemSDNodeUser(SDNode *N) const { 12961 SDNode::use_iterator I = N->use_begin(), E = N->use_end(); 12962 for (; I != E; ++I) { 12963 if (MemSDNode *M = dyn_cast<MemSDNode>(*I)) { 12964 if (getBasePtrIndex(M) == I.getOperandNo()) 12965 return true; 12966 } 12967 } 12968 return false; 12969 } 12970 12971 bool SITargetLowering::isReassocProfitable(SelectionDAG &DAG, SDValue N0, 12972 SDValue N1) const { 12973 if (!N0.hasOneUse()) 12974 return false; 12975 // Take care of the opportunity to keep N0 uniform 12976 if (N0->isDivergent() || !N1->isDivergent()) 12977 return true; 12978 // Check if we have a good chance to form the memory access pattern with the 12979 // base and offset 12980 return (DAG.isBaseWithConstantOffset(N0) && 12981 hasMemSDNodeUser(*N0->use_begin())); 12982 } 12983 12984 MachineMemOperand::Flags 12985 SITargetLowering::getTargetMMOFlags(const Instruction &I) const { 12986 // Propagate metadata set by AMDGPUAnnotateUniformValues to the MMO of a load. 12987 if (I.getMetadata("amdgpu.noclobber")) 12988 return MONoClobber; 12989 return MachineMemOperand::MONone; 12990 } 12991