1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 /// \file 10 /// Custom DAG lowering for SI 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "SIISelLowering.h" 15 #include "AMDGPU.h" 16 #include "AMDGPUInstrInfo.h" 17 #include "AMDGPUTargetMachine.h" 18 #include "SIMachineFunctionInfo.h" 19 #include "SIRegisterInfo.h" 20 #include "llvm/ADT/Statistic.h" 21 #include "llvm/Analysis/LegacyDivergenceAnalysis.h" 22 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 23 #include "llvm/BinaryFormat/ELF.h" 24 #include "llvm/CodeGen/Analysis.h" 25 #include "llvm/CodeGen/FunctionLoweringInfo.h" 26 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h" 27 #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h" 28 #include "llvm/CodeGen/MachineFunction.h" 29 #include "llvm/CodeGen/MachineLoopInfo.h" 30 #include "llvm/IR/DiagnosticInfo.h" 31 #include "llvm/IR/IntrinsicInst.h" 32 #include "llvm/IR/IntrinsicsAMDGPU.h" 33 #include "llvm/IR/IntrinsicsR600.h" 34 #include "llvm/Support/CommandLine.h" 35 #include "llvm/Support/KnownBits.h" 36 37 using namespace llvm; 38 39 #define DEBUG_TYPE "si-lower" 40 41 STATISTIC(NumTailCalls, "Number of tail calls"); 42 43 static cl::opt<bool> DisableLoopAlignment( 44 "amdgpu-disable-loop-alignment", 45 cl::desc("Do not align and prefetch loops"), 46 cl::init(false)); 47 48 static cl::opt<bool> UseDivergentRegisterIndexing( 49 "amdgpu-use-divergent-register-indexing", 50 cl::Hidden, 51 cl::desc("Use indirect register addressing for divergent indexes"), 52 cl::init(false)); 53 54 static bool hasFP32Denormals(const MachineFunction &MF) { 55 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 56 return Info->getMode().allFP32Denormals(); 57 } 58 59 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 60 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 61 return Info->getMode().allFP64FP16Denormals(); 62 } 63 64 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 65 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 66 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 67 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 68 return AMDGPU::SGPR0 + Reg; 69 } 70 } 71 llvm_unreachable("Cannot allocate sgpr"); 72 } 73 74 SITargetLowering::SITargetLowering(const TargetMachine &TM, 75 const GCNSubtarget &STI) 76 : AMDGPUTargetLowering(TM, STI), 77 Subtarget(&STI) { 78 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 79 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 80 81 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 82 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 83 84 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 85 86 const SIRegisterInfo *TRI = STI.getRegisterInfo(); 87 const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class(); 88 89 addRegisterClass(MVT::f64, V64RegClass); 90 addRegisterClass(MVT::v2f32, V64RegClass); 91 92 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 93 addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96)); 94 95 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 96 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 97 98 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 99 addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128)); 100 101 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 102 addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160)); 103 104 addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass); 105 addRegisterClass(MVT::v6f32, TRI->getVGPRClassForBitWidth(192)); 106 107 addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass); 108 addRegisterClass(MVT::v3f64, TRI->getVGPRClassForBitWidth(192)); 109 110 addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass); 111 addRegisterClass(MVT::v7f32, TRI->getVGPRClassForBitWidth(224)); 112 113 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass); 114 addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256)); 115 116 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass); 117 addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256)); 118 119 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass); 120 addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512)); 121 122 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass); 123 addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512)); 124 125 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass); 126 addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024)); 127 128 if (Subtarget->has16BitInsts()) { 129 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 130 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 131 132 // Unless there are also VOP3P operations, not operations are really legal. 133 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 134 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 135 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 136 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 137 } 138 139 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 140 addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024)); 141 142 computeRegisterProperties(Subtarget->getRegisterInfo()); 143 144 // The boolean content concept here is too inflexible. Compares only ever 145 // really produce a 1-bit result. Any copy/extend from these will turn into a 146 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 147 // it's what most targets use. 148 setBooleanContents(ZeroOrOneBooleanContent); 149 setBooleanVectorContents(ZeroOrOneBooleanContent); 150 151 // We need to custom lower vector stores from local memory 152 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 153 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 154 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 155 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 156 setOperationAction(ISD::LOAD, MVT::v6i32, Custom); 157 setOperationAction(ISD::LOAD, MVT::v7i32, Custom); 158 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 159 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 160 setOperationAction(ISD::LOAD, MVT::i1, Custom); 161 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 162 163 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 164 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 165 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 166 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 167 setOperationAction(ISD::STORE, MVT::v6i32, Custom); 168 setOperationAction(ISD::STORE, MVT::v7i32, Custom); 169 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 170 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 171 setOperationAction(ISD::STORE, MVT::i1, Custom); 172 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 173 174 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 175 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 176 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 177 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 178 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 179 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 180 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 181 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 182 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 183 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 184 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 185 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand); 186 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand); 187 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand); 188 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand); 189 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand); 190 191 setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand); 192 setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand); 193 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand); 194 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand); 195 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand); 196 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand); 197 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand); 198 199 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 200 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 201 202 setOperationAction(ISD::SELECT, MVT::i1, Promote); 203 setOperationAction(ISD::SELECT, MVT::i64, Custom); 204 setOperationAction(ISD::SELECT, MVT::f64, Promote); 205 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 206 207 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 208 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 209 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 210 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 211 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 212 213 setOperationAction(ISD::SETCC, MVT::i1, Promote); 214 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 215 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 216 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 217 218 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 219 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 220 setOperationAction(ISD::TRUNCATE, MVT::v3i32, Expand); 221 setOperationAction(ISD::FP_ROUND, MVT::v3f32, Expand); 222 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand); 223 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand); 224 setOperationAction(ISD::TRUNCATE, MVT::v5i32, Expand); 225 setOperationAction(ISD::FP_ROUND, MVT::v5f32, Expand); 226 setOperationAction(ISD::TRUNCATE, MVT::v6i32, Expand); 227 setOperationAction(ISD::FP_ROUND, MVT::v6f32, Expand); 228 setOperationAction(ISD::TRUNCATE, MVT::v7i32, Expand); 229 setOperationAction(ISD::FP_ROUND, MVT::v7f32, Expand); 230 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand); 231 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand); 232 setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand); 233 setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand); 234 235 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 236 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 237 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 238 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 239 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 240 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 241 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 242 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 243 244 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 245 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 246 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 247 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 248 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 249 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 250 251 setOperationAction(ISD::UADDO, MVT::i32, Legal); 252 setOperationAction(ISD::USUBO, MVT::i32, Legal); 253 254 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 255 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 256 257 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 258 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 259 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 260 261 #if 0 262 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 263 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 264 #endif 265 266 // We only support LOAD/STORE and vector manipulation ops for vectors 267 // with > 4 elements. 268 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 269 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 270 MVT::v3i64, MVT::v3f64, MVT::v6i32, MVT::v6f32, 271 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, 272 MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) { 273 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 274 switch (Op) { 275 case ISD::LOAD: 276 case ISD::STORE: 277 case ISD::BUILD_VECTOR: 278 case ISD::BITCAST: 279 case ISD::EXTRACT_VECTOR_ELT: 280 case ISD::INSERT_VECTOR_ELT: 281 case ISD::EXTRACT_SUBVECTOR: 282 case ISD::SCALAR_TO_VECTOR: 283 break; 284 case ISD::INSERT_SUBVECTOR: 285 case ISD::CONCAT_VECTORS: 286 setOperationAction(Op, VT, Custom); 287 break; 288 default: 289 setOperationAction(Op, VT, Expand); 290 break; 291 } 292 } 293 } 294 295 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 296 297 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 298 // is expanded to avoid having two separate loops in case the index is a VGPR. 299 300 // Most operations are naturally 32-bit vector operations. We only support 301 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 302 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 303 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 304 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 305 306 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 307 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 308 309 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 310 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 311 312 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 313 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 314 } 315 316 for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) { 317 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 318 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32); 319 320 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 321 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32); 322 323 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 324 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32); 325 326 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 327 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32); 328 } 329 330 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) { 331 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 332 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32); 333 334 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 335 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32); 336 337 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 338 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32); 339 340 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 341 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32); 342 } 343 344 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) { 345 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 346 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32); 347 348 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 349 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32); 350 351 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 352 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32); 353 354 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 355 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32); 356 } 357 358 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) { 359 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 360 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32); 361 362 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 363 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32); 364 365 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 366 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32); 367 368 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 369 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32); 370 } 371 372 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 373 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 374 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 375 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 376 377 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 378 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 379 380 // Avoid stack access for these. 381 // TODO: Generalize to more vector types. 382 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 383 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 384 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 385 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 386 387 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 388 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 389 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 390 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 391 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 392 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 393 394 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 395 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 396 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 397 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 398 399 // Deal with vec3 vector operations when widened to vec4. 400 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 401 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 402 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 403 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 404 405 // Deal with vec5/6/7 vector operations when widened to vec8. 406 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 407 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 408 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6i32, Custom); 409 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6f32, Custom); 410 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7i32, Custom); 411 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7f32, Custom); 412 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 413 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 414 415 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 416 // and output demarshalling 417 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 418 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 419 420 // We can't return success/failure, only the old value, 421 // let LLVM add the comparison 422 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 423 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 424 425 if (Subtarget->hasFlatAddressSpace()) { 426 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 427 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 428 } 429 430 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 431 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 432 433 // FIXME: This should be narrowed to i32, but that only happens if i64 is 434 // illegal. 435 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 436 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 437 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 438 439 // On SI this is s_memtime and s_memrealtime on VI. 440 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 441 setOperationAction(ISD::TRAP, MVT::Other, Custom); 442 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 443 444 if (Subtarget->has16BitInsts()) { 445 setOperationAction(ISD::FPOW, MVT::f16, Promote); 446 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 447 setOperationAction(ISD::FLOG, MVT::f16, Custom); 448 setOperationAction(ISD::FEXP, MVT::f16, Custom); 449 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 450 } 451 452 if (Subtarget->hasMadMacF32Insts()) 453 setOperationAction(ISD::FMAD, MVT::f32, Legal); 454 455 if (!Subtarget->hasBFI()) { 456 // fcopysign can be done in a single instruction with BFI. 457 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 458 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 459 } 460 461 if (!Subtarget->hasBCNT(32)) 462 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 463 464 if (!Subtarget->hasBCNT(64)) 465 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 466 467 if (Subtarget->hasFFBH()) { 468 setOperationAction(ISD::CTLZ, MVT::i32, Custom); 469 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 470 } 471 472 if (Subtarget->hasFFBL()) { 473 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 474 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 475 } 476 477 // We only really have 32-bit BFE instructions (and 16-bit on VI). 478 // 479 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 480 // effort to match them now. We want this to be false for i64 cases when the 481 // extraction isn't restricted to the upper or lower half. Ideally we would 482 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 483 // span the midpoint are probably relatively rare, so don't worry about them 484 // for now. 485 if (Subtarget->hasBFE()) 486 setHasExtractBitsInsn(true); 487 488 // Clamp modifier on add/sub 489 if (Subtarget->hasIntClamp()) { 490 setOperationAction(ISD::UADDSAT, MVT::i32, Legal); 491 setOperationAction(ISD::USUBSAT, MVT::i32, Legal); 492 } 493 494 if (Subtarget->hasAddNoCarry()) { 495 setOperationAction(ISD::SADDSAT, MVT::i16, Legal); 496 setOperationAction(ISD::SSUBSAT, MVT::i16, Legal); 497 setOperationAction(ISD::SADDSAT, MVT::i32, Legal); 498 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal); 499 } 500 501 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 502 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 503 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 504 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 505 506 507 // These are really only legal for ieee_mode functions. We should be avoiding 508 // them for functions that don't have ieee_mode enabled, so just say they are 509 // legal. 510 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 511 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 512 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 513 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 514 515 516 if (Subtarget->haveRoundOpsF64()) { 517 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 518 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 519 setOperationAction(ISD::FRINT, MVT::f64, Legal); 520 } else { 521 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 522 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 523 setOperationAction(ISD::FRINT, MVT::f64, Custom); 524 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 525 } 526 527 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 528 529 setOperationAction(ISD::FSIN, MVT::f32, Custom); 530 setOperationAction(ISD::FCOS, MVT::f32, Custom); 531 setOperationAction(ISD::FDIV, MVT::f32, Custom); 532 setOperationAction(ISD::FDIV, MVT::f64, Custom); 533 534 if (Subtarget->has16BitInsts()) { 535 setOperationAction(ISD::Constant, MVT::i16, Legal); 536 537 setOperationAction(ISD::SMIN, MVT::i16, Legal); 538 setOperationAction(ISD::SMAX, MVT::i16, Legal); 539 540 setOperationAction(ISD::UMIN, MVT::i16, Legal); 541 setOperationAction(ISD::UMAX, MVT::i16, Legal); 542 543 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 544 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 545 546 setOperationAction(ISD::ROTR, MVT::i16, Expand); 547 setOperationAction(ISD::ROTL, MVT::i16, Expand); 548 549 setOperationAction(ISD::SDIV, MVT::i16, Promote); 550 setOperationAction(ISD::UDIV, MVT::i16, Promote); 551 setOperationAction(ISD::SREM, MVT::i16, Promote); 552 setOperationAction(ISD::UREM, MVT::i16, Promote); 553 setOperationAction(ISD::UADDSAT, MVT::i16, Legal); 554 setOperationAction(ISD::USUBSAT, MVT::i16, Legal); 555 556 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 557 558 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 559 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 560 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 561 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 562 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 563 564 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 565 566 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 567 568 setOperationAction(ISD::LOAD, MVT::i16, Custom); 569 570 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 571 572 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 573 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 574 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 575 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 576 577 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Custom); 578 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Custom); 579 580 // F16 - Constant Actions. 581 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 582 583 // F16 - Load/Store Actions. 584 setOperationAction(ISD::LOAD, MVT::f16, Promote); 585 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 586 setOperationAction(ISD::STORE, MVT::f16, Promote); 587 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 588 589 // F16 - VOP1 Actions. 590 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 591 setOperationAction(ISD::FCOS, MVT::f16, Custom); 592 setOperationAction(ISD::FSIN, MVT::f16, Custom); 593 594 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 595 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 596 597 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 598 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 599 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 600 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 601 setOperationAction(ISD::FROUND, MVT::f16, Custom); 602 603 // F16 - VOP2 Actions. 604 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 605 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 606 607 setOperationAction(ISD::FDIV, MVT::f16, Custom); 608 609 // F16 - VOP3 Actions. 610 setOperationAction(ISD::FMA, MVT::f16, Legal); 611 if (STI.hasMadF16()) 612 setOperationAction(ISD::FMAD, MVT::f16, Legal); 613 614 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 615 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 616 switch (Op) { 617 case ISD::LOAD: 618 case ISD::STORE: 619 case ISD::BUILD_VECTOR: 620 case ISD::BITCAST: 621 case ISD::EXTRACT_VECTOR_ELT: 622 case ISD::INSERT_VECTOR_ELT: 623 case ISD::INSERT_SUBVECTOR: 624 case ISD::EXTRACT_SUBVECTOR: 625 case ISD::SCALAR_TO_VECTOR: 626 break; 627 case ISD::CONCAT_VECTORS: 628 setOperationAction(Op, VT, Custom); 629 break; 630 default: 631 setOperationAction(Op, VT, Expand); 632 break; 633 } 634 } 635 } 636 637 // v_perm_b32 can handle either of these. 638 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 639 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 640 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 641 642 // XXX - Do these do anything? Vector constants turn into build_vector. 643 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 644 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 645 646 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 647 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 648 649 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 650 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 651 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 652 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 653 654 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 655 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 656 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 657 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 658 659 setOperationAction(ISD::AND, MVT::v2i16, Promote); 660 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 661 setOperationAction(ISD::OR, MVT::v2i16, Promote); 662 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 663 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 664 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 665 666 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 667 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 668 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 669 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 670 671 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 672 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 673 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 674 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 675 676 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 677 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 678 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 679 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 680 681 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 682 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 683 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 684 685 if (!Subtarget->hasVOP3PInsts()) { 686 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 687 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 688 } 689 690 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 691 // This isn't really legal, but this avoids the legalizer unrolling it (and 692 // allows matching fneg (fabs x) patterns) 693 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 694 695 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 696 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 697 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 698 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 699 700 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 701 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 702 703 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 704 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 705 } 706 707 if (Subtarget->hasVOP3PInsts()) { 708 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 709 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 710 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 711 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 712 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 713 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 714 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 715 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 716 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 717 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 718 719 setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal); 720 setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal); 721 setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal); 722 setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal); 723 724 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 725 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 726 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 727 728 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 729 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 730 731 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 732 733 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 734 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 735 736 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 737 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 738 739 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 740 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 741 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 742 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 743 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 744 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 745 746 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 747 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 748 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 749 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 750 751 setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom); 752 setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom); 753 setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom); 754 setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom); 755 756 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 757 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 758 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 759 760 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 761 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 762 763 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 764 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 765 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 766 767 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 768 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 769 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 770 771 if (Subtarget->hasPackedFP32Ops()) { 772 setOperationAction(ISD::FADD, MVT::v2f32, Legal); 773 setOperationAction(ISD::FMUL, MVT::v2f32, Legal); 774 setOperationAction(ISD::FMA, MVT::v2f32, Legal); 775 setOperationAction(ISD::FNEG, MVT::v2f32, Legal); 776 777 for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) { 778 setOperationAction(ISD::FADD, VT, Custom); 779 setOperationAction(ISD::FMUL, VT, Custom); 780 setOperationAction(ISD::FMA, VT, Custom); 781 } 782 } 783 } 784 785 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 786 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 787 788 if (Subtarget->has16BitInsts()) { 789 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 790 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 791 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 792 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 793 } else { 794 // Legalization hack. 795 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 796 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 797 798 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 799 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 800 } 801 802 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 803 setOperationAction(ISD::SELECT, VT, Custom); 804 } 805 806 setOperationAction(ISD::SMULO, MVT::i64, Custom); 807 setOperationAction(ISD::UMULO, MVT::i64, Custom); 808 809 if (Subtarget->hasMad64_32()) { 810 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom); 811 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom); 812 } 813 814 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 815 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 816 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 817 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 818 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 819 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 820 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 821 822 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 823 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 824 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom); 825 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom); 826 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 827 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 828 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 829 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 830 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 831 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 832 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 833 834 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 835 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 836 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 837 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom); 838 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom); 839 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 840 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 841 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 842 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 843 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 844 845 setTargetDAGCombine(ISD::ADD); 846 setTargetDAGCombine(ISD::ADDCARRY); 847 setTargetDAGCombine(ISD::SUB); 848 setTargetDAGCombine(ISD::SUBCARRY); 849 setTargetDAGCombine(ISD::FADD); 850 setTargetDAGCombine(ISD::FSUB); 851 setTargetDAGCombine(ISD::FMINNUM); 852 setTargetDAGCombine(ISD::FMAXNUM); 853 setTargetDAGCombine(ISD::FMINNUM_IEEE); 854 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 855 setTargetDAGCombine(ISD::FMA); 856 setTargetDAGCombine(ISD::SMIN); 857 setTargetDAGCombine(ISD::SMAX); 858 setTargetDAGCombine(ISD::UMIN); 859 setTargetDAGCombine(ISD::UMAX); 860 setTargetDAGCombine(ISD::SETCC); 861 setTargetDAGCombine(ISD::AND); 862 setTargetDAGCombine(ISD::OR); 863 setTargetDAGCombine(ISD::XOR); 864 setTargetDAGCombine(ISD::SINT_TO_FP); 865 setTargetDAGCombine(ISD::UINT_TO_FP); 866 setTargetDAGCombine(ISD::FCANONICALIZE); 867 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 868 setTargetDAGCombine(ISD::ZERO_EXTEND); 869 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 870 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 871 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 872 873 // All memory operations. Some folding on the pointer operand is done to help 874 // matching the constant offsets in the addressing modes. 875 setTargetDAGCombine(ISD::LOAD); 876 setTargetDAGCombine(ISD::STORE); 877 setTargetDAGCombine(ISD::ATOMIC_LOAD); 878 setTargetDAGCombine(ISD::ATOMIC_STORE); 879 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 880 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 881 setTargetDAGCombine(ISD::ATOMIC_SWAP); 882 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 883 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 884 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 885 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 886 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 887 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 888 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 889 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 890 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 891 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 892 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 893 setTargetDAGCombine(ISD::INTRINSIC_VOID); 894 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 895 896 // FIXME: In other contexts we pretend this is a per-function property. 897 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 898 899 setSchedulingPreference(Sched::RegPressure); 900 } 901 902 const GCNSubtarget *SITargetLowering::getSubtarget() const { 903 return Subtarget; 904 } 905 906 //===----------------------------------------------------------------------===// 907 // TargetLowering queries 908 //===----------------------------------------------------------------------===// 909 910 // v_mad_mix* support a conversion from f16 to f32. 911 // 912 // There is only one special case when denormals are enabled we don't currently, 913 // where this is OK to use. 914 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 915 EVT DestVT, EVT SrcVT) const { 916 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 917 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 918 DestVT.getScalarType() == MVT::f32 && 919 SrcVT.getScalarType() == MVT::f16 && 920 // TODO: This probably only requires no input flushing? 921 !hasFP32Denormals(DAG.getMachineFunction()); 922 } 923 924 bool SITargetLowering::isFPExtFoldable(const MachineInstr &MI, unsigned Opcode, 925 LLT DestTy, LLT SrcTy) const { 926 return ((Opcode == TargetOpcode::G_FMAD && Subtarget->hasMadMixInsts()) || 927 (Opcode == TargetOpcode::G_FMA && Subtarget->hasFmaMixInsts())) && 928 DestTy.getScalarSizeInBits() == 32 && 929 SrcTy.getScalarSizeInBits() == 16 && 930 // TODO: This probably only requires no input flushing? 931 !hasFP32Denormals(*MI.getMF()); 932 } 933 934 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 935 // SI has some legal vector types, but no legal vector operations. Say no 936 // shuffles are legal in order to prefer scalarizing some vector operations. 937 return false; 938 } 939 940 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 941 CallingConv::ID CC, 942 EVT VT) const { 943 if (CC == CallingConv::AMDGPU_KERNEL) 944 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 945 946 if (VT.isVector()) { 947 EVT ScalarVT = VT.getScalarType(); 948 unsigned Size = ScalarVT.getSizeInBits(); 949 if (Size == 16) { 950 if (Subtarget->has16BitInsts()) 951 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 952 return VT.isInteger() ? MVT::i32 : MVT::f32; 953 } 954 955 if (Size < 16) 956 return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32; 957 return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32; 958 } 959 960 if (VT.getSizeInBits() > 32) 961 return MVT::i32; 962 963 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 964 } 965 966 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 967 CallingConv::ID CC, 968 EVT VT) const { 969 if (CC == CallingConv::AMDGPU_KERNEL) 970 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 971 972 if (VT.isVector()) { 973 unsigned NumElts = VT.getVectorNumElements(); 974 EVT ScalarVT = VT.getScalarType(); 975 unsigned Size = ScalarVT.getSizeInBits(); 976 977 // FIXME: Should probably promote 8-bit vectors to i16. 978 if (Size == 16 && Subtarget->has16BitInsts()) 979 return (NumElts + 1) / 2; 980 981 if (Size <= 32) 982 return NumElts; 983 984 if (Size > 32) 985 return NumElts * ((Size + 31) / 32); 986 } else if (VT.getSizeInBits() > 32) 987 return (VT.getSizeInBits() + 31) / 32; 988 989 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 990 } 991 992 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 993 LLVMContext &Context, CallingConv::ID CC, 994 EVT VT, EVT &IntermediateVT, 995 unsigned &NumIntermediates, MVT &RegisterVT) const { 996 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 997 unsigned NumElts = VT.getVectorNumElements(); 998 EVT ScalarVT = VT.getScalarType(); 999 unsigned Size = ScalarVT.getSizeInBits(); 1000 // FIXME: We should fix the ABI to be the same on targets without 16-bit 1001 // support, but unless we can properly handle 3-vectors, it will be still be 1002 // inconsistent. 1003 if (Size == 16 && Subtarget->has16BitInsts()) { 1004 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 1005 IntermediateVT = RegisterVT; 1006 NumIntermediates = (NumElts + 1) / 2; 1007 return NumIntermediates; 1008 } 1009 1010 if (Size == 32) { 1011 RegisterVT = ScalarVT.getSimpleVT(); 1012 IntermediateVT = RegisterVT; 1013 NumIntermediates = NumElts; 1014 return NumIntermediates; 1015 } 1016 1017 if (Size < 16 && Subtarget->has16BitInsts()) { 1018 // FIXME: Should probably form v2i16 pieces 1019 RegisterVT = MVT::i16; 1020 IntermediateVT = ScalarVT; 1021 NumIntermediates = NumElts; 1022 return NumIntermediates; 1023 } 1024 1025 1026 if (Size != 16 && Size <= 32) { 1027 RegisterVT = MVT::i32; 1028 IntermediateVT = ScalarVT; 1029 NumIntermediates = NumElts; 1030 return NumIntermediates; 1031 } 1032 1033 if (Size > 32) { 1034 RegisterVT = MVT::i32; 1035 IntermediateVT = RegisterVT; 1036 NumIntermediates = NumElts * ((Size + 31) / 32); 1037 return NumIntermediates; 1038 } 1039 } 1040 1041 return TargetLowering::getVectorTypeBreakdownForCallingConv( 1042 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 1043 } 1044 1045 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 1046 assert(DMaskLanes != 0); 1047 1048 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 1049 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 1050 return EVT::getVectorVT(Ty->getContext(), 1051 EVT::getEVT(VT->getElementType()), 1052 NumElts); 1053 } 1054 1055 return EVT::getEVT(Ty); 1056 } 1057 1058 // Peek through TFE struct returns to only use the data size. 1059 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 1060 auto *ST = dyn_cast<StructType>(Ty); 1061 if (!ST) 1062 return memVTFromImageData(Ty, DMaskLanes); 1063 1064 // Some intrinsics return an aggregate type - special case to work out the 1065 // correct memVT. 1066 // 1067 // Only limited forms of aggregate type currently expected. 1068 if (ST->getNumContainedTypes() != 2 || 1069 !ST->getContainedType(1)->isIntegerTy(32)) 1070 return EVT(); 1071 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 1072 } 1073 1074 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1075 const CallInst &CI, 1076 MachineFunction &MF, 1077 unsigned IntrID) const { 1078 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 1079 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 1080 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 1081 (Intrinsic::ID)IntrID); 1082 if (Attr.hasFnAttr(Attribute::ReadNone)) 1083 return false; 1084 1085 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1086 1087 if (RsrcIntr->IsImage) { 1088 Info.ptrVal = 1089 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1090 Info.align.reset(); 1091 } else { 1092 Info.ptrVal = 1093 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1094 } 1095 1096 Info.flags = MachineMemOperand::MODereferenceable; 1097 if (Attr.hasFnAttr(Attribute::ReadOnly)) { 1098 unsigned DMaskLanes = 4; 1099 1100 if (RsrcIntr->IsImage) { 1101 const AMDGPU::ImageDimIntrinsicInfo *Intr 1102 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 1103 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1104 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1105 1106 if (!BaseOpcode->Gather4) { 1107 // If this isn't a gather, we may have excess loaded elements in the 1108 // IR type. Check the dmask for the real number of elements loaded. 1109 unsigned DMask 1110 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1111 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1112 } 1113 1114 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1115 } else 1116 Info.memVT = EVT::getEVT(CI.getType()); 1117 1118 // FIXME: What does alignment mean for an image? 1119 Info.opc = ISD::INTRINSIC_W_CHAIN; 1120 Info.flags |= MachineMemOperand::MOLoad; 1121 } else if (Attr.hasFnAttr(Attribute::WriteOnly)) { 1122 Info.opc = ISD::INTRINSIC_VOID; 1123 1124 Type *DataTy = CI.getArgOperand(0)->getType(); 1125 if (RsrcIntr->IsImage) { 1126 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1127 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1128 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1129 } else 1130 Info.memVT = EVT::getEVT(DataTy); 1131 1132 Info.flags |= MachineMemOperand::MOStore; 1133 } else { 1134 // Atomic 1135 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID : 1136 ISD::INTRINSIC_W_CHAIN; 1137 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 1138 Info.flags = MachineMemOperand::MOLoad | 1139 MachineMemOperand::MOStore | 1140 MachineMemOperand::MODereferenceable; 1141 1142 // XXX - Should this be volatile without known ordering? 1143 Info.flags |= MachineMemOperand::MOVolatile; 1144 } 1145 return true; 1146 } 1147 1148 switch (IntrID) { 1149 case Intrinsic::amdgcn_atomic_inc: 1150 case Intrinsic::amdgcn_atomic_dec: 1151 case Intrinsic::amdgcn_ds_ordered_add: 1152 case Intrinsic::amdgcn_ds_ordered_swap: 1153 case Intrinsic::amdgcn_ds_fadd: 1154 case Intrinsic::amdgcn_ds_fmin: 1155 case Intrinsic::amdgcn_ds_fmax: { 1156 Info.opc = ISD::INTRINSIC_W_CHAIN; 1157 Info.memVT = MVT::getVT(CI.getType()); 1158 Info.ptrVal = CI.getOperand(0); 1159 Info.align.reset(); 1160 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1161 1162 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1163 if (!Vol->isZero()) 1164 Info.flags |= MachineMemOperand::MOVolatile; 1165 1166 return true; 1167 } 1168 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1169 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1170 1171 Info.opc = ISD::INTRINSIC_W_CHAIN; 1172 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1173 Info.ptrVal = 1174 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1175 Info.align.reset(); 1176 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1177 1178 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1179 if (!Vol || !Vol->isZero()) 1180 Info.flags |= MachineMemOperand::MOVolatile; 1181 1182 return true; 1183 } 1184 case Intrinsic::amdgcn_ds_append: 1185 case Intrinsic::amdgcn_ds_consume: { 1186 Info.opc = ISD::INTRINSIC_W_CHAIN; 1187 Info.memVT = MVT::getVT(CI.getType()); 1188 Info.ptrVal = CI.getOperand(0); 1189 Info.align.reset(); 1190 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1191 1192 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1193 if (!Vol->isZero()) 1194 Info.flags |= MachineMemOperand::MOVolatile; 1195 1196 return true; 1197 } 1198 case Intrinsic::amdgcn_global_atomic_csub: { 1199 Info.opc = ISD::INTRINSIC_W_CHAIN; 1200 Info.memVT = MVT::getVT(CI.getType()); 1201 Info.ptrVal = CI.getOperand(0); 1202 Info.align.reset(); 1203 Info.flags = MachineMemOperand::MOLoad | 1204 MachineMemOperand::MOStore | 1205 MachineMemOperand::MOVolatile; 1206 return true; 1207 } 1208 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 1209 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1210 Info.opc = ISD::INTRINSIC_W_CHAIN; 1211 Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT? 1212 Info.ptrVal = 1213 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1214 Info.align.reset(); 1215 Info.flags = MachineMemOperand::MOLoad | 1216 MachineMemOperand::MODereferenceable; 1217 return true; 1218 } 1219 case Intrinsic::amdgcn_global_atomic_fadd: 1220 case Intrinsic::amdgcn_global_atomic_fmin: 1221 case Intrinsic::amdgcn_global_atomic_fmax: 1222 case Intrinsic::amdgcn_flat_atomic_fadd: 1223 case Intrinsic::amdgcn_flat_atomic_fmin: 1224 case Intrinsic::amdgcn_flat_atomic_fmax: { 1225 Info.opc = ISD::INTRINSIC_W_CHAIN; 1226 Info.memVT = MVT::getVT(CI.getType()); 1227 Info.ptrVal = CI.getOperand(0); 1228 Info.align.reset(); 1229 Info.flags = MachineMemOperand::MOLoad | 1230 MachineMemOperand::MOStore | 1231 MachineMemOperand::MODereferenceable | 1232 MachineMemOperand::MOVolatile; 1233 return true; 1234 } 1235 case Intrinsic::amdgcn_ds_gws_init: 1236 case Intrinsic::amdgcn_ds_gws_barrier: 1237 case Intrinsic::amdgcn_ds_gws_sema_v: 1238 case Intrinsic::amdgcn_ds_gws_sema_br: 1239 case Intrinsic::amdgcn_ds_gws_sema_p: 1240 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1241 Info.opc = ISD::INTRINSIC_VOID; 1242 1243 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1244 Info.ptrVal = 1245 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1246 1247 // This is an abstract access, but we need to specify a type and size. 1248 Info.memVT = MVT::i32; 1249 Info.size = 4; 1250 Info.align = Align(4); 1251 1252 Info.flags = MachineMemOperand::MOStore; 1253 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1254 Info.flags = MachineMemOperand::MOLoad; 1255 return true; 1256 } 1257 default: 1258 return false; 1259 } 1260 } 1261 1262 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1263 SmallVectorImpl<Value*> &Ops, 1264 Type *&AccessTy) const { 1265 switch (II->getIntrinsicID()) { 1266 case Intrinsic::amdgcn_atomic_inc: 1267 case Intrinsic::amdgcn_atomic_dec: 1268 case Intrinsic::amdgcn_ds_ordered_add: 1269 case Intrinsic::amdgcn_ds_ordered_swap: 1270 case Intrinsic::amdgcn_ds_append: 1271 case Intrinsic::amdgcn_ds_consume: 1272 case Intrinsic::amdgcn_ds_fadd: 1273 case Intrinsic::amdgcn_ds_fmin: 1274 case Intrinsic::amdgcn_ds_fmax: 1275 case Intrinsic::amdgcn_global_atomic_fadd: 1276 case Intrinsic::amdgcn_flat_atomic_fadd: 1277 case Intrinsic::amdgcn_flat_atomic_fmin: 1278 case Intrinsic::amdgcn_flat_atomic_fmax: 1279 case Intrinsic::amdgcn_global_atomic_csub: { 1280 Value *Ptr = II->getArgOperand(0); 1281 AccessTy = II->getType(); 1282 Ops.push_back(Ptr); 1283 return true; 1284 } 1285 default: 1286 return false; 1287 } 1288 } 1289 1290 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1291 if (!Subtarget->hasFlatInstOffsets()) { 1292 // Flat instructions do not have offsets, and only have the register 1293 // address. 1294 return AM.BaseOffs == 0 && AM.Scale == 0; 1295 } 1296 1297 return AM.Scale == 0 && 1298 (AM.BaseOffs == 0 || 1299 Subtarget->getInstrInfo()->isLegalFLATOffset( 1300 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT)); 1301 } 1302 1303 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1304 if (Subtarget->hasFlatGlobalInsts()) 1305 return AM.Scale == 0 && 1306 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1307 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1308 SIInstrFlags::FlatGlobal)); 1309 1310 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1311 // Assume the we will use FLAT for all global memory accesses 1312 // on VI. 1313 // FIXME: This assumption is currently wrong. On VI we still use 1314 // MUBUF instructions for the r + i addressing mode. As currently 1315 // implemented, the MUBUF instructions only work on buffer < 4GB. 1316 // It may be possible to support > 4GB buffers with MUBUF instructions, 1317 // by setting the stride value in the resource descriptor which would 1318 // increase the size limit to (stride * 4GB). However, this is risky, 1319 // because it has never been validated. 1320 return isLegalFlatAddressingMode(AM); 1321 } 1322 1323 return isLegalMUBUFAddressingMode(AM); 1324 } 1325 1326 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1327 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1328 // additionally can do r + r + i with addr64. 32-bit has more addressing 1329 // mode options. Depending on the resource constant, it can also do 1330 // (i64 r0) + (i32 r1) * (i14 i). 1331 // 1332 // Private arrays end up using a scratch buffer most of the time, so also 1333 // assume those use MUBUF instructions. Scratch loads / stores are currently 1334 // implemented as mubuf instructions with offen bit set, so slightly 1335 // different than the normal addr64. 1336 if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs)) 1337 return false; 1338 1339 // FIXME: Since we can split immediate into soffset and immediate offset, 1340 // would it make sense to allow any immediate? 1341 1342 switch (AM.Scale) { 1343 case 0: // r + i or just i, depending on HasBaseReg. 1344 return true; 1345 case 1: 1346 return true; // We have r + r or r + i. 1347 case 2: 1348 if (AM.HasBaseReg) { 1349 // Reject 2 * r + r. 1350 return false; 1351 } 1352 1353 // Allow 2 * r as r + r 1354 // Or 2 * r + i is allowed as r + r + i. 1355 return true; 1356 default: // Don't allow n * r 1357 return false; 1358 } 1359 } 1360 1361 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1362 const AddrMode &AM, Type *Ty, 1363 unsigned AS, Instruction *I) const { 1364 // No global is ever allowed as a base. 1365 if (AM.BaseGV) 1366 return false; 1367 1368 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1369 return isLegalGlobalAddressingMode(AM); 1370 1371 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1372 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1373 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1374 // If the offset isn't a multiple of 4, it probably isn't going to be 1375 // correctly aligned. 1376 // FIXME: Can we get the real alignment here? 1377 if (AM.BaseOffs % 4 != 0) 1378 return isLegalMUBUFAddressingMode(AM); 1379 1380 // There are no SMRD extloads, so if we have to do a small type access we 1381 // will use a MUBUF load. 1382 // FIXME?: We also need to do this if unaligned, but we don't know the 1383 // alignment here. 1384 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1385 return isLegalGlobalAddressingMode(AM); 1386 1387 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1388 // SMRD instructions have an 8-bit, dword offset on SI. 1389 if (!isUInt<8>(AM.BaseOffs / 4)) 1390 return false; 1391 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1392 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1393 // in 8-bits, it can use a smaller encoding. 1394 if (!isUInt<32>(AM.BaseOffs / 4)) 1395 return false; 1396 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1397 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1398 if (!isUInt<20>(AM.BaseOffs)) 1399 return false; 1400 } else 1401 llvm_unreachable("unhandled generation"); 1402 1403 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1404 return true; 1405 1406 if (AM.Scale == 1 && AM.HasBaseReg) 1407 return true; 1408 1409 return false; 1410 1411 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1412 return isLegalMUBUFAddressingMode(AM); 1413 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1414 AS == AMDGPUAS::REGION_ADDRESS) { 1415 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1416 // field. 1417 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1418 // an 8-bit dword offset but we don't know the alignment here. 1419 if (!isUInt<16>(AM.BaseOffs)) 1420 return false; 1421 1422 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1423 return true; 1424 1425 if (AM.Scale == 1 && AM.HasBaseReg) 1426 return true; 1427 1428 return false; 1429 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1430 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1431 // For an unknown address space, this usually means that this is for some 1432 // reason being used for pure arithmetic, and not based on some addressing 1433 // computation. We don't have instructions that compute pointers with any 1434 // addressing modes, so treat them as having no offset like flat 1435 // instructions. 1436 return isLegalFlatAddressingMode(AM); 1437 } 1438 1439 // Assume a user alias of global for unknown address spaces. 1440 return isLegalGlobalAddressingMode(AM); 1441 } 1442 1443 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1444 const MachineFunction &MF) const { 1445 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1446 return (MemVT.getSizeInBits() <= 4 * 32); 1447 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1448 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1449 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1450 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1451 return (MemVT.getSizeInBits() <= 2 * 32); 1452 } 1453 return true; 1454 } 1455 1456 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1457 unsigned Size, unsigned AddrSpace, Align Alignment, 1458 MachineMemOperand::Flags Flags, bool *IsFast) const { 1459 if (IsFast) 1460 *IsFast = false; 1461 1462 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1463 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1464 // Check if alignment requirements for ds_read/write instructions are 1465 // disabled. 1466 if (Subtarget->hasUnalignedDSAccessEnabled() && 1467 !Subtarget->hasLDSMisalignedBug()) { 1468 if (IsFast) 1469 *IsFast = Alignment != Align(2); 1470 return true; 1471 } 1472 1473 // Either, the alignment requirements are "enabled", or there is an 1474 // unaligned LDS access related hardware bug though alignment requirements 1475 // are "disabled". In either case, we need to check for proper alignment 1476 // requirements. 1477 // 1478 if (Size == 64) { 1479 // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we 1480 // can do a 4 byte aligned, 8 byte access in a single operation using 1481 // ds_read2/write2_b32 with adjacent offsets. 1482 bool AlignedBy4 = Alignment >= Align(4); 1483 if (IsFast) 1484 *IsFast = AlignedBy4; 1485 1486 return AlignedBy4; 1487 } 1488 if (Size == 96) { 1489 // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on 1490 // gfx8 and older. 1491 bool AlignedBy16 = Alignment >= Align(16); 1492 if (IsFast) 1493 *IsFast = AlignedBy16; 1494 1495 return AlignedBy16; 1496 } 1497 if (Size == 128) { 1498 // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on 1499 // gfx8 and older, but we can do a 8 byte aligned, 16 byte access in a 1500 // single operation using ds_read2/write2_b64. 1501 bool AlignedBy8 = Alignment >= Align(8); 1502 if (IsFast) 1503 *IsFast = AlignedBy8; 1504 1505 return AlignedBy8; 1506 } 1507 } 1508 1509 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) { 1510 bool AlignedBy4 = Alignment >= Align(4); 1511 if (IsFast) 1512 *IsFast = AlignedBy4; 1513 1514 return AlignedBy4 || 1515 Subtarget->enableFlatScratch() || 1516 Subtarget->hasUnalignedScratchAccess(); 1517 } 1518 1519 // FIXME: We have to be conservative here and assume that flat operations 1520 // will access scratch. If we had access to the IR function, then we 1521 // could determine if any private memory was used in the function. 1522 if (AddrSpace == AMDGPUAS::FLAT_ADDRESS && 1523 !Subtarget->hasUnalignedScratchAccess()) { 1524 bool AlignedBy4 = Alignment >= Align(4); 1525 if (IsFast) 1526 *IsFast = AlignedBy4; 1527 1528 return AlignedBy4; 1529 } 1530 1531 if (Subtarget->hasUnalignedBufferAccessEnabled() && 1532 !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1533 AddrSpace == AMDGPUAS::REGION_ADDRESS)) { 1534 // If we have an uniform constant load, it still requires using a slow 1535 // buffer instruction if unaligned. 1536 if (IsFast) { 1537 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1538 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1539 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1540 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1541 Alignment >= Align(4) : Alignment != Align(2); 1542 } 1543 1544 return true; 1545 } 1546 1547 // Smaller than dword value must be aligned. 1548 if (Size < 32) 1549 return false; 1550 1551 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1552 // byte-address are ignored, thus forcing Dword alignment. 1553 // This applies to private, global, and constant memory. 1554 if (IsFast) 1555 *IsFast = true; 1556 1557 return Size >= 32 && Alignment >= Align(4); 1558 } 1559 1560 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1561 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 1562 bool *IsFast) const { 1563 if (IsFast) 1564 *IsFast = false; 1565 1566 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1567 // which isn't a simple VT. 1568 // Until MVT is extended to handle this, simply check for the size and 1569 // rely on the condition below: allow accesses if the size is a multiple of 4. 1570 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1571 VT.getStoreSize() > 16)) { 1572 return false; 1573 } 1574 1575 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1576 Alignment, Flags, IsFast); 1577 } 1578 1579 EVT SITargetLowering::getOptimalMemOpType( 1580 const MemOp &Op, const AttributeList &FuncAttributes) const { 1581 // FIXME: Should account for address space here. 1582 1583 // The default fallback uses the private pointer size as a guess for a type to 1584 // use. Make sure we switch these to 64-bit accesses. 1585 1586 if (Op.size() >= 16 && 1587 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1588 return MVT::v4i32; 1589 1590 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1591 return MVT::v2i32; 1592 1593 // Use the default. 1594 return MVT::Other; 1595 } 1596 1597 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1598 const MemSDNode *MemNode = cast<MemSDNode>(N); 1599 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1600 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1601 return I && I->getMetadata("amdgpu.noclobber"); 1602 } 1603 1604 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) { 1605 return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS || 1606 AS == AMDGPUAS::PRIVATE_ADDRESS; 1607 } 1608 1609 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1610 unsigned DestAS) const { 1611 // Flat -> private/local is a simple truncate. 1612 // Flat -> global is no-op 1613 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1614 return true; 1615 1616 const GCNTargetMachine &TM = 1617 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1618 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 1619 } 1620 1621 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1622 const MemSDNode *MemNode = cast<MemSDNode>(N); 1623 1624 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1625 } 1626 1627 TargetLoweringBase::LegalizeTypeAction 1628 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1629 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 && 1630 VT.getScalarType().bitsLE(MVT::i16)) 1631 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1632 return TargetLoweringBase::getPreferredVectorAction(VT); 1633 } 1634 1635 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1636 Type *Ty) const { 1637 // FIXME: Could be smarter if called for vector constants. 1638 return true; 1639 } 1640 1641 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1642 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1643 switch (Op) { 1644 case ISD::LOAD: 1645 case ISD::STORE: 1646 1647 // These operations are done with 32-bit instructions anyway. 1648 case ISD::AND: 1649 case ISD::OR: 1650 case ISD::XOR: 1651 case ISD::SELECT: 1652 // TODO: Extensions? 1653 return true; 1654 default: 1655 return false; 1656 } 1657 } 1658 1659 // SimplifySetCC uses this function to determine whether or not it should 1660 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1661 if (VT == MVT::i1 && Op == ISD::SETCC) 1662 return false; 1663 1664 return TargetLowering::isTypeDesirableForOp(Op, VT); 1665 } 1666 1667 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1668 const SDLoc &SL, 1669 SDValue Chain, 1670 uint64_t Offset) const { 1671 const DataLayout &DL = DAG.getDataLayout(); 1672 MachineFunction &MF = DAG.getMachineFunction(); 1673 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1674 1675 const ArgDescriptor *InputPtrReg; 1676 const TargetRegisterClass *RC; 1677 LLT ArgTy; 1678 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1679 1680 std::tie(InputPtrReg, RC, ArgTy) = 1681 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1682 1683 // We may not have the kernarg segment argument if we have no kernel 1684 // arguments. 1685 if (!InputPtrReg) 1686 return DAG.getConstant(0, SL, PtrVT); 1687 1688 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1689 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1690 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1691 1692 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset)); 1693 } 1694 1695 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1696 const SDLoc &SL) const { 1697 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1698 FIRST_IMPLICIT); 1699 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1700 } 1701 1702 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1703 const SDLoc &SL, SDValue Val, 1704 bool Signed, 1705 const ISD::InputArg *Arg) const { 1706 // First, if it is a widened vector, narrow it. 1707 if (VT.isVector() && 1708 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1709 EVT NarrowedVT = 1710 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1711 VT.getVectorNumElements()); 1712 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1713 DAG.getConstant(0, SL, MVT::i32)); 1714 } 1715 1716 // Then convert the vector elements or scalar value. 1717 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1718 VT.bitsLT(MemVT)) { 1719 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1720 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1721 } 1722 1723 if (MemVT.isFloatingPoint()) 1724 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1725 else if (Signed) 1726 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1727 else 1728 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1729 1730 return Val; 1731 } 1732 1733 SDValue SITargetLowering::lowerKernargMemParameter( 1734 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1735 uint64_t Offset, Align Alignment, bool Signed, 1736 const ISD::InputArg *Arg) const { 1737 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1738 1739 // Try to avoid using an extload by loading earlier than the argument address, 1740 // and extracting the relevant bits. The load should hopefully be merged with 1741 // the previous argument. 1742 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1743 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1744 int64_t AlignDownOffset = alignDown(Offset, 4); 1745 int64_t OffsetDiff = Offset - AlignDownOffset; 1746 1747 EVT IntVT = MemVT.changeTypeToInteger(); 1748 1749 // TODO: If we passed in the base kernel offset we could have a better 1750 // alignment than 4, but we don't really need it. 1751 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1752 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4), 1753 MachineMemOperand::MODereferenceable | 1754 MachineMemOperand::MOInvariant); 1755 1756 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1757 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1758 1759 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1760 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1761 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1762 1763 1764 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1765 } 1766 1767 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1768 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1769 MachineMemOperand::MODereferenceable | 1770 MachineMemOperand::MOInvariant); 1771 1772 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1773 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1774 } 1775 1776 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1777 const SDLoc &SL, SDValue Chain, 1778 const ISD::InputArg &Arg) const { 1779 MachineFunction &MF = DAG.getMachineFunction(); 1780 MachineFrameInfo &MFI = MF.getFrameInfo(); 1781 1782 if (Arg.Flags.isByVal()) { 1783 unsigned Size = Arg.Flags.getByValSize(); 1784 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1785 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1786 } 1787 1788 unsigned ArgOffset = VA.getLocMemOffset(); 1789 unsigned ArgSize = VA.getValVT().getStoreSize(); 1790 1791 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1792 1793 // Create load nodes to retrieve arguments from the stack. 1794 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1795 SDValue ArgValue; 1796 1797 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1798 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1799 MVT MemVT = VA.getValVT(); 1800 1801 switch (VA.getLocInfo()) { 1802 default: 1803 break; 1804 case CCValAssign::BCvt: 1805 MemVT = VA.getLocVT(); 1806 break; 1807 case CCValAssign::SExt: 1808 ExtType = ISD::SEXTLOAD; 1809 break; 1810 case CCValAssign::ZExt: 1811 ExtType = ISD::ZEXTLOAD; 1812 break; 1813 case CCValAssign::AExt: 1814 ExtType = ISD::EXTLOAD; 1815 break; 1816 } 1817 1818 ArgValue = DAG.getExtLoad( 1819 ExtType, SL, VA.getLocVT(), Chain, FIN, 1820 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1821 MemVT); 1822 return ArgValue; 1823 } 1824 1825 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1826 const SIMachineFunctionInfo &MFI, 1827 EVT VT, 1828 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1829 const ArgDescriptor *Reg; 1830 const TargetRegisterClass *RC; 1831 LLT Ty; 1832 1833 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1834 if (!Reg) { 1835 if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) { 1836 // It's possible for a kernarg intrinsic call to appear in a kernel with 1837 // no allocated segment, in which case we do not add the user sgpr 1838 // argument, so just return null. 1839 return DAG.getConstant(0, SDLoc(), VT); 1840 } 1841 1842 // It's undefined behavior if a function marked with the amdgpu-no-* 1843 // attributes uses the corresponding intrinsic. 1844 return DAG.getUNDEF(VT); 1845 } 1846 1847 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1848 } 1849 1850 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1851 CallingConv::ID CallConv, 1852 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped, 1853 FunctionType *FType, 1854 SIMachineFunctionInfo *Info) { 1855 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1856 const ISD::InputArg *Arg = &Ins[I]; 1857 1858 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1859 "vector type argument should have been split"); 1860 1861 // First check if it's a PS input addr. 1862 if (CallConv == CallingConv::AMDGPU_PS && 1863 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1864 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1865 1866 // Inconveniently only the first part of the split is marked as isSplit, 1867 // so skip to the end. We only want to increment PSInputNum once for the 1868 // entire split argument. 1869 if (Arg->Flags.isSplit()) { 1870 while (!Arg->Flags.isSplitEnd()) { 1871 assert((!Arg->VT.isVector() || 1872 Arg->VT.getScalarSizeInBits() == 16) && 1873 "unexpected vector split in ps argument type"); 1874 if (!SkipArg) 1875 Splits.push_back(*Arg); 1876 Arg = &Ins[++I]; 1877 } 1878 } 1879 1880 if (SkipArg) { 1881 // We can safely skip PS inputs. 1882 Skipped.set(Arg->getOrigArgIndex()); 1883 ++PSInputNum; 1884 continue; 1885 } 1886 1887 Info->markPSInputAllocated(PSInputNum); 1888 if (Arg->Used) 1889 Info->markPSInputEnabled(PSInputNum); 1890 1891 ++PSInputNum; 1892 } 1893 1894 Splits.push_back(*Arg); 1895 } 1896 } 1897 1898 // Allocate special inputs passed in VGPRs. 1899 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1900 MachineFunction &MF, 1901 const SIRegisterInfo &TRI, 1902 SIMachineFunctionInfo &Info) const { 1903 const LLT S32 = LLT::scalar(32); 1904 MachineRegisterInfo &MRI = MF.getRegInfo(); 1905 1906 if (Info.hasWorkItemIDX()) { 1907 Register Reg = AMDGPU::VGPR0; 1908 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1909 1910 CCInfo.AllocateReg(Reg); 1911 unsigned Mask = (Subtarget->hasPackedTID() && 1912 Info.hasWorkItemIDY()) ? 0x3ff : ~0u; 1913 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1914 } 1915 1916 if (Info.hasWorkItemIDY()) { 1917 assert(Info.hasWorkItemIDX()); 1918 if (Subtarget->hasPackedTID()) { 1919 Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1920 0x3ff << 10)); 1921 } else { 1922 unsigned Reg = AMDGPU::VGPR1; 1923 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1924 1925 CCInfo.AllocateReg(Reg); 1926 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1927 } 1928 } 1929 1930 if (Info.hasWorkItemIDZ()) { 1931 assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY()); 1932 if (Subtarget->hasPackedTID()) { 1933 Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1934 0x3ff << 20)); 1935 } else { 1936 unsigned Reg = AMDGPU::VGPR2; 1937 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1938 1939 CCInfo.AllocateReg(Reg); 1940 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1941 } 1942 } 1943 } 1944 1945 // Try to allocate a VGPR at the end of the argument list, or if no argument 1946 // VGPRs are left allocating a stack slot. 1947 // If \p Mask is is given it indicates bitfield position in the register. 1948 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1949 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1950 ArgDescriptor Arg = ArgDescriptor()) { 1951 if (Arg.isSet()) 1952 return ArgDescriptor::createArg(Arg, Mask); 1953 1954 ArrayRef<MCPhysReg> ArgVGPRs 1955 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1956 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1957 if (RegIdx == ArgVGPRs.size()) { 1958 // Spill to stack required. 1959 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 1960 1961 return ArgDescriptor::createStack(Offset, Mask); 1962 } 1963 1964 unsigned Reg = ArgVGPRs[RegIdx]; 1965 Reg = CCInfo.AllocateReg(Reg); 1966 assert(Reg != AMDGPU::NoRegister); 1967 1968 MachineFunction &MF = CCInfo.getMachineFunction(); 1969 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1970 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1971 return ArgDescriptor::createRegister(Reg, Mask); 1972 } 1973 1974 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1975 const TargetRegisterClass *RC, 1976 unsigned NumArgRegs) { 1977 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1978 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1979 if (RegIdx == ArgSGPRs.size()) 1980 report_fatal_error("ran out of SGPRs for arguments"); 1981 1982 unsigned Reg = ArgSGPRs[RegIdx]; 1983 Reg = CCInfo.AllocateReg(Reg); 1984 assert(Reg != AMDGPU::NoRegister); 1985 1986 MachineFunction &MF = CCInfo.getMachineFunction(); 1987 MF.addLiveIn(Reg, RC); 1988 return ArgDescriptor::createRegister(Reg); 1989 } 1990 1991 // If this has a fixed position, we still should allocate the register in the 1992 // CCInfo state. Technically we could get away with this for values passed 1993 // outside of the normal argument range. 1994 static void allocateFixedSGPRInputImpl(CCState &CCInfo, 1995 const TargetRegisterClass *RC, 1996 MCRegister Reg) { 1997 Reg = CCInfo.AllocateReg(Reg); 1998 assert(Reg != AMDGPU::NoRegister); 1999 MachineFunction &MF = CCInfo.getMachineFunction(); 2000 MF.addLiveIn(Reg, RC); 2001 } 2002 2003 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) { 2004 if (Arg) { 2005 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 2006 Arg.getRegister()); 2007 } else 2008 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 2009 } 2010 2011 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) { 2012 if (Arg) { 2013 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 2014 Arg.getRegister()); 2015 } else 2016 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 2017 } 2018 2019 /// Allocate implicit function VGPR arguments at the end of allocated user 2020 /// arguments. 2021 void SITargetLowering::allocateSpecialInputVGPRs( 2022 CCState &CCInfo, MachineFunction &MF, 2023 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 2024 const unsigned Mask = 0x3ff; 2025 ArgDescriptor Arg; 2026 2027 if (Info.hasWorkItemIDX()) { 2028 Arg = allocateVGPR32Input(CCInfo, Mask); 2029 Info.setWorkItemIDX(Arg); 2030 } 2031 2032 if (Info.hasWorkItemIDY()) { 2033 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 2034 Info.setWorkItemIDY(Arg); 2035 } 2036 2037 if (Info.hasWorkItemIDZ()) 2038 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 2039 } 2040 2041 /// Allocate implicit function VGPR arguments in fixed registers. 2042 void SITargetLowering::allocateSpecialInputVGPRsFixed( 2043 CCState &CCInfo, MachineFunction &MF, 2044 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 2045 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 2046 if (!Reg) 2047 report_fatal_error("failed to allocated VGPR for implicit arguments"); 2048 2049 const unsigned Mask = 0x3ff; 2050 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 2051 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 2052 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 2053 } 2054 2055 void SITargetLowering::allocateSpecialInputSGPRs( 2056 CCState &CCInfo, 2057 MachineFunction &MF, 2058 const SIRegisterInfo &TRI, 2059 SIMachineFunctionInfo &Info) const { 2060 auto &ArgInfo = Info.getArgInfo(); 2061 2062 // TODO: Unify handling with private memory pointers. 2063 if (Info.hasDispatchPtr()) 2064 allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr); 2065 2066 if (Info.hasQueuePtr()) 2067 allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr); 2068 2069 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 2070 // constant offset from the kernarg segment. 2071 if (Info.hasImplicitArgPtr()) 2072 allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr); 2073 2074 if (Info.hasDispatchID()) 2075 allocateSGPR64Input(CCInfo, ArgInfo.DispatchID); 2076 2077 // flat_scratch_init is not applicable for non-kernel functions. 2078 2079 if (Info.hasWorkGroupIDX()) 2080 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX); 2081 2082 if (Info.hasWorkGroupIDY()) 2083 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY); 2084 2085 if (Info.hasWorkGroupIDZ()) 2086 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ); 2087 } 2088 2089 // Allocate special inputs passed in user SGPRs. 2090 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 2091 MachineFunction &MF, 2092 const SIRegisterInfo &TRI, 2093 SIMachineFunctionInfo &Info) const { 2094 if (Info.hasImplicitBufferPtr()) { 2095 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 2096 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 2097 CCInfo.AllocateReg(ImplicitBufferPtrReg); 2098 } 2099 2100 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 2101 if (Info.hasPrivateSegmentBuffer()) { 2102 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 2103 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 2104 CCInfo.AllocateReg(PrivateSegmentBufferReg); 2105 } 2106 2107 if (Info.hasDispatchPtr()) { 2108 Register DispatchPtrReg = Info.addDispatchPtr(TRI); 2109 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 2110 CCInfo.AllocateReg(DispatchPtrReg); 2111 } 2112 2113 if (Info.hasQueuePtr()) { 2114 Register QueuePtrReg = Info.addQueuePtr(TRI); 2115 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 2116 CCInfo.AllocateReg(QueuePtrReg); 2117 } 2118 2119 if (Info.hasKernargSegmentPtr()) { 2120 MachineRegisterInfo &MRI = MF.getRegInfo(); 2121 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 2122 CCInfo.AllocateReg(InputPtrReg); 2123 2124 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 2125 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 2126 } 2127 2128 if (Info.hasDispatchID()) { 2129 Register DispatchIDReg = Info.addDispatchID(TRI); 2130 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 2131 CCInfo.AllocateReg(DispatchIDReg); 2132 } 2133 2134 if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) { 2135 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI); 2136 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 2137 CCInfo.AllocateReg(FlatScratchInitReg); 2138 } 2139 2140 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 2141 // these from the dispatch pointer. 2142 } 2143 2144 // Allocate special input registers that are initialized per-wave. 2145 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 2146 MachineFunction &MF, 2147 SIMachineFunctionInfo &Info, 2148 CallingConv::ID CallConv, 2149 bool IsShader) const { 2150 if (Info.hasWorkGroupIDX()) { 2151 Register Reg = Info.addWorkGroupIDX(); 2152 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2153 CCInfo.AllocateReg(Reg); 2154 } 2155 2156 if (Info.hasWorkGroupIDY()) { 2157 Register Reg = Info.addWorkGroupIDY(); 2158 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2159 CCInfo.AllocateReg(Reg); 2160 } 2161 2162 if (Info.hasWorkGroupIDZ()) { 2163 Register Reg = Info.addWorkGroupIDZ(); 2164 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2165 CCInfo.AllocateReg(Reg); 2166 } 2167 2168 if (Info.hasWorkGroupInfo()) { 2169 Register Reg = Info.addWorkGroupInfo(); 2170 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2171 CCInfo.AllocateReg(Reg); 2172 } 2173 2174 if (Info.hasPrivateSegmentWaveByteOffset()) { 2175 // Scratch wave offset passed in system SGPR. 2176 unsigned PrivateSegmentWaveByteOffsetReg; 2177 2178 if (IsShader) { 2179 PrivateSegmentWaveByteOffsetReg = 2180 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 2181 2182 // This is true if the scratch wave byte offset doesn't have a fixed 2183 // location. 2184 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 2185 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 2186 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 2187 } 2188 } else 2189 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 2190 2191 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 2192 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 2193 } 2194 } 2195 2196 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2197 MachineFunction &MF, 2198 const SIRegisterInfo &TRI, 2199 SIMachineFunctionInfo &Info) { 2200 // Now that we've figured out where the scratch register inputs are, see if 2201 // should reserve the arguments and use them directly. 2202 MachineFrameInfo &MFI = MF.getFrameInfo(); 2203 bool HasStackObjects = MFI.hasStackObjects(); 2204 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2205 2206 // Record that we know we have non-spill stack objects so we don't need to 2207 // check all stack objects later. 2208 if (HasStackObjects) 2209 Info.setHasNonSpillStackObjects(true); 2210 2211 // Everything live out of a block is spilled with fast regalloc, so it's 2212 // almost certain that spilling will be required. 2213 if (TM.getOptLevel() == CodeGenOpt::None) 2214 HasStackObjects = true; 2215 2216 // For now assume stack access is needed in any callee functions, so we need 2217 // the scratch registers to pass in. 2218 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2219 2220 if (!ST.enableFlatScratch()) { 2221 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2222 // If we have stack objects, we unquestionably need the private buffer 2223 // resource. For the Code Object V2 ABI, this will be the first 4 user 2224 // SGPR inputs. We can reserve those and use them directly. 2225 2226 Register PrivateSegmentBufferReg = 2227 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2228 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2229 } else { 2230 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2231 // We tentatively reserve the last registers (skipping the last registers 2232 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2233 // we'll replace these with the ones immediately after those which were 2234 // really allocated. In the prologue copies will be inserted from the 2235 // argument to these reserved registers. 2236 2237 // Without HSA, relocations are used for the scratch pointer and the 2238 // buffer resource setup is always inserted in the prologue. Scratch wave 2239 // offset is still in an input SGPR. 2240 Info.setScratchRSrcReg(ReservedBufferReg); 2241 } 2242 } 2243 2244 MachineRegisterInfo &MRI = MF.getRegInfo(); 2245 2246 // For entry functions we have to set up the stack pointer if we use it, 2247 // whereas non-entry functions get this "for free". This means there is no 2248 // intrinsic advantage to using S32 over S34 in cases where we do not have 2249 // calls but do need a frame pointer (i.e. if we are requested to have one 2250 // because frame pointer elimination is disabled). To keep things simple we 2251 // only ever use S32 as the call ABI stack pointer, and so using it does not 2252 // imply we need a separate frame pointer. 2253 // 2254 // Try to use s32 as the SP, but move it if it would interfere with input 2255 // arguments. This won't work with calls though. 2256 // 2257 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2258 // registers. 2259 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2260 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2261 } else { 2262 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2263 2264 if (MFI.hasCalls()) 2265 report_fatal_error("call in graphics shader with too many input SGPRs"); 2266 2267 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2268 if (!MRI.isLiveIn(Reg)) { 2269 Info.setStackPtrOffsetReg(Reg); 2270 break; 2271 } 2272 } 2273 2274 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2275 report_fatal_error("failed to find register for SP"); 2276 } 2277 2278 // hasFP should be accurate for entry functions even before the frame is 2279 // finalized, because it does not rely on the known stack size, only 2280 // properties like whether variable sized objects are present. 2281 if (ST.getFrameLowering()->hasFP(MF)) { 2282 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2283 } 2284 } 2285 2286 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2287 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2288 return !Info->isEntryFunction(); 2289 } 2290 2291 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2292 2293 } 2294 2295 void SITargetLowering::insertCopiesSplitCSR( 2296 MachineBasicBlock *Entry, 2297 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2298 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2299 2300 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2301 if (!IStart) 2302 return; 2303 2304 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2305 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2306 MachineBasicBlock::iterator MBBI = Entry->begin(); 2307 for (const MCPhysReg *I = IStart; *I; ++I) { 2308 const TargetRegisterClass *RC = nullptr; 2309 if (AMDGPU::SReg_64RegClass.contains(*I)) 2310 RC = &AMDGPU::SGPR_64RegClass; 2311 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2312 RC = &AMDGPU::SGPR_32RegClass; 2313 else 2314 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2315 2316 Register NewVR = MRI->createVirtualRegister(RC); 2317 // Create copy from CSR to a virtual register. 2318 Entry->addLiveIn(*I); 2319 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2320 .addReg(*I); 2321 2322 // Insert the copy-back instructions right before the terminator. 2323 for (auto *Exit : Exits) 2324 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2325 TII->get(TargetOpcode::COPY), *I) 2326 .addReg(NewVR); 2327 } 2328 } 2329 2330 SDValue SITargetLowering::LowerFormalArguments( 2331 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2332 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2333 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2334 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2335 2336 MachineFunction &MF = DAG.getMachineFunction(); 2337 const Function &Fn = MF.getFunction(); 2338 FunctionType *FType = MF.getFunction().getFunctionType(); 2339 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2340 2341 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) { 2342 DiagnosticInfoUnsupported NoGraphicsHSA( 2343 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2344 DAG.getContext()->diagnose(NoGraphicsHSA); 2345 return DAG.getEntryNode(); 2346 } 2347 2348 Info->allocateModuleLDSGlobal(Fn.getParent()); 2349 2350 SmallVector<ISD::InputArg, 16> Splits; 2351 SmallVector<CCValAssign, 16> ArgLocs; 2352 BitVector Skipped(Ins.size()); 2353 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2354 *DAG.getContext()); 2355 2356 bool IsGraphics = AMDGPU::isGraphics(CallConv); 2357 bool IsKernel = AMDGPU::isKernel(CallConv); 2358 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2359 2360 if (IsGraphics) { 2361 assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && 2362 (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && 2363 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2364 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2365 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2366 !Info->hasWorkItemIDZ()); 2367 } 2368 2369 if (CallConv == CallingConv::AMDGPU_PS) { 2370 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2371 2372 // At least one interpolation mode must be enabled or else the GPU will 2373 // hang. 2374 // 2375 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2376 // set PSInputAddr, the user wants to enable some bits after the compilation 2377 // based on run-time states. Since we can't know what the final PSInputEna 2378 // will look like, so we shouldn't do anything here and the user should take 2379 // responsibility for the correct programming. 2380 // 2381 // Otherwise, the following restrictions apply: 2382 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2383 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2384 // enabled too. 2385 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2386 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) { 2387 CCInfo.AllocateReg(AMDGPU::VGPR0); 2388 CCInfo.AllocateReg(AMDGPU::VGPR1); 2389 Info->markPSInputAllocated(0); 2390 Info->markPSInputEnabled(0); 2391 } 2392 if (Subtarget->isAmdPalOS()) { 2393 // For isAmdPalOS, the user does not enable some bits after compilation 2394 // based on run-time states; the register values being generated here are 2395 // the final ones set in hardware. Therefore we need to apply the 2396 // workaround to PSInputAddr and PSInputEnable together. (The case where 2397 // a bit is set in PSInputAddr but not PSInputEnable is where the 2398 // frontend set up an input arg for a particular interpolation mode, but 2399 // nothing uses that input arg. Really we should have an earlier pass 2400 // that removes such an arg.) 2401 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2402 if ((PsInputBits & 0x7F) == 0 || 2403 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1))) 2404 Info->markPSInputEnabled( 2405 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2406 } 2407 } else if (IsKernel) { 2408 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2409 } else { 2410 Splits.append(Ins.begin(), Ins.end()); 2411 } 2412 2413 if (IsEntryFunc) { 2414 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2415 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2416 } else if (!IsGraphics) { 2417 // For the fixed ABI, pass workitem IDs in the last argument register. 2418 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2419 } 2420 2421 if (IsKernel) { 2422 analyzeFormalArgumentsCompute(CCInfo, Ins); 2423 } else { 2424 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2425 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2426 } 2427 2428 SmallVector<SDValue, 16> Chains; 2429 2430 // FIXME: This is the minimum kernel argument alignment. We should improve 2431 // this to the maximum alignment of the arguments. 2432 // 2433 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2434 // kern arg offset. 2435 const Align KernelArgBaseAlign = Align(16); 2436 2437 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2438 const ISD::InputArg &Arg = Ins[i]; 2439 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2440 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2441 continue; 2442 } 2443 2444 CCValAssign &VA = ArgLocs[ArgIdx++]; 2445 MVT VT = VA.getLocVT(); 2446 2447 if (IsEntryFunc && VA.isMemLoc()) { 2448 VT = Ins[i].VT; 2449 EVT MemVT = VA.getLocVT(); 2450 2451 const uint64_t Offset = VA.getLocMemOffset(); 2452 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2453 2454 if (Arg.Flags.isByRef()) { 2455 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset); 2456 2457 const GCNTargetMachine &TM = 2458 static_cast<const GCNTargetMachine &>(getTargetMachine()); 2459 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS, 2460 Arg.Flags.getPointerAddrSpace())) { 2461 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS, 2462 Arg.Flags.getPointerAddrSpace()); 2463 } 2464 2465 InVals.push_back(Ptr); 2466 continue; 2467 } 2468 2469 SDValue Arg = lowerKernargMemParameter( 2470 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]); 2471 Chains.push_back(Arg.getValue(1)); 2472 2473 auto *ParamTy = 2474 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2475 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2476 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2477 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2478 // On SI local pointers are just offsets into LDS, so they are always 2479 // less than 16-bits. On CI and newer they could potentially be 2480 // real pointers, so we can't guarantee their size. 2481 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2482 DAG.getValueType(MVT::i16)); 2483 } 2484 2485 InVals.push_back(Arg); 2486 continue; 2487 } else if (!IsEntryFunc && VA.isMemLoc()) { 2488 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2489 InVals.push_back(Val); 2490 if (!Arg.Flags.isByVal()) 2491 Chains.push_back(Val.getValue(1)); 2492 continue; 2493 } 2494 2495 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2496 2497 Register Reg = VA.getLocReg(); 2498 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2499 EVT ValVT = VA.getValVT(); 2500 2501 Reg = MF.addLiveIn(Reg, RC); 2502 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2503 2504 if (Arg.Flags.isSRet()) { 2505 // The return object should be reasonably addressable. 2506 2507 // FIXME: This helps when the return is a real sret. If it is a 2508 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2509 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2510 unsigned NumBits 2511 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2512 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2513 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2514 } 2515 2516 // If this is an 8 or 16-bit value, it is really passed promoted 2517 // to 32 bits. Insert an assert[sz]ext to capture this, then 2518 // truncate to the right size. 2519 switch (VA.getLocInfo()) { 2520 case CCValAssign::Full: 2521 break; 2522 case CCValAssign::BCvt: 2523 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2524 break; 2525 case CCValAssign::SExt: 2526 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2527 DAG.getValueType(ValVT)); 2528 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2529 break; 2530 case CCValAssign::ZExt: 2531 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2532 DAG.getValueType(ValVT)); 2533 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2534 break; 2535 case CCValAssign::AExt: 2536 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2537 break; 2538 default: 2539 llvm_unreachable("Unknown loc info!"); 2540 } 2541 2542 InVals.push_back(Val); 2543 } 2544 2545 // Start adding system SGPRs. 2546 if (IsEntryFunc) { 2547 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics); 2548 } else { 2549 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2550 if (!IsGraphics) 2551 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2552 } 2553 2554 auto &ArgUsageInfo = 2555 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2556 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2557 2558 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2559 Info->setBytesInStackArgArea(StackArgSize); 2560 2561 return Chains.empty() ? Chain : 2562 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2563 } 2564 2565 // TODO: If return values can't fit in registers, we should return as many as 2566 // possible in registers before passing on stack. 2567 bool SITargetLowering::CanLowerReturn( 2568 CallingConv::ID CallConv, 2569 MachineFunction &MF, bool IsVarArg, 2570 const SmallVectorImpl<ISD::OutputArg> &Outs, 2571 LLVMContext &Context) const { 2572 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2573 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2574 // for shaders. Vector types should be explicitly handled by CC. 2575 if (AMDGPU::isEntryFunctionCC(CallConv)) 2576 return true; 2577 2578 SmallVector<CCValAssign, 16> RVLocs; 2579 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2580 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2581 } 2582 2583 SDValue 2584 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2585 bool isVarArg, 2586 const SmallVectorImpl<ISD::OutputArg> &Outs, 2587 const SmallVectorImpl<SDValue> &OutVals, 2588 const SDLoc &DL, SelectionDAG &DAG) const { 2589 MachineFunction &MF = DAG.getMachineFunction(); 2590 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2591 2592 if (AMDGPU::isKernel(CallConv)) { 2593 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2594 OutVals, DL, DAG); 2595 } 2596 2597 bool IsShader = AMDGPU::isShader(CallConv); 2598 2599 Info->setIfReturnsVoid(Outs.empty()); 2600 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2601 2602 // CCValAssign - represent the assignment of the return value to a location. 2603 SmallVector<CCValAssign, 48> RVLocs; 2604 SmallVector<ISD::OutputArg, 48> Splits; 2605 2606 // CCState - Info about the registers and stack slots. 2607 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2608 *DAG.getContext()); 2609 2610 // Analyze outgoing return values. 2611 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2612 2613 SDValue Flag; 2614 SmallVector<SDValue, 48> RetOps; 2615 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2616 2617 // Add return address for callable functions. 2618 if (!Info->isEntryFunction()) { 2619 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2620 SDValue ReturnAddrReg = CreateLiveInRegister( 2621 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2622 2623 SDValue ReturnAddrVirtualReg = 2624 DAG.getRegister(MF.getRegInfo().createVirtualRegister( 2625 CallConv != CallingConv::AMDGPU_Gfx 2626 ? &AMDGPU::CCR_SGPR_64RegClass 2627 : &AMDGPU::Gfx_CCR_SGPR_64RegClass), 2628 MVT::i64); 2629 Chain = 2630 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2631 Flag = Chain.getValue(1); 2632 RetOps.push_back(ReturnAddrVirtualReg); 2633 } 2634 2635 // Copy the result values into the output registers. 2636 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2637 ++I, ++RealRVLocIdx) { 2638 CCValAssign &VA = RVLocs[I]; 2639 assert(VA.isRegLoc() && "Can only return in registers!"); 2640 // TODO: Partially return in registers if return values don't fit. 2641 SDValue Arg = OutVals[RealRVLocIdx]; 2642 2643 // Copied from other backends. 2644 switch (VA.getLocInfo()) { 2645 case CCValAssign::Full: 2646 break; 2647 case CCValAssign::BCvt: 2648 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2649 break; 2650 case CCValAssign::SExt: 2651 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2652 break; 2653 case CCValAssign::ZExt: 2654 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2655 break; 2656 case CCValAssign::AExt: 2657 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2658 break; 2659 default: 2660 llvm_unreachable("Unknown loc info!"); 2661 } 2662 2663 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2664 Flag = Chain.getValue(1); 2665 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2666 } 2667 2668 // FIXME: Does sret work properly? 2669 if (!Info->isEntryFunction()) { 2670 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2671 const MCPhysReg *I = 2672 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2673 if (I) { 2674 for (; *I; ++I) { 2675 if (AMDGPU::SReg_64RegClass.contains(*I)) 2676 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2677 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2678 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2679 else 2680 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2681 } 2682 } 2683 } 2684 2685 // Update chain and glue. 2686 RetOps[0] = Chain; 2687 if (Flag.getNode()) 2688 RetOps.push_back(Flag); 2689 2690 unsigned Opc = AMDGPUISD::ENDPGM; 2691 if (!IsWaveEnd) { 2692 if (IsShader) 2693 Opc = AMDGPUISD::RETURN_TO_EPILOG; 2694 else if (CallConv == CallingConv::AMDGPU_Gfx) 2695 Opc = AMDGPUISD::RET_GFX_FLAG; 2696 else 2697 Opc = AMDGPUISD::RET_FLAG; 2698 } 2699 2700 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2701 } 2702 2703 SDValue SITargetLowering::LowerCallResult( 2704 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2705 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2706 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2707 SDValue ThisVal) const { 2708 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2709 2710 // Assign locations to each value returned by this call. 2711 SmallVector<CCValAssign, 16> RVLocs; 2712 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2713 *DAG.getContext()); 2714 CCInfo.AnalyzeCallResult(Ins, RetCC); 2715 2716 // Copy all of the result registers out of their specified physreg. 2717 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2718 CCValAssign VA = RVLocs[i]; 2719 SDValue Val; 2720 2721 if (VA.isRegLoc()) { 2722 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2723 Chain = Val.getValue(1); 2724 InFlag = Val.getValue(2); 2725 } else if (VA.isMemLoc()) { 2726 report_fatal_error("TODO: return values in memory"); 2727 } else 2728 llvm_unreachable("unknown argument location type"); 2729 2730 switch (VA.getLocInfo()) { 2731 case CCValAssign::Full: 2732 break; 2733 case CCValAssign::BCvt: 2734 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2735 break; 2736 case CCValAssign::ZExt: 2737 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2738 DAG.getValueType(VA.getValVT())); 2739 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2740 break; 2741 case CCValAssign::SExt: 2742 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2743 DAG.getValueType(VA.getValVT())); 2744 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2745 break; 2746 case CCValAssign::AExt: 2747 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2748 break; 2749 default: 2750 llvm_unreachable("Unknown loc info!"); 2751 } 2752 2753 InVals.push_back(Val); 2754 } 2755 2756 return Chain; 2757 } 2758 2759 // Add code to pass special inputs required depending on used features separate 2760 // from the explicit user arguments present in the IR. 2761 void SITargetLowering::passSpecialInputs( 2762 CallLoweringInfo &CLI, 2763 CCState &CCInfo, 2764 const SIMachineFunctionInfo &Info, 2765 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2766 SmallVectorImpl<SDValue> &MemOpChains, 2767 SDValue Chain) const { 2768 // If we don't have a call site, this was a call inserted by 2769 // legalization. These can never use special inputs. 2770 if (!CLI.CB) 2771 return; 2772 2773 SelectionDAG &DAG = CLI.DAG; 2774 const SDLoc &DL = CLI.DL; 2775 const Function &F = DAG.getMachineFunction().getFunction(); 2776 2777 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2778 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2779 2780 const AMDGPUFunctionArgInfo *CalleeArgInfo 2781 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2782 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2783 auto &ArgUsageInfo = 2784 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2785 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2786 } 2787 2788 // TODO: Unify with private memory register handling. This is complicated by 2789 // the fact that at least in kernels, the input argument is not necessarily 2790 // in the same location as the input. 2791 static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue, 2792 StringLiteral> ImplicitAttrs[] = { 2793 {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"}, 2794 {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" }, 2795 {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"}, 2796 {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"}, 2797 {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"}, 2798 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"}, 2799 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"} 2800 }; 2801 2802 for (auto Attr : ImplicitAttrs) { 2803 const ArgDescriptor *OutgoingArg; 2804 const TargetRegisterClass *ArgRC; 2805 LLT ArgTy; 2806 2807 AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first; 2808 2809 // If the callee does not use the attribute value, skip copying the value. 2810 if (CLI.CB->hasFnAttr(Attr.second)) 2811 continue; 2812 2813 std::tie(OutgoingArg, ArgRC, ArgTy) = 2814 CalleeArgInfo->getPreloadedValue(InputID); 2815 if (!OutgoingArg) 2816 continue; 2817 2818 const ArgDescriptor *IncomingArg; 2819 const TargetRegisterClass *IncomingArgRC; 2820 LLT Ty; 2821 std::tie(IncomingArg, IncomingArgRC, Ty) = 2822 CallerArgInfo.getPreloadedValue(InputID); 2823 assert(IncomingArgRC == ArgRC); 2824 2825 // All special arguments are ints for now. 2826 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2827 SDValue InputReg; 2828 2829 if (IncomingArg) { 2830 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2831 } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) { 2832 // The implicit arg ptr is special because it doesn't have a corresponding 2833 // input for kernels, and is computed from the kernarg segment pointer. 2834 InputReg = getImplicitArgPtr(DAG, DL); 2835 } else { 2836 // We may have proven the input wasn't needed, although the ABI is 2837 // requiring it. We just need to allocate the register appropriately. 2838 InputReg = DAG.getUNDEF(ArgVT); 2839 } 2840 2841 if (OutgoingArg->isRegister()) { 2842 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2843 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2844 report_fatal_error("failed to allocate implicit input argument"); 2845 } else { 2846 unsigned SpecialArgOffset = 2847 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2848 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2849 SpecialArgOffset); 2850 MemOpChains.push_back(ArgStore); 2851 } 2852 } 2853 2854 // Pack workitem IDs into a single register or pass it as is if already 2855 // packed. 2856 const ArgDescriptor *OutgoingArg; 2857 const TargetRegisterClass *ArgRC; 2858 LLT Ty; 2859 2860 std::tie(OutgoingArg, ArgRC, Ty) = 2861 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2862 if (!OutgoingArg) 2863 std::tie(OutgoingArg, ArgRC, Ty) = 2864 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2865 if (!OutgoingArg) 2866 std::tie(OutgoingArg, ArgRC, Ty) = 2867 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2868 if (!OutgoingArg) 2869 return; 2870 2871 const ArgDescriptor *IncomingArgX = std::get<0>( 2872 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2873 const ArgDescriptor *IncomingArgY = std::get<0>( 2874 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2875 const ArgDescriptor *IncomingArgZ = std::get<0>( 2876 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2877 2878 SDValue InputReg; 2879 SDLoc SL; 2880 2881 const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x"); 2882 const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y"); 2883 const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z"); 2884 2885 // If incoming ids are not packed we need to pack them. 2886 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX && 2887 NeedWorkItemIDX) { 2888 if (Subtarget->getMaxWorkitemID(F, 0) != 0) { 2889 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2890 } else { 2891 InputReg = DAG.getConstant(0, DL, MVT::i32); 2892 } 2893 } 2894 2895 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY && 2896 NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) { 2897 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2898 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2899 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2900 InputReg = InputReg.getNode() ? 2901 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2902 } 2903 2904 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ && 2905 NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) { 2906 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2907 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2908 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2909 InputReg = InputReg.getNode() ? 2910 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2911 } 2912 2913 if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) { 2914 if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) { 2915 // We're in a situation where the outgoing function requires the workitem 2916 // ID, but the calling function does not have it (e.g a graphics function 2917 // calling a C calling convention function). This is illegal, but we need 2918 // to produce something. 2919 InputReg = DAG.getUNDEF(MVT::i32); 2920 } else { 2921 // Workitem ids are already packed, any of present incoming arguments 2922 // will carry all required fields. 2923 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2924 IncomingArgX ? *IncomingArgX : 2925 IncomingArgY ? *IncomingArgY : 2926 *IncomingArgZ, ~0u); 2927 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2928 } 2929 } 2930 2931 if (OutgoingArg->isRegister()) { 2932 if (InputReg) 2933 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2934 2935 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2936 } else { 2937 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2938 if (InputReg) { 2939 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2940 SpecialArgOffset); 2941 MemOpChains.push_back(ArgStore); 2942 } 2943 } 2944 } 2945 2946 static bool canGuaranteeTCO(CallingConv::ID CC) { 2947 return CC == CallingConv::Fast; 2948 } 2949 2950 /// Return true if we might ever do TCO for calls with this calling convention. 2951 static bool mayTailCallThisCC(CallingConv::ID CC) { 2952 switch (CC) { 2953 case CallingConv::C: 2954 case CallingConv::AMDGPU_Gfx: 2955 return true; 2956 default: 2957 return canGuaranteeTCO(CC); 2958 } 2959 } 2960 2961 bool SITargetLowering::isEligibleForTailCallOptimization( 2962 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2963 const SmallVectorImpl<ISD::OutputArg> &Outs, 2964 const SmallVectorImpl<SDValue> &OutVals, 2965 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2966 if (!mayTailCallThisCC(CalleeCC)) 2967 return false; 2968 2969 // For a divergent call target, we need to do a waterfall loop over the 2970 // possible callees which precludes us from using a simple jump. 2971 if (Callee->isDivergent()) 2972 return false; 2973 2974 MachineFunction &MF = DAG.getMachineFunction(); 2975 const Function &CallerF = MF.getFunction(); 2976 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2977 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2978 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2979 2980 // Kernels aren't callable, and don't have a live in return address so it 2981 // doesn't make sense to do a tail call with entry functions. 2982 if (!CallerPreserved) 2983 return false; 2984 2985 bool CCMatch = CallerCC == CalleeCC; 2986 2987 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2988 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2989 return true; 2990 return false; 2991 } 2992 2993 // TODO: Can we handle var args? 2994 if (IsVarArg) 2995 return false; 2996 2997 for (const Argument &Arg : CallerF.args()) { 2998 if (Arg.hasByValAttr()) 2999 return false; 3000 } 3001 3002 LLVMContext &Ctx = *DAG.getContext(); 3003 3004 // Check that the call results are passed in the same way. 3005 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 3006 CCAssignFnForCall(CalleeCC, IsVarArg), 3007 CCAssignFnForCall(CallerCC, IsVarArg))) 3008 return false; 3009 3010 // The callee has to preserve all registers the caller needs to preserve. 3011 if (!CCMatch) { 3012 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 3013 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 3014 return false; 3015 } 3016 3017 // Nothing more to check if the callee is taking no arguments. 3018 if (Outs.empty()) 3019 return true; 3020 3021 SmallVector<CCValAssign, 16> ArgLocs; 3022 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 3023 3024 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 3025 3026 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 3027 // If the stack arguments for this call do not fit into our own save area then 3028 // the call cannot be made tail. 3029 // TODO: Is this really necessary? 3030 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 3031 return false; 3032 3033 const MachineRegisterInfo &MRI = MF.getRegInfo(); 3034 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 3035 } 3036 3037 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 3038 if (!CI->isTailCall()) 3039 return false; 3040 3041 const Function *ParentFn = CI->getParent()->getParent(); 3042 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 3043 return false; 3044 return true; 3045 } 3046 3047 // The wave scratch offset register is used as the global base pointer. 3048 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 3049 SmallVectorImpl<SDValue> &InVals) const { 3050 SelectionDAG &DAG = CLI.DAG; 3051 const SDLoc &DL = CLI.DL; 3052 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 3053 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 3054 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 3055 SDValue Chain = CLI.Chain; 3056 SDValue Callee = CLI.Callee; 3057 bool &IsTailCall = CLI.IsTailCall; 3058 CallingConv::ID CallConv = CLI.CallConv; 3059 bool IsVarArg = CLI.IsVarArg; 3060 bool IsSibCall = false; 3061 bool IsThisReturn = false; 3062 MachineFunction &MF = DAG.getMachineFunction(); 3063 3064 if (Callee.isUndef() || isNullConstant(Callee)) { 3065 if (!CLI.IsTailCall) { 3066 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 3067 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 3068 } 3069 3070 return Chain; 3071 } 3072 3073 if (IsVarArg) { 3074 return lowerUnhandledCall(CLI, InVals, 3075 "unsupported call to variadic function "); 3076 } 3077 3078 if (!CLI.CB) 3079 report_fatal_error("unsupported libcall legalization"); 3080 3081 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 3082 return lowerUnhandledCall(CLI, InVals, 3083 "unsupported required tail call to function "); 3084 } 3085 3086 if (AMDGPU::isShader(CallConv)) { 3087 // Note the issue is with the CC of the called function, not of the call 3088 // itself. 3089 return lowerUnhandledCall(CLI, InVals, 3090 "unsupported call to a shader function "); 3091 } 3092 3093 if (AMDGPU::isShader(MF.getFunction().getCallingConv()) && 3094 CallConv != CallingConv::AMDGPU_Gfx) { 3095 // Only allow calls with specific calling conventions. 3096 return lowerUnhandledCall(CLI, InVals, 3097 "unsupported calling convention for call from " 3098 "graphics shader of function "); 3099 } 3100 3101 if (IsTailCall) { 3102 IsTailCall = isEligibleForTailCallOptimization( 3103 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 3104 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 3105 report_fatal_error("failed to perform tail call elimination on a call " 3106 "site marked musttail"); 3107 } 3108 3109 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 3110 3111 // A sibling call is one where we're under the usual C ABI and not planning 3112 // to change that but can still do a tail call: 3113 if (!TailCallOpt && IsTailCall) 3114 IsSibCall = true; 3115 3116 if (IsTailCall) 3117 ++NumTailCalls; 3118 } 3119 3120 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3121 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3122 SmallVector<SDValue, 8> MemOpChains; 3123 3124 // Analyze operands of the call, assigning locations to each operand. 3125 SmallVector<CCValAssign, 16> ArgLocs; 3126 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 3127 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 3128 3129 if (CallConv != CallingConv::AMDGPU_Gfx) { 3130 // With a fixed ABI, allocate fixed registers before user arguments. 3131 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3132 } 3133 3134 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 3135 3136 // Get a count of how many bytes are to be pushed on the stack. 3137 unsigned NumBytes = CCInfo.getNextStackOffset(); 3138 3139 if (IsSibCall) { 3140 // Since we're not changing the ABI to make this a tail call, the memory 3141 // operands are already available in the caller's incoming argument space. 3142 NumBytes = 0; 3143 } 3144 3145 // FPDiff is the byte offset of the call's argument area from the callee's. 3146 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3147 // by this amount for a tail call. In a sibling call it must be 0 because the 3148 // caller will deallocate the entire stack and the callee still expects its 3149 // arguments to begin at SP+0. Completely unused for non-tail calls. 3150 int32_t FPDiff = 0; 3151 MachineFrameInfo &MFI = MF.getFrameInfo(); 3152 3153 // Adjust the stack pointer for the new arguments... 3154 // These operations are automatically eliminated by the prolog/epilog pass 3155 if (!IsSibCall) { 3156 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 3157 3158 if (!Subtarget->enableFlatScratch()) { 3159 SmallVector<SDValue, 4> CopyFromChains; 3160 3161 // In the HSA case, this should be an identity copy. 3162 SDValue ScratchRSrcReg 3163 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 3164 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 3165 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 3166 Chain = DAG.getTokenFactor(DL, CopyFromChains); 3167 } 3168 } 3169 3170 MVT PtrVT = MVT::i32; 3171 3172 // Walk the register/memloc assignments, inserting copies/loads. 3173 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3174 CCValAssign &VA = ArgLocs[i]; 3175 SDValue Arg = OutVals[i]; 3176 3177 // Promote the value if needed. 3178 switch (VA.getLocInfo()) { 3179 case CCValAssign::Full: 3180 break; 3181 case CCValAssign::BCvt: 3182 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3183 break; 3184 case CCValAssign::ZExt: 3185 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3186 break; 3187 case CCValAssign::SExt: 3188 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3189 break; 3190 case CCValAssign::AExt: 3191 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3192 break; 3193 case CCValAssign::FPExt: 3194 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3195 break; 3196 default: 3197 llvm_unreachable("Unknown loc info!"); 3198 } 3199 3200 if (VA.isRegLoc()) { 3201 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3202 } else { 3203 assert(VA.isMemLoc()); 3204 3205 SDValue DstAddr; 3206 MachinePointerInfo DstInfo; 3207 3208 unsigned LocMemOffset = VA.getLocMemOffset(); 3209 int32_t Offset = LocMemOffset; 3210 3211 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3212 MaybeAlign Alignment; 3213 3214 if (IsTailCall) { 3215 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3216 unsigned OpSize = Flags.isByVal() ? 3217 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3218 3219 // FIXME: We can have better than the minimum byval required alignment. 3220 Alignment = 3221 Flags.isByVal() 3222 ? Flags.getNonZeroByValAlign() 3223 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3224 3225 Offset = Offset + FPDiff; 3226 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3227 3228 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3229 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3230 3231 // Make sure any stack arguments overlapping with where we're storing 3232 // are loaded before this eventual operation. Otherwise they'll be 3233 // clobbered. 3234 3235 // FIXME: Why is this really necessary? This seems to just result in a 3236 // lot of code to copy the stack and write them back to the same 3237 // locations, which are supposed to be immutable? 3238 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3239 } else { 3240 // Stores to the argument stack area are relative to the stack pointer. 3241 SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(), 3242 MVT::i32); 3243 DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff); 3244 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3245 Alignment = 3246 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3247 } 3248 3249 if (Outs[i].Flags.isByVal()) { 3250 SDValue SizeNode = 3251 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3252 SDValue Cpy = 3253 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3254 Outs[i].Flags.getNonZeroByValAlign(), 3255 /*isVol = */ false, /*AlwaysInline = */ true, 3256 /*isTailCall = */ false, DstInfo, 3257 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3258 3259 MemOpChains.push_back(Cpy); 3260 } else { 3261 SDValue Store = 3262 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment); 3263 MemOpChains.push_back(Store); 3264 } 3265 } 3266 } 3267 3268 if (!MemOpChains.empty()) 3269 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3270 3271 // Build a sequence of copy-to-reg nodes chained together with token chain 3272 // and flag operands which copy the outgoing args into the appropriate regs. 3273 SDValue InFlag; 3274 for (auto &RegToPass : RegsToPass) { 3275 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3276 RegToPass.second, InFlag); 3277 InFlag = Chain.getValue(1); 3278 } 3279 3280 3281 SDValue PhysReturnAddrReg; 3282 if (IsTailCall) { 3283 // Since the return is being combined with the call, we need to pass on the 3284 // return address. 3285 3286 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3287 SDValue ReturnAddrReg = CreateLiveInRegister( 3288 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 3289 3290 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3291 MVT::i64); 3292 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3293 InFlag = Chain.getValue(1); 3294 } 3295 3296 // We don't usually want to end the call-sequence here because we would tidy 3297 // the frame up *after* the call, however in the ABI-changing tail-call case 3298 // we've carefully laid out the parameters so that when sp is reset they'll be 3299 // in the correct location. 3300 if (IsTailCall && !IsSibCall) { 3301 Chain = DAG.getCALLSEQ_END(Chain, 3302 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3303 DAG.getTargetConstant(0, DL, MVT::i32), 3304 InFlag, DL); 3305 InFlag = Chain.getValue(1); 3306 } 3307 3308 std::vector<SDValue> Ops; 3309 Ops.push_back(Chain); 3310 Ops.push_back(Callee); 3311 // Add a redundant copy of the callee global which will not be legalized, as 3312 // we need direct access to the callee later. 3313 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3314 const GlobalValue *GV = GSD->getGlobal(); 3315 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3316 } else { 3317 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3318 } 3319 3320 if (IsTailCall) { 3321 // Each tail call may have to adjust the stack by a different amount, so 3322 // this information must travel along with the operation for eventual 3323 // consumption by emitEpilogue. 3324 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3325 3326 Ops.push_back(PhysReturnAddrReg); 3327 } 3328 3329 // Add argument registers to the end of the list so that they are known live 3330 // into the call. 3331 for (auto &RegToPass : RegsToPass) { 3332 Ops.push_back(DAG.getRegister(RegToPass.first, 3333 RegToPass.second.getValueType())); 3334 } 3335 3336 // Add a register mask operand representing the call-preserved registers. 3337 3338 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3339 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3340 assert(Mask && "Missing call preserved mask for calling convention"); 3341 Ops.push_back(DAG.getRegisterMask(Mask)); 3342 3343 if (InFlag.getNode()) 3344 Ops.push_back(InFlag); 3345 3346 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3347 3348 // If we're doing a tall call, use a TC_RETURN here rather than an 3349 // actual call instruction. 3350 if (IsTailCall) { 3351 MFI.setHasTailCall(); 3352 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3353 } 3354 3355 // Returns a chain and a flag for retval copy to use. 3356 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3357 Chain = Call.getValue(0); 3358 InFlag = Call.getValue(1); 3359 3360 uint64_t CalleePopBytes = NumBytes; 3361 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3362 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3363 InFlag, DL); 3364 if (!Ins.empty()) 3365 InFlag = Chain.getValue(1); 3366 3367 // Handle result values, copying them out of physregs into vregs that we 3368 // return. 3369 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3370 InVals, IsThisReturn, 3371 IsThisReturn ? OutVals[0] : SDValue()); 3372 } 3373 3374 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3375 // except for applying the wave size scale to the increment amount. 3376 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3377 SDValue Op, SelectionDAG &DAG) const { 3378 const MachineFunction &MF = DAG.getMachineFunction(); 3379 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3380 3381 SDLoc dl(Op); 3382 EVT VT = Op.getValueType(); 3383 SDValue Tmp1 = Op; 3384 SDValue Tmp2 = Op.getValue(1); 3385 SDValue Tmp3 = Op.getOperand(2); 3386 SDValue Chain = Tmp1.getOperand(0); 3387 3388 Register SPReg = Info->getStackPtrOffsetReg(); 3389 3390 // Chain the dynamic stack allocation so that it doesn't modify the stack 3391 // pointer when other instructions are using the stack. 3392 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3393 3394 SDValue Size = Tmp2.getOperand(1); 3395 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3396 Chain = SP.getValue(1); 3397 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3398 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3399 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3400 unsigned Opc = 3401 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3402 ISD::ADD : ISD::SUB; 3403 3404 SDValue ScaledSize = DAG.getNode( 3405 ISD::SHL, dl, VT, Size, 3406 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3407 3408 Align StackAlign = TFL->getStackAlign(); 3409 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3410 if (Alignment && *Alignment > StackAlign) { 3411 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3412 DAG.getConstant(-(uint64_t)Alignment->value() 3413 << ST.getWavefrontSizeLog2(), 3414 dl, VT)); 3415 } 3416 3417 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3418 Tmp2 = DAG.getCALLSEQ_END( 3419 Chain, DAG.getIntPtrConstant(0, dl, true), 3420 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3421 3422 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3423 } 3424 3425 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3426 SelectionDAG &DAG) const { 3427 // We only handle constant sizes here to allow non-entry block, static sized 3428 // allocas. A truly dynamic value is more difficult to support because we 3429 // don't know if the size value is uniform or not. If the size isn't uniform, 3430 // we would need to do a wave reduction to get the maximum size to know how 3431 // much to increment the uniform stack pointer. 3432 SDValue Size = Op.getOperand(1); 3433 if (isa<ConstantSDNode>(Size)) 3434 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3435 3436 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3437 } 3438 3439 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3440 const MachineFunction &MF) const { 3441 Register Reg = StringSwitch<Register>(RegName) 3442 .Case("m0", AMDGPU::M0) 3443 .Case("exec", AMDGPU::EXEC) 3444 .Case("exec_lo", AMDGPU::EXEC_LO) 3445 .Case("exec_hi", AMDGPU::EXEC_HI) 3446 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3447 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3448 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3449 .Default(Register()); 3450 3451 if (Reg == AMDGPU::NoRegister) { 3452 report_fatal_error(Twine("invalid register name \"" 3453 + StringRef(RegName) + "\".")); 3454 3455 } 3456 3457 if (!Subtarget->hasFlatScrRegister() && 3458 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3459 report_fatal_error(Twine("invalid register \"" 3460 + StringRef(RegName) + "\" for subtarget.")); 3461 } 3462 3463 switch (Reg) { 3464 case AMDGPU::M0: 3465 case AMDGPU::EXEC_LO: 3466 case AMDGPU::EXEC_HI: 3467 case AMDGPU::FLAT_SCR_LO: 3468 case AMDGPU::FLAT_SCR_HI: 3469 if (VT.getSizeInBits() == 32) 3470 return Reg; 3471 break; 3472 case AMDGPU::EXEC: 3473 case AMDGPU::FLAT_SCR: 3474 if (VT.getSizeInBits() == 64) 3475 return Reg; 3476 break; 3477 default: 3478 llvm_unreachable("missing register type checking"); 3479 } 3480 3481 report_fatal_error(Twine("invalid type for register \"" 3482 + StringRef(RegName) + "\".")); 3483 } 3484 3485 // If kill is not the last instruction, split the block so kill is always a 3486 // proper terminator. 3487 MachineBasicBlock * 3488 SITargetLowering::splitKillBlock(MachineInstr &MI, 3489 MachineBasicBlock *BB) const { 3490 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/); 3491 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3492 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3493 return SplitBB; 3494 } 3495 3496 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3497 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3498 // be the first instruction in the remainder block. 3499 // 3500 /// \returns { LoopBody, Remainder } 3501 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3502 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3503 MachineFunction *MF = MBB.getParent(); 3504 MachineBasicBlock::iterator I(&MI); 3505 3506 // To insert the loop we need to split the block. Move everything after this 3507 // point to a new block, and insert a new empty block between the two. 3508 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3509 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3510 MachineFunction::iterator MBBI(MBB); 3511 ++MBBI; 3512 3513 MF->insert(MBBI, LoopBB); 3514 MF->insert(MBBI, RemainderBB); 3515 3516 LoopBB->addSuccessor(LoopBB); 3517 LoopBB->addSuccessor(RemainderBB); 3518 3519 // Move the rest of the block into a new block. 3520 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3521 3522 if (InstInLoop) { 3523 auto Next = std::next(I); 3524 3525 // Move instruction to loop body. 3526 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3527 3528 // Move the rest of the block. 3529 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3530 } else { 3531 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3532 } 3533 3534 MBB.addSuccessor(LoopBB); 3535 3536 return std::make_pair(LoopBB, RemainderBB); 3537 } 3538 3539 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3540 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3541 MachineBasicBlock *MBB = MI.getParent(); 3542 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3543 auto I = MI.getIterator(); 3544 auto E = std::next(I); 3545 3546 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3547 .addImm(0); 3548 3549 MIBundleBuilder Bundler(*MBB, I, E); 3550 finalizeBundle(*MBB, Bundler.begin()); 3551 } 3552 3553 MachineBasicBlock * 3554 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3555 MachineBasicBlock *BB) const { 3556 const DebugLoc &DL = MI.getDebugLoc(); 3557 3558 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3559 3560 MachineBasicBlock *LoopBB; 3561 MachineBasicBlock *RemainderBB; 3562 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3563 3564 // Apparently kill flags are only valid if the def is in the same block? 3565 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3566 Src->setIsKill(false); 3567 3568 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3569 3570 MachineBasicBlock::iterator I = LoopBB->end(); 3571 3572 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3573 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3574 3575 // Clear TRAP_STS.MEM_VIOL 3576 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3577 .addImm(0) 3578 .addImm(EncodedReg); 3579 3580 bundleInstWithWaitcnt(MI); 3581 3582 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3583 3584 // Load and check TRAP_STS.MEM_VIOL 3585 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3586 .addImm(EncodedReg); 3587 3588 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3589 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3590 .addReg(Reg, RegState::Kill) 3591 .addImm(0); 3592 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3593 .addMBB(LoopBB); 3594 3595 return RemainderBB; 3596 } 3597 3598 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3599 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3600 // will only do one iteration. In the worst case, this will loop 64 times. 3601 // 3602 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3603 static MachineBasicBlock::iterator 3604 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI, 3605 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB, 3606 const DebugLoc &DL, const MachineOperand &Idx, 3607 unsigned InitReg, unsigned ResultReg, unsigned PhiReg, 3608 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode, 3609 Register &SGPRIdxReg) { 3610 3611 MachineFunction *MF = OrigBB.getParent(); 3612 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3613 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3614 MachineBasicBlock::iterator I = LoopBB.begin(); 3615 3616 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3617 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3618 Register NewExec = MRI.createVirtualRegister(BoolRC); 3619 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3620 Register CondReg = MRI.createVirtualRegister(BoolRC); 3621 3622 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3623 .addReg(InitReg) 3624 .addMBB(&OrigBB) 3625 .addReg(ResultReg) 3626 .addMBB(&LoopBB); 3627 3628 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3629 .addReg(InitSaveExecReg) 3630 .addMBB(&OrigBB) 3631 .addReg(NewExec) 3632 .addMBB(&LoopBB); 3633 3634 // Read the next variant <- also loop target. 3635 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3636 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef())); 3637 3638 // Compare the just read M0 value to all possible Idx values. 3639 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3640 .addReg(CurrentIdxReg) 3641 .addReg(Idx.getReg(), 0, Idx.getSubReg()); 3642 3643 // Update EXEC, save the original EXEC value to VCC. 3644 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3645 : AMDGPU::S_AND_SAVEEXEC_B64), 3646 NewExec) 3647 .addReg(CondReg, RegState::Kill); 3648 3649 MRI.setSimpleHint(NewExec, CondReg); 3650 3651 if (UseGPRIdxMode) { 3652 if (Offset == 0) { 3653 SGPRIdxReg = CurrentIdxReg; 3654 } else { 3655 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3656 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg) 3657 .addReg(CurrentIdxReg, RegState::Kill) 3658 .addImm(Offset); 3659 } 3660 } else { 3661 // Move index from VCC into M0 3662 if (Offset == 0) { 3663 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3664 .addReg(CurrentIdxReg, RegState::Kill); 3665 } else { 3666 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3667 .addReg(CurrentIdxReg, RegState::Kill) 3668 .addImm(Offset); 3669 } 3670 } 3671 3672 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3673 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3674 MachineInstr *InsertPt = 3675 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3676 : AMDGPU::S_XOR_B64_term), Exec) 3677 .addReg(Exec) 3678 .addReg(NewExec); 3679 3680 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3681 // s_cbranch_scc0? 3682 3683 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3684 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3685 .addMBB(&LoopBB); 3686 3687 return InsertPt->getIterator(); 3688 } 3689 3690 // This has slightly sub-optimal regalloc when the source vector is killed by 3691 // the read. The register allocator does not understand that the kill is 3692 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3693 // subregister from it, using 1 more VGPR than necessary. This was saved when 3694 // this was expanded after register allocation. 3695 static MachineBasicBlock::iterator 3696 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI, 3697 unsigned InitResultReg, unsigned PhiReg, int Offset, 3698 bool UseGPRIdxMode, Register &SGPRIdxReg) { 3699 MachineFunction *MF = MBB.getParent(); 3700 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3701 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3702 MachineRegisterInfo &MRI = MF->getRegInfo(); 3703 const DebugLoc &DL = MI.getDebugLoc(); 3704 MachineBasicBlock::iterator I(&MI); 3705 3706 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3707 Register DstReg = MI.getOperand(0).getReg(); 3708 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3709 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3710 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3711 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3712 3713 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3714 3715 // Save the EXEC mask 3716 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3717 .addReg(Exec); 3718 3719 MachineBasicBlock *LoopBB; 3720 MachineBasicBlock *RemainderBB; 3721 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3722 3723 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3724 3725 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3726 InitResultReg, DstReg, PhiReg, TmpExec, 3727 Offset, UseGPRIdxMode, SGPRIdxReg); 3728 3729 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3730 MachineFunction::iterator MBBI(LoopBB); 3731 ++MBBI; 3732 MF->insert(MBBI, LandingPad); 3733 LoopBB->removeSuccessor(RemainderBB); 3734 LandingPad->addSuccessor(RemainderBB); 3735 LoopBB->addSuccessor(LandingPad); 3736 MachineBasicBlock::iterator First = LandingPad->begin(); 3737 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3738 .addReg(SaveExec); 3739 3740 return InsPt; 3741 } 3742 3743 // Returns subreg index, offset 3744 static std::pair<unsigned, int> 3745 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3746 const TargetRegisterClass *SuperRC, 3747 unsigned VecReg, 3748 int Offset) { 3749 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3750 3751 // Skip out of bounds offsets, or else we would end up using an undefined 3752 // register. 3753 if (Offset >= NumElts || Offset < 0) 3754 return std::make_pair(AMDGPU::sub0, Offset); 3755 3756 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3757 } 3758 3759 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3760 MachineRegisterInfo &MRI, MachineInstr &MI, 3761 int Offset) { 3762 MachineBasicBlock *MBB = MI.getParent(); 3763 const DebugLoc &DL = MI.getDebugLoc(); 3764 MachineBasicBlock::iterator I(&MI); 3765 3766 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3767 3768 assert(Idx->getReg() != AMDGPU::NoRegister); 3769 3770 if (Offset == 0) { 3771 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx); 3772 } else { 3773 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3774 .add(*Idx) 3775 .addImm(Offset); 3776 } 3777 } 3778 3779 static Register getIndirectSGPRIdx(const SIInstrInfo *TII, 3780 MachineRegisterInfo &MRI, MachineInstr &MI, 3781 int Offset) { 3782 MachineBasicBlock *MBB = MI.getParent(); 3783 const DebugLoc &DL = MI.getDebugLoc(); 3784 MachineBasicBlock::iterator I(&MI); 3785 3786 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3787 3788 if (Offset == 0) 3789 return Idx->getReg(); 3790 3791 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3792 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3793 .add(*Idx) 3794 .addImm(Offset); 3795 return Tmp; 3796 } 3797 3798 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3799 MachineBasicBlock &MBB, 3800 const GCNSubtarget &ST) { 3801 const SIInstrInfo *TII = ST.getInstrInfo(); 3802 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3803 MachineFunction *MF = MBB.getParent(); 3804 MachineRegisterInfo &MRI = MF->getRegInfo(); 3805 3806 Register Dst = MI.getOperand(0).getReg(); 3807 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3808 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3809 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3810 3811 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3812 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3813 3814 unsigned SubReg; 3815 std::tie(SubReg, Offset) 3816 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3817 3818 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3819 3820 // Check for a SGPR index. 3821 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3822 MachineBasicBlock::iterator I(&MI); 3823 const DebugLoc &DL = MI.getDebugLoc(); 3824 3825 if (UseGPRIdxMode) { 3826 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3827 // to avoid interfering with other uses, so probably requires a new 3828 // optimization pass. 3829 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3830 3831 const MCInstrDesc &GPRIDXDesc = 3832 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3833 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3834 .addReg(SrcReg) 3835 .addReg(Idx) 3836 .addImm(SubReg); 3837 } else { 3838 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3839 3840 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3841 .addReg(SrcReg, 0, SubReg) 3842 .addReg(SrcReg, RegState::Implicit); 3843 } 3844 3845 MI.eraseFromParent(); 3846 3847 return &MBB; 3848 } 3849 3850 // Control flow needs to be inserted if indexing with a VGPR. 3851 const DebugLoc &DL = MI.getDebugLoc(); 3852 MachineBasicBlock::iterator I(&MI); 3853 3854 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3855 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3856 3857 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3858 3859 Register SGPRIdxReg; 3860 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, 3861 UseGPRIdxMode, SGPRIdxReg); 3862 3863 MachineBasicBlock *LoopBB = InsPt->getParent(); 3864 3865 if (UseGPRIdxMode) { 3866 const MCInstrDesc &GPRIDXDesc = 3867 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3868 3869 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3870 .addReg(SrcReg) 3871 .addReg(SGPRIdxReg) 3872 .addImm(SubReg); 3873 } else { 3874 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3875 .addReg(SrcReg, 0, SubReg) 3876 .addReg(SrcReg, RegState::Implicit); 3877 } 3878 3879 MI.eraseFromParent(); 3880 3881 return LoopBB; 3882 } 3883 3884 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3885 MachineBasicBlock &MBB, 3886 const GCNSubtarget &ST) { 3887 const SIInstrInfo *TII = ST.getInstrInfo(); 3888 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3889 MachineFunction *MF = MBB.getParent(); 3890 MachineRegisterInfo &MRI = MF->getRegInfo(); 3891 3892 Register Dst = MI.getOperand(0).getReg(); 3893 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3894 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3895 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3896 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3897 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3898 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3899 3900 // This can be an immediate, but will be folded later. 3901 assert(Val->getReg()); 3902 3903 unsigned SubReg; 3904 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3905 SrcVec->getReg(), 3906 Offset); 3907 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3908 3909 if (Idx->getReg() == AMDGPU::NoRegister) { 3910 MachineBasicBlock::iterator I(&MI); 3911 const DebugLoc &DL = MI.getDebugLoc(); 3912 3913 assert(Offset == 0); 3914 3915 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3916 .add(*SrcVec) 3917 .add(*Val) 3918 .addImm(SubReg); 3919 3920 MI.eraseFromParent(); 3921 return &MBB; 3922 } 3923 3924 // Check for a SGPR index. 3925 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3926 MachineBasicBlock::iterator I(&MI); 3927 const DebugLoc &DL = MI.getDebugLoc(); 3928 3929 if (UseGPRIdxMode) { 3930 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3931 3932 const MCInstrDesc &GPRIDXDesc = 3933 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3934 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3935 .addReg(SrcVec->getReg()) 3936 .add(*Val) 3937 .addReg(Idx) 3938 .addImm(SubReg); 3939 } else { 3940 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3941 3942 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3943 TRI.getRegSizeInBits(*VecRC), 32, false); 3944 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3945 .addReg(SrcVec->getReg()) 3946 .add(*Val) 3947 .addImm(SubReg); 3948 } 3949 MI.eraseFromParent(); 3950 return &MBB; 3951 } 3952 3953 // Control flow needs to be inserted if indexing with a VGPR. 3954 if (Val->isReg()) 3955 MRI.clearKillFlags(Val->getReg()); 3956 3957 const DebugLoc &DL = MI.getDebugLoc(); 3958 3959 Register PhiReg = MRI.createVirtualRegister(VecRC); 3960 3961 Register SGPRIdxReg; 3962 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset, 3963 UseGPRIdxMode, SGPRIdxReg); 3964 MachineBasicBlock *LoopBB = InsPt->getParent(); 3965 3966 if (UseGPRIdxMode) { 3967 const MCInstrDesc &GPRIDXDesc = 3968 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3969 3970 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3971 .addReg(PhiReg) 3972 .add(*Val) 3973 .addReg(SGPRIdxReg) 3974 .addImm(AMDGPU::sub0); 3975 } else { 3976 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3977 TRI.getRegSizeInBits(*VecRC), 32, false); 3978 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3979 .addReg(PhiReg) 3980 .add(*Val) 3981 .addImm(AMDGPU::sub0); 3982 } 3983 3984 MI.eraseFromParent(); 3985 return LoopBB; 3986 } 3987 3988 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3989 MachineInstr &MI, MachineBasicBlock *BB) const { 3990 3991 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3992 MachineFunction *MF = BB->getParent(); 3993 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3994 3995 switch (MI.getOpcode()) { 3996 case AMDGPU::S_UADDO_PSEUDO: 3997 case AMDGPU::S_USUBO_PSEUDO: { 3998 const DebugLoc &DL = MI.getDebugLoc(); 3999 MachineOperand &Dest0 = MI.getOperand(0); 4000 MachineOperand &Dest1 = MI.getOperand(1); 4001 MachineOperand &Src0 = MI.getOperand(2); 4002 MachineOperand &Src1 = MI.getOperand(3); 4003 4004 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 4005 ? AMDGPU::S_ADD_I32 4006 : AMDGPU::S_SUB_I32; 4007 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 4008 4009 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 4010 .addImm(1) 4011 .addImm(0); 4012 4013 MI.eraseFromParent(); 4014 return BB; 4015 } 4016 case AMDGPU::S_ADD_U64_PSEUDO: 4017 case AMDGPU::S_SUB_U64_PSEUDO: { 4018 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4019 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4020 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4021 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 4022 const DebugLoc &DL = MI.getDebugLoc(); 4023 4024 MachineOperand &Dest = MI.getOperand(0); 4025 MachineOperand &Src0 = MI.getOperand(1); 4026 MachineOperand &Src1 = MI.getOperand(2); 4027 4028 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4029 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4030 4031 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 4032 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 4033 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 4034 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 4035 4036 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 4037 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 4038 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 4039 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 4040 4041 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 4042 4043 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 4044 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 4045 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 4046 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 4047 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 4048 .addReg(DestSub0) 4049 .addImm(AMDGPU::sub0) 4050 .addReg(DestSub1) 4051 .addImm(AMDGPU::sub1); 4052 MI.eraseFromParent(); 4053 return BB; 4054 } 4055 case AMDGPU::V_ADD_U64_PSEUDO: 4056 case AMDGPU::V_SUB_U64_PSEUDO: { 4057 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4058 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4059 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4060 const DebugLoc &DL = MI.getDebugLoc(); 4061 4062 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 4063 4064 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4065 4066 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4067 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4068 4069 Register CarryReg = MRI.createVirtualRegister(CarryRC); 4070 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 4071 4072 MachineOperand &Dest = MI.getOperand(0); 4073 MachineOperand &Src0 = MI.getOperand(1); 4074 MachineOperand &Src1 = MI.getOperand(2); 4075 4076 const TargetRegisterClass *Src0RC = Src0.isReg() 4077 ? MRI.getRegClass(Src0.getReg()) 4078 : &AMDGPU::VReg_64RegClass; 4079 const TargetRegisterClass *Src1RC = Src1.isReg() 4080 ? MRI.getRegClass(Src1.getReg()) 4081 : &AMDGPU::VReg_64RegClass; 4082 4083 const TargetRegisterClass *Src0SubRC = 4084 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 4085 const TargetRegisterClass *Src1SubRC = 4086 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 4087 4088 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 4089 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 4090 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 4091 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 4092 4093 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 4094 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 4095 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 4096 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 4097 4098 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 4099 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 4100 .addReg(CarryReg, RegState::Define) 4101 .add(SrcReg0Sub0) 4102 .add(SrcReg1Sub0) 4103 .addImm(0); // clamp bit 4104 4105 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 4106 MachineInstr *HiHalf = 4107 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 4108 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 4109 .add(SrcReg0Sub1) 4110 .add(SrcReg1Sub1) 4111 .addReg(CarryReg, RegState::Kill) 4112 .addImm(0); // clamp bit 4113 4114 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 4115 .addReg(DestSub0) 4116 .addImm(AMDGPU::sub0) 4117 .addReg(DestSub1) 4118 .addImm(AMDGPU::sub1); 4119 TII->legalizeOperands(*LoHalf); 4120 TII->legalizeOperands(*HiHalf); 4121 MI.eraseFromParent(); 4122 return BB; 4123 } 4124 case AMDGPU::S_ADD_CO_PSEUDO: 4125 case AMDGPU::S_SUB_CO_PSEUDO: { 4126 // This pseudo has a chance to be selected 4127 // only from uniform add/subcarry node. All the VGPR operands 4128 // therefore assumed to be splat vectors. 4129 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4130 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4131 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4132 MachineBasicBlock::iterator MII = MI; 4133 const DebugLoc &DL = MI.getDebugLoc(); 4134 MachineOperand &Dest = MI.getOperand(0); 4135 MachineOperand &CarryDest = MI.getOperand(1); 4136 MachineOperand &Src0 = MI.getOperand(2); 4137 MachineOperand &Src1 = MI.getOperand(3); 4138 MachineOperand &Src2 = MI.getOperand(4); 4139 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 4140 ? AMDGPU::S_ADDC_U32 4141 : AMDGPU::S_SUBB_U32; 4142 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 4143 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4144 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 4145 .addReg(Src0.getReg()); 4146 Src0.setReg(RegOp0); 4147 } 4148 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 4149 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4150 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 4151 .addReg(Src1.getReg()); 4152 Src1.setReg(RegOp1); 4153 } 4154 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4155 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 4156 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 4157 .addReg(Src2.getReg()); 4158 Src2.setReg(RegOp2); 4159 } 4160 4161 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg()); 4162 unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC); 4163 assert(WaveSize == 64 || WaveSize == 32); 4164 4165 if (WaveSize == 64) { 4166 if (ST.hasScalarCompareEq64()) { 4167 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 4168 .addReg(Src2.getReg()) 4169 .addImm(0); 4170 } else { 4171 const TargetRegisterClass *SubRC = 4172 TRI->getSubRegClass(Src2RC, AMDGPU::sub0); 4173 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm( 4174 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC); 4175 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm( 4176 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC); 4177 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4178 4179 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32) 4180 .add(Src2Sub0) 4181 .add(Src2Sub1); 4182 4183 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 4184 .addReg(Src2_32, RegState::Kill) 4185 .addImm(0); 4186 } 4187 } else { 4188 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4189 .addReg(Src2.getReg()) 4190 .addImm(0); 4191 } 4192 4193 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4194 4195 unsigned SelOpc = 4196 (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32; 4197 4198 BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg()) 4199 .addImm(-1) 4200 .addImm(0); 4201 4202 MI.eraseFromParent(); 4203 return BB; 4204 } 4205 case AMDGPU::SI_INIT_M0: { 4206 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4207 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4208 .add(MI.getOperand(0)); 4209 MI.eraseFromParent(); 4210 return BB; 4211 } 4212 case AMDGPU::GET_GROUPSTATICSIZE: { 4213 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4214 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4215 DebugLoc DL = MI.getDebugLoc(); 4216 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4217 .add(MI.getOperand(0)) 4218 .addImm(MFI->getLDSSize()); 4219 MI.eraseFromParent(); 4220 return BB; 4221 } 4222 case AMDGPU::SI_INDIRECT_SRC_V1: 4223 case AMDGPU::SI_INDIRECT_SRC_V2: 4224 case AMDGPU::SI_INDIRECT_SRC_V4: 4225 case AMDGPU::SI_INDIRECT_SRC_V8: 4226 case AMDGPU::SI_INDIRECT_SRC_V16: 4227 case AMDGPU::SI_INDIRECT_SRC_V32: 4228 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4229 case AMDGPU::SI_INDIRECT_DST_V1: 4230 case AMDGPU::SI_INDIRECT_DST_V2: 4231 case AMDGPU::SI_INDIRECT_DST_V4: 4232 case AMDGPU::SI_INDIRECT_DST_V8: 4233 case AMDGPU::SI_INDIRECT_DST_V16: 4234 case AMDGPU::SI_INDIRECT_DST_V32: 4235 return emitIndirectDst(MI, *BB, *getSubtarget()); 4236 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4237 case AMDGPU::SI_KILL_I1_PSEUDO: 4238 return splitKillBlock(MI, BB); 4239 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4240 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4241 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4242 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4243 4244 Register Dst = MI.getOperand(0).getReg(); 4245 Register Src0 = MI.getOperand(1).getReg(); 4246 Register Src1 = MI.getOperand(2).getReg(); 4247 const DebugLoc &DL = MI.getDebugLoc(); 4248 Register SrcCond = MI.getOperand(3).getReg(); 4249 4250 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4251 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4252 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4253 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4254 4255 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4256 .addReg(SrcCond); 4257 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4258 .addImm(0) 4259 .addReg(Src0, 0, AMDGPU::sub0) 4260 .addImm(0) 4261 .addReg(Src1, 0, AMDGPU::sub0) 4262 .addReg(SrcCondCopy); 4263 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4264 .addImm(0) 4265 .addReg(Src0, 0, AMDGPU::sub1) 4266 .addImm(0) 4267 .addReg(Src1, 0, AMDGPU::sub1) 4268 .addReg(SrcCondCopy); 4269 4270 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4271 .addReg(DstLo) 4272 .addImm(AMDGPU::sub0) 4273 .addReg(DstHi) 4274 .addImm(AMDGPU::sub1); 4275 MI.eraseFromParent(); 4276 return BB; 4277 } 4278 case AMDGPU::SI_BR_UNDEF: { 4279 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4280 const DebugLoc &DL = MI.getDebugLoc(); 4281 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4282 .add(MI.getOperand(0)); 4283 Br->getOperand(1).setIsUndef(true); // read undef SCC 4284 MI.eraseFromParent(); 4285 return BB; 4286 } 4287 case AMDGPU::ADJCALLSTACKUP: 4288 case AMDGPU::ADJCALLSTACKDOWN: { 4289 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4290 MachineInstrBuilder MIB(*MF, &MI); 4291 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4292 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 4293 return BB; 4294 } 4295 case AMDGPU::SI_CALL_ISEL: { 4296 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4297 const DebugLoc &DL = MI.getDebugLoc(); 4298 4299 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4300 4301 MachineInstrBuilder MIB; 4302 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4303 4304 for (const MachineOperand &MO : MI.operands()) 4305 MIB.add(MO); 4306 4307 MIB.cloneMemRefs(MI); 4308 MI.eraseFromParent(); 4309 return BB; 4310 } 4311 case AMDGPU::V_ADD_CO_U32_e32: 4312 case AMDGPU::V_SUB_CO_U32_e32: 4313 case AMDGPU::V_SUBREV_CO_U32_e32: { 4314 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4315 const DebugLoc &DL = MI.getDebugLoc(); 4316 unsigned Opc = MI.getOpcode(); 4317 4318 bool NeedClampOperand = false; 4319 if (TII->pseudoToMCOpcode(Opc) == -1) { 4320 Opc = AMDGPU::getVOPe64(Opc); 4321 NeedClampOperand = true; 4322 } 4323 4324 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4325 if (TII->isVOP3(*I)) { 4326 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4327 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4328 I.addReg(TRI->getVCC(), RegState::Define); 4329 } 4330 I.add(MI.getOperand(1)) 4331 .add(MI.getOperand(2)); 4332 if (NeedClampOperand) 4333 I.addImm(0); // clamp bit for e64 encoding 4334 4335 TII->legalizeOperands(*I); 4336 4337 MI.eraseFromParent(); 4338 return BB; 4339 } 4340 case AMDGPU::V_ADDC_U32_e32: 4341 case AMDGPU::V_SUBB_U32_e32: 4342 case AMDGPU::V_SUBBREV_U32_e32: 4343 // These instructions have an implicit use of vcc which counts towards the 4344 // constant bus limit. 4345 TII->legalizeOperands(MI); 4346 return BB; 4347 case AMDGPU::DS_GWS_INIT: 4348 case AMDGPU::DS_GWS_SEMA_BR: 4349 case AMDGPU::DS_GWS_BARRIER: 4350 if (Subtarget->needsAlignedVGPRs()) { 4351 // Add implicit aligned super-reg to force alignment on the data operand. 4352 const DebugLoc &DL = MI.getDebugLoc(); 4353 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4354 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 4355 MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0); 4356 Register DataReg = Op->getReg(); 4357 bool IsAGPR = TRI->isAGPR(MRI, DataReg); 4358 Register Undef = MRI.createVirtualRegister( 4359 IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass); 4360 BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef); 4361 Register NewVR = 4362 MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass 4363 : &AMDGPU::VReg_64_Align2RegClass); 4364 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR) 4365 .addReg(DataReg, 0, Op->getSubReg()) 4366 .addImm(AMDGPU::sub0) 4367 .addReg(Undef) 4368 .addImm(AMDGPU::sub1); 4369 Op->setReg(NewVR); 4370 Op->setSubReg(AMDGPU::sub0); 4371 MI.addOperand(MachineOperand::CreateReg(NewVR, false, true)); 4372 } 4373 LLVM_FALLTHROUGH; 4374 case AMDGPU::DS_GWS_SEMA_V: 4375 case AMDGPU::DS_GWS_SEMA_P: 4376 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4377 // A s_waitcnt 0 is required to be the instruction immediately following. 4378 if (getSubtarget()->hasGWSAutoReplay()) { 4379 bundleInstWithWaitcnt(MI); 4380 return BB; 4381 } 4382 4383 return emitGWSMemViolTestLoop(MI, BB); 4384 case AMDGPU::S_SETREG_B32: { 4385 // Try to optimize cases that only set the denormal mode or rounding mode. 4386 // 4387 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4388 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4389 // instead. 4390 // 4391 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4392 // allow you to have a no side effect instruction in the output of a 4393 // sideeffecting pattern. 4394 unsigned ID, Offset, Width; 4395 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4396 if (ID != AMDGPU::Hwreg::ID_MODE) 4397 return BB; 4398 4399 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4400 const unsigned SetMask = WidthMask << Offset; 4401 4402 if (getSubtarget()->hasDenormModeInst()) { 4403 unsigned SetDenormOp = 0; 4404 unsigned SetRoundOp = 0; 4405 4406 // The dedicated instructions can only set the whole denorm or round mode 4407 // at once, not a subset of bits in either. 4408 if (SetMask == 4409 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4410 // If this fully sets both the round and denorm mode, emit the two 4411 // dedicated instructions for these. 4412 SetRoundOp = AMDGPU::S_ROUND_MODE; 4413 SetDenormOp = AMDGPU::S_DENORM_MODE; 4414 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4415 SetRoundOp = AMDGPU::S_ROUND_MODE; 4416 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4417 SetDenormOp = AMDGPU::S_DENORM_MODE; 4418 } 4419 4420 if (SetRoundOp || SetDenormOp) { 4421 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4422 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4423 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4424 unsigned ImmVal = Def->getOperand(1).getImm(); 4425 if (SetRoundOp) { 4426 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4427 .addImm(ImmVal & 0xf); 4428 4429 // If we also have the denorm mode, get just the denorm mode bits. 4430 ImmVal >>= 4; 4431 } 4432 4433 if (SetDenormOp) { 4434 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4435 .addImm(ImmVal & 0xf); 4436 } 4437 4438 MI.eraseFromParent(); 4439 return BB; 4440 } 4441 } 4442 } 4443 4444 // If only FP bits are touched, used the no side effects pseudo. 4445 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4446 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) 4447 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode)); 4448 4449 return BB; 4450 } 4451 default: 4452 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4453 } 4454 } 4455 4456 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4457 return isTypeLegal(VT.getScalarType()); 4458 } 4459 4460 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4461 // This currently forces unfolding various combinations of fsub into fma with 4462 // free fneg'd operands. As long as we have fast FMA (controlled by 4463 // isFMAFasterThanFMulAndFAdd), we should perform these. 4464 4465 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4466 // most of these combines appear to be cycle neutral but save on instruction 4467 // count / code size. 4468 return true; 4469 } 4470 4471 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; } 4472 4473 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4474 EVT VT) const { 4475 if (!VT.isVector()) { 4476 return MVT::i1; 4477 } 4478 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4479 } 4480 4481 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4482 // TODO: Should i16 be used always if legal? For now it would force VALU 4483 // shifts. 4484 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4485 } 4486 4487 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4488 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4489 ? Ty.changeElementSize(16) 4490 : Ty.changeElementSize(32); 4491 } 4492 4493 // Answering this is somewhat tricky and depends on the specific device which 4494 // have different rates for fma or all f64 operations. 4495 // 4496 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4497 // regardless of which device (although the number of cycles differs between 4498 // devices), so it is always profitable for f64. 4499 // 4500 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4501 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4502 // which we can always do even without fused FP ops since it returns the same 4503 // result as the separate operations and since it is always full 4504 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4505 // however does not support denormals, so we do report fma as faster if we have 4506 // a fast fma device and require denormals. 4507 // 4508 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4509 EVT VT) const { 4510 VT = VT.getScalarType(); 4511 4512 switch (VT.getSimpleVT().SimpleTy) { 4513 case MVT::f32: { 4514 // If mad is not available this depends only on if f32 fma is full rate. 4515 if (!Subtarget->hasMadMacF32Insts()) 4516 return Subtarget->hasFastFMAF32(); 4517 4518 // Otherwise f32 mad is always full rate and returns the same result as 4519 // the separate operations so should be preferred over fma. 4520 // However does not support denomals. 4521 if (hasFP32Denormals(MF)) 4522 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4523 4524 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4525 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4526 } 4527 case MVT::f64: 4528 return true; 4529 case MVT::f16: 4530 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4531 default: 4532 break; 4533 } 4534 4535 return false; 4536 } 4537 4538 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4539 LLT Ty) const { 4540 switch (Ty.getScalarSizeInBits()) { 4541 case 16: 4542 return isFMAFasterThanFMulAndFAdd(MF, MVT::f16); 4543 case 32: 4544 return isFMAFasterThanFMulAndFAdd(MF, MVT::f32); 4545 case 64: 4546 return isFMAFasterThanFMulAndFAdd(MF, MVT::f64); 4547 default: 4548 break; 4549 } 4550 4551 return false; 4552 } 4553 4554 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const { 4555 if (!Ty.isScalar()) 4556 return false; 4557 4558 if (Ty.getScalarSizeInBits() == 16) 4559 return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF()); 4560 if (Ty.getScalarSizeInBits() == 32) 4561 return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF()); 4562 4563 return false; 4564 } 4565 4566 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4567 const SDNode *N) const { 4568 // TODO: Check future ftz flag 4569 // v_mad_f32/v_mac_f32 do not support denormals. 4570 EVT VT = N->getValueType(0); 4571 if (VT == MVT::f32) 4572 return Subtarget->hasMadMacF32Insts() && 4573 !hasFP32Denormals(DAG.getMachineFunction()); 4574 if (VT == MVT::f16) { 4575 return Subtarget->hasMadF16() && 4576 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4577 } 4578 4579 return false; 4580 } 4581 4582 //===----------------------------------------------------------------------===// 4583 // Custom DAG Lowering Operations 4584 //===----------------------------------------------------------------------===// 4585 4586 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4587 // wider vector type is legal. 4588 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4589 SelectionDAG &DAG) const { 4590 unsigned Opc = Op.getOpcode(); 4591 EVT VT = Op.getValueType(); 4592 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4593 4594 SDValue Lo, Hi; 4595 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4596 4597 SDLoc SL(Op); 4598 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4599 Op->getFlags()); 4600 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4601 Op->getFlags()); 4602 4603 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4604 } 4605 4606 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4607 // wider vector type is legal. 4608 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4609 SelectionDAG &DAG) const { 4610 unsigned Opc = Op.getOpcode(); 4611 EVT VT = Op.getValueType(); 4612 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4613 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32); 4614 4615 SDValue Lo0, Hi0; 4616 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4617 SDValue Lo1, Hi1; 4618 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4619 4620 SDLoc SL(Op); 4621 4622 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4623 Op->getFlags()); 4624 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4625 Op->getFlags()); 4626 4627 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4628 } 4629 4630 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4631 SelectionDAG &DAG) const { 4632 unsigned Opc = Op.getOpcode(); 4633 EVT VT = Op.getValueType(); 4634 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4635 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32); 4636 4637 SDValue Lo0, Hi0; 4638 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4639 SDValue Lo1, Hi1; 4640 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4641 SDValue Lo2, Hi2; 4642 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4643 4644 SDLoc SL(Op); 4645 4646 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4647 Op->getFlags()); 4648 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4649 Op->getFlags()); 4650 4651 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4652 } 4653 4654 4655 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4656 switch (Op.getOpcode()) { 4657 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4658 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4659 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4660 case ISD::LOAD: { 4661 SDValue Result = LowerLOAD(Op, DAG); 4662 assert((!Result.getNode() || 4663 Result.getNode()->getNumValues() == 2) && 4664 "Load should return a value and a chain"); 4665 return Result; 4666 } 4667 4668 case ISD::FSIN: 4669 case ISD::FCOS: 4670 return LowerTrig(Op, DAG); 4671 case ISD::SELECT: return LowerSELECT(Op, DAG); 4672 case ISD::FDIV: return LowerFDIV(Op, DAG); 4673 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4674 case ISD::STORE: return LowerSTORE(Op, DAG); 4675 case ISD::GlobalAddress: { 4676 MachineFunction &MF = DAG.getMachineFunction(); 4677 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4678 return LowerGlobalAddress(MFI, Op, DAG); 4679 } 4680 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4681 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4682 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4683 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4684 case ISD::INSERT_SUBVECTOR: 4685 return lowerINSERT_SUBVECTOR(Op, DAG); 4686 case ISD::INSERT_VECTOR_ELT: 4687 return lowerINSERT_VECTOR_ELT(Op, DAG); 4688 case ISD::EXTRACT_VECTOR_ELT: 4689 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4690 case ISD::VECTOR_SHUFFLE: 4691 return lowerVECTOR_SHUFFLE(Op, DAG); 4692 case ISD::BUILD_VECTOR: 4693 return lowerBUILD_VECTOR(Op, DAG); 4694 case ISD::FP_ROUND: 4695 return lowerFP_ROUND(Op, DAG); 4696 case ISD::TRAP: 4697 return lowerTRAP(Op, DAG); 4698 case ISD::DEBUGTRAP: 4699 return lowerDEBUGTRAP(Op, DAG); 4700 case ISD::FABS: 4701 case ISD::FNEG: 4702 case ISD::FCANONICALIZE: 4703 case ISD::BSWAP: 4704 return splitUnaryVectorOp(Op, DAG); 4705 case ISD::FMINNUM: 4706 case ISD::FMAXNUM: 4707 return lowerFMINNUM_FMAXNUM(Op, DAG); 4708 case ISD::FMA: 4709 return splitTernaryVectorOp(Op, DAG); 4710 case ISD::FP_TO_SINT: 4711 case ISD::FP_TO_UINT: 4712 return LowerFP_TO_INT(Op, DAG); 4713 case ISD::SHL: 4714 case ISD::SRA: 4715 case ISD::SRL: 4716 case ISD::ADD: 4717 case ISD::SUB: 4718 case ISD::MUL: 4719 case ISD::SMIN: 4720 case ISD::SMAX: 4721 case ISD::UMIN: 4722 case ISD::UMAX: 4723 case ISD::FADD: 4724 case ISD::FMUL: 4725 case ISD::FMINNUM_IEEE: 4726 case ISD::FMAXNUM_IEEE: 4727 case ISD::UADDSAT: 4728 case ISD::USUBSAT: 4729 case ISD::SADDSAT: 4730 case ISD::SSUBSAT: 4731 return splitBinaryVectorOp(Op, DAG); 4732 case ISD::SMULO: 4733 case ISD::UMULO: 4734 return lowerXMULO(Op, DAG); 4735 case ISD::SMUL_LOHI: 4736 case ISD::UMUL_LOHI: 4737 return lowerXMUL_LOHI(Op, DAG); 4738 case ISD::DYNAMIC_STACKALLOC: 4739 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4740 } 4741 return SDValue(); 4742 } 4743 4744 // Used for D16: Casts the result of an instruction into the right vector, 4745 // packs values if loads return unpacked values. 4746 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4747 const SDLoc &DL, 4748 SelectionDAG &DAG, bool Unpacked) { 4749 if (!LoadVT.isVector()) 4750 return Result; 4751 4752 // Cast back to the original packed type or to a larger type that is a 4753 // multiple of 32 bit for D16. Widening the return type is a required for 4754 // legalization. 4755 EVT FittingLoadVT = LoadVT; 4756 if ((LoadVT.getVectorNumElements() % 2) == 1) { 4757 FittingLoadVT = 4758 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4759 LoadVT.getVectorNumElements() + 1); 4760 } 4761 4762 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4763 // Truncate to v2i16/v4i16. 4764 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger(); 4765 4766 // Workaround legalizer not scalarizing truncate after vector op 4767 // legalization but not creating intermediate vector trunc. 4768 SmallVector<SDValue, 4> Elts; 4769 DAG.ExtractVectorElements(Result, Elts); 4770 for (SDValue &Elt : Elts) 4771 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4772 4773 // Pad illegal v1i16/v3fi6 to v4i16 4774 if ((LoadVT.getVectorNumElements() % 2) == 1) 4775 Elts.push_back(DAG.getUNDEF(MVT::i16)); 4776 4777 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4778 4779 // Bitcast to original type (v2f16/v4f16). 4780 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4781 } 4782 4783 // Cast back to the original packed type. 4784 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4785 } 4786 4787 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4788 MemSDNode *M, 4789 SelectionDAG &DAG, 4790 ArrayRef<SDValue> Ops, 4791 bool IsIntrinsic) const { 4792 SDLoc DL(M); 4793 4794 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4795 EVT LoadVT = M->getValueType(0); 4796 4797 EVT EquivLoadVT = LoadVT; 4798 if (LoadVT.isVector()) { 4799 if (Unpacked) { 4800 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4801 LoadVT.getVectorNumElements()); 4802 } else if ((LoadVT.getVectorNumElements() % 2) == 1) { 4803 // Widen v3f16 to legal type 4804 EquivLoadVT = 4805 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4806 LoadVT.getVectorNumElements() + 1); 4807 } 4808 } 4809 4810 // Change from v4f16/v2f16 to EquivLoadVT. 4811 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4812 4813 SDValue Load 4814 = DAG.getMemIntrinsicNode( 4815 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4816 VTList, Ops, M->getMemoryVT(), 4817 M->getMemOperand()); 4818 4819 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4820 4821 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4822 } 4823 4824 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4825 SelectionDAG &DAG, 4826 ArrayRef<SDValue> Ops) const { 4827 SDLoc DL(M); 4828 EVT LoadVT = M->getValueType(0); 4829 EVT EltType = LoadVT.getScalarType(); 4830 EVT IntVT = LoadVT.changeTypeToInteger(); 4831 4832 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4833 4834 unsigned Opc = 4835 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4836 4837 if (IsD16) { 4838 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4839 } 4840 4841 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4842 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4843 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4844 4845 if (isTypeLegal(LoadVT)) { 4846 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4847 M->getMemOperand(), DAG); 4848 } 4849 4850 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4851 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4852 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4853 M->getMemOperand(), DAG); 4854 return DAG.getMergeValues( 4855 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4856 DL); 4857 } 4858 4859 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4860 SDNode *N, SelectionDAG &DAG) { 4861 EVT VT = N->getValueType(0); 4862 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4863 unsigned CondCode = CD->getZExtValue(); 4864 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4865 return DAG.getUNDEF(VT); 4866 4867 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4868 4869 SDValue LHS = N->getOperand(1); 4870 SDValue RHS = N->getOperand(2); 4871 4872 SDLoc DL(N); 4873 4874 EVT CmpVT = LHS.getValueType(); 4875 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4876 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4877 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4878 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4879 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4880 } 4881 4882 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4883 4884 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4885 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4886 4887 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4888 DAG.getCondCode(CCOpcode)); 4889 if (VT.bitsEq(CCVT)) 4890 return SetCC; 4891 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4892 } 4893 4894 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4895 SDNode *N, SelectionDAG &DAG) { 4896 EVT VT = N->getValueType(0); 4897 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4898 4899 unsigned CondCode = CD->getZExtValue(); 4900 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4901 return DAG.getUNDEF(VT); 4902 4903 SDValue Src0 = N->getOperand(1); 4904 SDValue Src1 = N->getOperand(2); 4905 EVT CmpVT = Src0.getValueType(); 4906 SDLoc SL(N); 4907 4908 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4909 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4910 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4911 } 4912 4913 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4914 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4915 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4916 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4917 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4918 Src1, DAG.getCondCode(CCOpcode)); 4919 if (VT.bitsEq(CCVT)) 4920 return SetCC; 4921 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4922 } 4923 4924 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4925 SelectionDAG &DAG) { 4926 EVT VT = N->getValueType(0); 4927 SDValue Src = N->getOperand(1); 4928 SDLoc SL(N); 4929 4930 if (Src.getOpcode() == ISD::SETCC) { 4931 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4932 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4933 Src.getOperand(1), Src.getOperand(2)); 4934 } 4935 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4936 // (ballot 0) -> 0 4937 if (Arg->isZero()) 4938 return DAG.getConstant(0, SL, VT); 4939 4940 // (ballot 1) -> EXEC/EXEC_LO 4941 if (Arg->isOne()) { 4942 Register Exec; 4943 if (VT.getScalarSizeInBits() == 32) 4944 Exec = AMDGPU::EXEC_LO; 4945 else if (VT.getScalarSizeInBits() == 64) 4946 Exec = AMDGPU::EXEC; 4947 else 4948 return SDValue(); 4949 4950 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4951 } 4952 } 4953 4954 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4955 // ISD::SETNE) 4956 return DAG.getNode( 4957 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4958 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4959 } 4960 4961 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4962 SmallVectorImpl<SDValue> &Results, 4963 SelectionDAG &DAG) const { 4964 switch (N->getOpcode()) { 4965 case ISD::INSERT_VECTOR_ELT: { 4966 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4967 Results.push_back(Res); 4968 return; 4969 } 4970 case ISD::EXTRACT_VECTOR_ELT: { 4971 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4972 Results.push_back(Res); 4973 return; 4974 } 4975 case ISD::INTRINSIC_WO_CHAIN: { 4976 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4977 switch (IID) { 4978 case Intrinsic::amdgcn_cvt_pkrtz: { 4979 SDValue Src0 = N->getOperand(1); 4980 SDValue Src1 = N->getOperand(2); 4981 SDLoc SL(N); 4982 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4983 Src0, Src1); 4984 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4985 return; 4986 } 4987 case Intrinsic::amdgcn_cvt_pknorm_i16: 4988 case Intrinsic::amdgcn_cvt_pknorm_u16: 4989 case Intrinsic::amdgcn_cvt_pk_i16: 4990 case Intrinsic::amdgcn_cvt_pk_u16: { 4991 SDValue Src0 = N->getOperand(1); 4992 SDValue Src1 = N->getOperand(2); 4993 SDLoc SL(N); 4994 unsigned Opcode; 4995 4996 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4997 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4998 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4999 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 5000 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 5001 Opcode = AMDGPUISD::CVT_PK_I16_I32; 5002 else 5003 Opcode = AMDGPUISD::CVT_PK_U16_U32; 5004 5005 EVT VT = N->getValueType(0); 5006 if (isTypeLegal(VT)) 5007 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 5008 else { 5009 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 5010 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 5011 } 5012 return; 5013 } 5014 } 5015 break; 5016 } 5017 case ISD::INTRINSIC_W_CHAIN: { 5018 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 5019 if (Res.getOpcode() == ISD::MERGE_VALUES) { 5020 // FIXME: Hacky 5021 for (unsigned I = 0; I < Res.getNumOperands(); I++) { 5022 Results.push_back(Res.getOperand(I)); 5023 } 5024 } else { 5025 Results.push_back(Res); 5026 Results.push_back(Res.getValue(1)); 5027 } 5028 return; 5029 } 5030 5031 break; 5032 } 5033 case ISD::SELECT: { 5034 SDLoc SL(N); 5035 EVT VT = N->getValueType(0); 5036 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 5037 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 5038 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 5039 5040 EVT SelectVT = NewVT; 5041 if (NewVT.bitsLT(MVT::i32)) { 5042 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 5043 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 5044 SelectVT = MVT::i32; 5045 } 5046 5047 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 5048 N->getOperand(0), LHS, RHS); 5049 5050 if (NewVT != SelectVT) 5051 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 5052 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 5053 return; 5054 } 5055 case ISD::FNEG: { 5056 if (N->getValueType(0) != MVT::v2f16) 5057 break; 5058 5059 SDLoc SL(N); 5060 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 5061 5062 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 5063 BC, 5064 DAG.getConstant(0x80008000, SL, MVT::i32)); 5065 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 5066 return; 5067 } 5068 case ISD::FABS: { 5069 if (N->getValueType(0) != MVT::v2f16) 5070 break; 5071 5072 SDLoc SL(N); 5073 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 5074 5075 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 5076 BC, 5077 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 5078 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 5079 return; 5080 } 5081 default: 5082 break; 5083 } 5084 } 5085 5086 /// Helper function for LowerBRCOND 5087 static SDNode *findUser(SDValue Value, unsigned Opcode) { 5088 5089 SDNode *Parent = Value.getNode(); 5090 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 5091 I != E; ++I) { 5092 5093 if (I.getUse().get() != Value) 5094 continue; 5095 5096 if (I->getOpcode() == Opcode) 5097 return *I; 5098 } 5099 return nullptr; 5100 } 5101 5102 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 5103 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 5104 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 5105 case Intrinsic::amdgcn_if: 5106 return AMDGPUISD::IF; 5107 case Intrinsic::amdgcn_else: 5108 return AMDGPUISD::ELSE; 5109 case Intrinsic::amdgcn_loop: 5110 return AMDGPUISD::LOOP; 5111 case Intrinsic::amdgcn_end_cf: 5112 llvm_unreachable("should not occur"); 5113 default: 5114 return 0; 5115 } 5116 } 5117 5118 // break, if_break, else_break are all only used as inputs to loop, not 5119 // directly as branch conditions. 5120 return 0; 5121 } 5122 5123 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 5124 const Triple &TT = getTargetMachine().getTargetTriple(); 5125 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5126 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5127 AMDGPU::shouldEmitConstantsToTextSection(TT); 5128 } 5129 5130 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 5131 // FIXME: Either avoid relying on address space here or change the default 5132 // address space for functions to avoid the explicit check. 5133 return (GV->getValueType()->isFunctionTy() || 5134 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 5135 !shouldEmitFixup(GV) && 5136 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 5137 } 5138 5139 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 5140 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 5141 } 5142 5143 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 5144 if (!GV->hasExternalLinkage()) 5145 return true; 5146 5147 const auto OS = getTargetMachine().getTargetTriple().getOS(); 5148 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 5149 } 5150 5151 /// This transforms the control flow intrinsics to get the branch destination as 5152 /// last parameter, also switches branch target with BR if the need arise 5153 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 5154 SelectionDAG &DAG) const { 5155 SDLoc DL(BRCOND); 5156 5157 SDNode *Intr = BRCOND.getOperand(1).getNode(); 5158 SDValue Target = BRCOND.getOperand(2); 5159 SDNode *BR = nullptr; 5160 SDNode *SetCC = nullptr; 5161 5162 if (Intr->getOpcode() == ISD::SETCC) { 5163 // As long as we negate the condition everything is fine 5164 SetCC = Intr; 5165 Intr = SetCC->getOperand(0).getNode(); 5166 5167 } else { 5168 // Get the target from BR if we don't negate the condition 5169 BR = findUser(BRCOND, ISD::BR); 5170 assert(BR && "brcond missing unconditional branch user"); 5171 Target = BR->getOperand(1); 5172 } 5173 5174 unsigned CFNode = isCFIntrinsic(Intr); 5175 if (CFNode == 0) { 5176 // This is a uniform branch so we don't need to legalize. 5177 return BRCOND; 5178 } 5179 5180 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 5181 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 5182 5183 assert(!SetCC || 5184 (SetCC->getConstantOperandVal(1) == 1 && 5185 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 5186 ISD::SETNE)); 5187 5188 // operands of the new intrinsic call 5189 SmallVector<SDValue, 4> Ops; 5190 if (HaveChain) 5191 Ops.push_back(BRCOND.getOperand(0)); 5192 5193 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 5194 Ops.push_back(Target); 5195 5196 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 5197 5198 // build the new intrinsic call 5199 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 5200 5201 if (!HaveChain) { 5202 SDValue Ops[] = { 5203 SDValue(Result, 0), 5204 BRCOND.getOperand(0) 5205 }; 5206 5207 Result = DAG.getMergeValues(Ops, DL).getNode(); 5208 } 5209 5210 if (BR) { 5211 // Give the branch instruction our target 5212 SDValue Ops[] = { 5213 BR->getOperand(0), 5214 BRCOND.getOperand(2) 5215 }; 5216 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5217 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5218 } 5219 5220 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5221 5222 // Copy the intrinsic results to registers 5223 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5224 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5225 if (!CopyToReg) 5226 continue; 5227 5228 Chain = DAG.getCopyToReg( 5229 Chain, DL, 5230 CopyToReg->getOperand(1), 5231 SDValue(Result, i - 1), 5232 SDValue()); 5233 5234 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5235 } 5236 5237 // Remove the old intrinsic from the chain 5238 DAG.ReplaceAllUsesOfValueWith( 5239 SDValue(Intr, Intr->getNumValues() - 1), 5240 Intr->getOperand(0)); 5241 5242 return Chain; 5243 } 5244 5245 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5246 SelectionDAG &DAG) const { 5247 MVT VT = Op.getSimpleValueType(); 5248 SDLoc DL(Op); 5249 // Checking the depth 5250 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5251 return DAG.getConstant(0, DL, VT); 5252 5253 MachineFunction &MF = DAG.getMachineFunction(); 5254 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5255 // Check for kernel and shader functions 5256 if (Info->isEntryFunction()) 5257 return DAG.getConstant(0, DL, VT); 5258 5259 MachineFrameInfo &MFI = MF.getFrameInfo(); 5260 // There is a call to @llvm.returnaddress in this function 5261 MFI.setReturnAddressIsTaken(true); 5262 5263 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5264 // Get the return address reg and mark it as an implicit live-in 5265 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5266 5267 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5268 } 5269 5270 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5271 SDValue Op, 5272 const SDLoc &DL, 5273 EVT VT) const { 5274 return Op.getValueType().bitsLE(VT) ? 5275 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5276 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5277 DAG.getTargetConstant(0, DL, MVT::i32)); 5278 } 5279 5280 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5281 assert(Op.getValueType() == MVT::f16 && 5282 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5283 5284 SDValue Src = Op.getOperand(0); 5285 EVT SrcVT = Src.getValueType(); 5286 if (SrcVT != MVT::f64) 5287 return Op; 5288 5289 SDLoc DL(Op); 5290 5291 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5292 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5293 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5294 } 5295 5296 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5297 SelectionDAG &DAG) const { 5298 EVT VT = Op.getValueType(); 5299 const MachineFunction &MF = DAG.getMachineFunction(); 5300 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5301 bool IsIEEEMode = Info->getMode().IEEE; 5302 5303 // FIXME: Assert during selection that this is only selected for 5304 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5305 // mode functions, but this happens to be OK since it's only done in cases 5306 // where there is known no sNaN. 5307 if (IsIEEEMode) 5308 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5309 5310 if (VT == MVT::v4f16) 5311 return splitBinaryVectorOp(Op, DAG); 5312 return Op; 5313 } 5314 5315 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5316 EVT VT = Op.getValueType(); 5317 SDLoc SL(Op); 5318 SDValue LHS = Op.getOperand(0); 5319 SDValue RHS = Op.getOperand(1); 5320 bool isSigned = Op.getOpcode() == ISD::SMULO; 5321 5322 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5323 const APInt &C = RHSC->getAPIntValue(); 5324 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5325 if (C.isPowerOf2()) { 5326 // smulo(x, signed_min) is same as umulo(x, signed_min). 5327 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5328 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5329 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5330 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5331 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5332 SL, VT, Result, ShiftAmt), 5333 LHS, ISD::SETNE); 5334 return DAG.getMergeValues({ Result, Overflow }, SL); 5335 } 5336 } 5337 5338 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5339 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5340 SL, VT, LHS, RHS); 5341 5342 SDValue Sign = isSigned 5343 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5344 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5345 : DAG.getConstant(0, SL, VT); 5346 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5347 5348 return DAG.getMergeValues({ Result, Overflow }, SL); 5349 } 5350 5351 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const { 5352 if (Op->isDivergent()) { 5353 // Select to V_MAD_[IU]64_[IU]32. 5354 return Op; 5355 } 5356 if (Subtarget->hasSMulHi()) { 5357 // Expand to S_MUL_I32 + S_MUL_HI_[IU]32. 5358 return SDValue(); 5359 } 5360 // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to 5361 // calculate the high part, so we might as well do the whole thing with 5362 // V_MAD_[IU]64_[IU]32. 5363 return Op; 5364 } 5365 5366 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5367 if (!Subtarget->isTrapHandlerEnabled() || 5368 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) 5369 return lowerTrapEndpgm(Op, DAG); 5370 5371 if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) { 5372 switch (*HsaAbiVer) { 5373 case ELF::ELFABIVERSION_AMDGPU_HSA_V2: 5374 case ELF::ELFABIVERSION_AMDGPU_HSA_V3: 5375 return lowerTrapHsaQueuePtr(Op, DAG); 5376 case ELF::ELFABIVERSION_AMDGPU_HSA_V4: 5377 return Subtarget->supportsGetDoorbellID() ? 5378 lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG); 5379 } 5380 } 5381 5382 llvm_unreachable("Unknown trap handler"); 5383 } 5384 5385 SDValue SITargetLowering::lowerTrapEndpgm( 5386 SDValue Op, SelectionDAG &DAG) const { 5387 SDLoc SL(Op); 5388 SDValue Chain = Op.getOperand(0); 5389 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5390 } 5391 5392 SDValue SITargetLowering::lowerTrapHsaQueuePtr( 5393 SDValue Op, SelectionDAG &DAG) const { 5394 SDLoc SL(Op); 5395 SDValue Chain = Op.getOperand(0); 5396 5397 MachineFunction &MF = DAG.getMachineFunction(); 5398 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5399 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5400 5401 SDValue QueuePtr; 5402 if (UserSGPR == AMDGPU::NoRegister) { 5403 // We probably are in a function incorrectly marked with 5404 // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the trap, 5405 // so just use a null pointer. 5406 QueuePtr = DAG.getConstant(0, SL, MVT::i64); 5407 } else { 5408 QueuePtr = CreateLiveInRegister( 5409 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5410 } 5411 5412 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5413 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5414 QueuePtr, SDValue()); 5415 5416 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5417 SDValue Ops[] = { 5418 ToReg, 5419 DAG.getTargetConstant(TrapID, SL, MVT::i16), 5420 SGPR01, 5421 ToReg.getValue(1) 5422 }; 5423 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5424 } 5425 5426 SDValue SITargetLowering::lowerTrapHsa( 5427 SDValue Op, SelectionDAG &DAG) const { 5428 SDLoc SL(Op); 5429 SDValue Chain = Op.getOperand(0); 5430 5431 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5432 SDValue Ops[] = { 5433 Chain, 5434 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5435 }; 5436 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5437 } 5438 5439 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5440 SDLoc SL(Op); 5441 SDValue Chain = Op.getOperand(0); 5442 MachineFunction &MF = DAG.getMachineFunction(); 5443 5444 if (!Subtarget->isTrapHandlerEnabled() || 5445 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) { 5446 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5447 "debugtrap handler not supported", 5448 Op.getDebugLoc(), 5449 DS_Warning); 5450 LLVMContext &Ctx = MF.getFunction().getContext(); 5451 Ctx.diagnose(NoTrap); 5452 return Chain; 5453 } 5454 5455 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap); 5456 SDValue Ops[] = { 5457 Chain, 5458 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5459 }; 5460 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5461 } 5462 5463 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5464 SelectionDAG &DAG) const { 5465 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5466 if (Subtarget->hasApertureRegs()) { 5467 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5468 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5469 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5470 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5471 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5472 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5473 unsigned Encoding = 5474 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5475 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5476 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5477 5478 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5479 SDValue ApertureReg = SDValue( 5480 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5481 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5482 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5483 } 5484 5485 MachineFunction &MF = DAG.getMachineFunction(); 5486 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5487 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5488 if (UserSGPR == AMDGPU::NoRegister) { 5489 // We probably are in a function incorrectly marked with 5490 // amdgpu-no-queue-ptr. This is undefined. 5491 return DAG.getUNDEF(MVT::i32); 5492 } 5493 5494 SDValue QueuePtr = CreateLiveInRegister( 5495 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5496 5497 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5498 // private_segment_aperture_base_hi. 5499 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5500 5501 SDValue Ptr = 5502 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5503 5504 // TODO: Use custom target PseudoSourceValue. 5505 // TODO: We should use the value from the IR intrinsic call, but it might not 5506 // be available and how do we get it? 5507 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5508 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5509 commonAlignment(Align(64), StructOffset), 5510 MachineMemOperand::MODereferenceable | 5511 MachineMemOperand::MOInvariant); 5512 } 5513 5514 /// Return true if the value is a known valid address, such that a null check is 5515 /// not necessary. 5516 static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG, 5517 const AMDGPUTargetMachine &TM, unsigned AddrSpace) { 5518 if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) || 5519 isa<BasicBlockSDNode>(Val)) 5520 return true; 5521 5522 if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val)) 5523 return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace); 5524 5525 // TODO: Search through arithmetic, handle arguments and loads 5526 // marked nonnull. 5527 return false; 5528 } 5529 5530 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5531 SelectionDAG &DAG) const { 5532 SDLoc SL(Op); 5533 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5534 5535 SDValue Src = ASC->getOperand(0); 5536 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5537 unsigned SrcAS = ASC->getSrcAddressSpace(); 5538 5539 const AMDGPUTargetMachine &TM = 5540 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5541 5542 // flat -> local/private 5543 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) { 5544 unsigned DestAS = ASC->getDestAddressSpace(); 5545 5546 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5547 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5548 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5549 5550 if (isKnownNonNull(Src, DAG, TM, SrcAS)) 5551 return Ptr; 5552 5553 unsigned NullVal = TM.getNullPointerValue(DestAS); 5554 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5555 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5556 5557 return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr, 5558 SegmentNullPtr); 5559 } 5560 } 5561 5562 // local/private -> flat 5563 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5564 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5565 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5566 5567 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5568 SDValue CvtPtr = 5569 DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5570 CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr); 5571 5572 if (isKnownNonNull(Src, DAG, TM, SrcAS)) 5573 return CvtPtr; 5574 5575 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5576 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5577 5578 SDValue NonNull 5579 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5580 5581 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr, 5582 FlatNullPtr); 5583 } 5584 } 5585 5586 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5587 Src.getValueType() == MVT::i64) 5588 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5589 5590 // global <-> flat are no-ops and never emitted. 5591 5592 const MachineFunction &MF = DAG.getMachineFunction(); 5593 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5594 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5595 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5596 5597 return DAG.getUNDEF(ASC->getValueType(0)); 5598 } 5599 5600 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5601 // the small vector and inserting them into the big vector. That is better than 5602 // the default expansion of doing it via a stack slot. Even though the use of 5603 // the stack slot would be optimized away afterwards, the stack slot itself 5604 // remains. 5605 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5606 SelectionDAG &DAG) const { 5607 SDValue Vec = Op.getOperand(0); 5608 SDValue Ins = Op.getOperand(1); 5609 SDValue Idx = Op.getOperand(2); 5610 EVT VecVT = Vec.getValueType(); 5611 EVT InsVT = Ins.getValueType(); 5612 EVT EltVT = VecVT.getVectorElementType(); 5613 unsigned InsNumElts = InsVT.getVectorNumElements(); 5614 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5615 SDLoc SL(Op); 5616 5617 for (unsigned I = 0; I != InsNumElts; ++I) { 5618 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5619 DAG.getConstant(I, SL, MVT::i32)); 5620 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5621 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5622 } 5623 return Vec; 5624 } 5625 5626 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5627 SelectionDAG &DAG) const { 5628 SDValue Vec = Op.getOperand(0); 5629 SDValue InsVal = Op.getOperand(1); 5630 SDValue Idx = Op.getOperand(2); 5631 EVT VecVT = Vec.getValueType(); 5632 EVT EltVT = VecVT.getVectorElementType(); 5633 unsigned VecSize = VecVT.getSizeInBits(); 5634 unsigned EltSize = EltVT.getSizeInBits(); 5635 5636 5637 assert(VecSize <= 64); 5638 5639 unsigned NumElts = VecVT.getVectorNumElements(); 5640 SDLoc SL(Op); 5641 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5642 5643 if (NumElts == 4 && EltSize == 16 && KIdx) { 5644 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5645 5646 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5647 DAG.getConstant(0, SL, MVT::i32)); 5648 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5649 DAG.getConstant(1, SL, MVT::i32)); 5650 5651 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5652 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5653 5654 unsigned Idx = KIdx->getZExtValue(); 5655 bool InsertLo = Idx < 2; 5656 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5657 InsertLo ? LoVec : HiVec, 5658 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5659 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5660 5661 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5662 5663 SDValue Concat = InsertLo ? 5664 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5665 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5666 5667 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5668 } 5669 5670 if (isa<ConstantSDNode>(Idx)) 5671 return SDValue(); 5672 5673 MVT IntVT = MVT::getIntegerVT(VecSize); 5674 5675 // Avoid stack access for dynamic indexing. 5676 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5677 5678 // Create a congruent vector with the target value in each element so that 5679 // the required element can be masked and ORed into the target vector. 5680 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5681 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5682 5683 assert(isPowerOf2_32(EltSize)); 5684 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5685 5686 // Convert vector index to bit-index. 5687 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5688 5689 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5690 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5691 DAG.getConstant(0xffff, SL, IntVT), 5692 ScaledIdx); 5693 5694 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5695 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5696 DAG.getNOT(SL, BFM, IntVT), BCVec); 5697 5698 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5699 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5700 } 5701 5702 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5703 SelectionDAG &DAG) const { 5704 SDLoc SL(Op); 5705 5706 EVT ResultVT = Op.getValueType(); 5707 SDValue Vec = Op.getOperand(0); 5708 SDValue Idx = Op.getOperand(1); 5709 EVT VecVT = Vec.getValueType(); 5710 unsigned VecSize = VecVT.getSizeInBits(); 5711 EVT EltVT = VecVT.getVectorElementType(); 5712 assert(VecSize <= 64); 5713 5714 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5715 5716 // Make sure we do any optimizations that will make it easier to fold 5717 // source modifiers before obscuring it with bit operations. 5718 5719 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5720 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5721 return Combined; 5722 5723 unsigned EltSize = EltVT.getSizeInBits(); 5724 assert(isPowerOf2_32(EltSize)); 5725 5726 MVT IntVT = MVT::getIntegerVT(VecSize); 5727 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5728 5729 // Convert vector index to bit-index (* EltSize) 5730 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5731 5732 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5733 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5734 5735 if (ResultVT == MVT::f16) { 5736 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5737 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5738 } 5739 5740 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5741 } 5742 5743 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5744 assert(Elt % 2 == 0); 5745 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5746 } 5747 5748 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5749 SelectionDAG &DAG) const { 5750 SDLoc SL(Op); 5751 EVT ResultVT = Op.getValueType(); 5752 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5753 5754 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5755 EVT EltVT = PackVT.getVectorElementType(); 5756 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5757 5758 // vector_shuffle <0,1,6,7> lhs, rhs 5759 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5760 // 5761 // vector_shuffle <6,7,2,3> lhs, rhs 5762 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5763 // 5764 // vector_shuffle <6,7,0,1> lhs, rhs 5765 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5766 5767 // Avoid scalarizing when both halves are reading from consecutive elements. 5768 SmallVector<SDValue, 4> Pieces; 5769 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5770 if (elementPairIsContiguous(SVN->getMask(), I)) { 5771 const int Idx = SVN->getMaskElt(I); 5772 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5773 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5774 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5775 PackVT, SVN->getOperand(VecIdx), 5776 DAG.getConstant(EltIdx, SL, MVT::i32)); 5777 Pieces.push_back(SubVec); 5778 } else { 5779 const int Idx0 = SVN->getMaskElt(I); 5780 const int Idx1 = SVN->getMaskElt(I + 1); 5781 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5782 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5783 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5784 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5785 5786 SDValue Vec0 = SVN->getOperand(VecIdx0); 5787 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5788 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5789 5790 SDValue Vec1 = SVN->getOperand(VecIdx1); 5791 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5792 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5793 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5794 } 5795 } 5796 5797 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5798 } 5799 5800 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5801 SelectionDAG &DAG) const { 5802 SDLoc SL(Op); 5803 EVT VT = Op.getValueType(); 5804 5805 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5806 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5807 5808 // Turn into pair of packed build_vectors. 5809 // TODO: Special case for constants that can be materialized with s_mov_b64. 5810 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5811 { Op.getOperand(0), Op.getOperand(1) }); 5812 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5813 { Op.getOperand(2), Op.getOperand(3) }); 5814 5815 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5816 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5817 5818 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5819 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5820 } 5821 5822 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5823 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5824 5825 SDValue Lo = Op.getOperand(0); 5826 SDValue Hi = Op.getOperand(1); 5827 5828 // Avoid adding defined bits with the zero_extend. 5829 if (Hi.isUndef()) { 5830 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5831 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5832 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5833 } 5834 5835 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5836 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5837 5838 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5839 DAG.getConstant(16, SL, MVT::i32)); 5840 if (Lo.isUndef()) 5841 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5842 5843 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5844 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5845 5846 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5847 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5848 } 5849 5850 bool 5851 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5852 // We can fold offsets for anything that doesn't require a GOT relocation. 5853 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5854 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5855 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5856 !shouldEmitGOTReloc(GA->getGlobal()); 5857 } 5858 5859 static SDValue 5860 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5861 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5862 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5863 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5864 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5865 // lowered to the following code sequence: 5866 // 5867 // For constant address space: 5868 // s_getpc_b64 s[0:1] 5869 // s_add_u32 s0, s0, $symbol 5870 // s_addc_u32 s1, s1, 0 5871 // 5872 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5873 // a fixup or relocation is emitted to replace $symbol with a literal 5874 // constant, which is a pc-relative offset from the encoding of the $symbol 5875 // operand to the global variable. 5876 // 5877 // For global address space: 5878 // s_getpc_b64 s[0:1] 5879 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5880 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5881 // 5882 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5883 // fixups or relocations are emitted to replace $symbol@*@lo and 5884 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5885 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5886 // operand to the global variable. 5887 // 5888 // What we want here is an offset from the value returned by s_getpc 5889 // (which is the address of the s_add_u32 instruction) to the global 5890 // variable, but since the encoding of $symbol starts 4 bytes after the start 5891 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5892 // small. This requires us to add 4 to the global variable offset in order to 5893 // compute the correct address. Similarly for the s_addc_u32 instruction, the 5894 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 5895 // instruction. 5896 SDValue PtrLo = 5897 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5898 SDValue PtrHi; 5899 if (GAFlags == SIInstrInfo::MO_NONE) { 5900 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5901 } else { 5902 PtrHi = 5903 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 5904 } 5905 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5906 } 5907 5908 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5909 SDValue Op, 5910 SelectionDAG &DAG) const { 5911 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5912 SDLoc DL(GSD); 5913 EVT PtrVT = Op.getValueType(); 5914 5915 const GlobalValue *GV = GSD->getGlobal(); 5916 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5917 shouldUseLDSConstAddress(GV)) || 5918 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5919 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 5920 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5921 GV->hasExternalLinkage()) { 5922 Type *Ty = GV->getValueType(); 5923 // HIP uses an unsized array `extern __shared__ T s[]` or similar 5924 // zero-sized type in other languages to declare the dynamic shared 5925 // memory which size is not known at the compile time. They will be 5926 // allocated by the runtime and placed directly after the static 5927 // allocated ones. They all share the same offset. 5928 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 5929 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 5930 // Adjust alignment for that dynamic shared memory array. 5931 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 5932 return SDValue( 5933 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 5934 } 5935 } 5936 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5937 } 5938 5939 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5940 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5941 SIInstrInfo::MO_ABS32_LO); 5942 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5943 } 5944 5945 if (shouldEmitFixup(GV)) 5946 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5947 else if (shouldEmitPCReloc(GV)) 5948 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5949 SIInstrInfo::MO_REL32); 5950 5951 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5952 SIInstrInfo::MO_GOTPCREL32); 5953 5954 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5955 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5956 const DataLayout &DataLayout = DAG.getDataLayout(); 5957 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 5958 MachinePointerInfo PtrInfo 5959 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5960 5961 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 5962 MachineMemOperand::MODereferenceable | 5963 MachineMemOperand::MOInvariant); 5964 } 5965 5966 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5967 const SDLoc &DL, SDValue V) const { 5968 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5969 // the destination register. 5970 // 5971 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5972 // so we will end up with redundant moves to m0. 5973 // 5974 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5975 5976 // A Null SDValue creates a glue result. 5977 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5978 V, Chain); 5979 return SDValue(M0, 0); 5980 } 5981 5982 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5983 SDValue Op, 5984 MVT VT, 5985 unsigned Offset) const { 5986 SDLoc SL(Op); 5987 SDValue Param = lowerKernargMemParameter( 5988 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 5989 // The local size values will have the hi 16-bits as zero. 5990 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5991 DAG.getValueType(VT)); 5992 } 5993 5994 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5995 EVT VT) { 5996 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5997 "non-hsa intrinsic with hsa target", 5998 DL.getDebugLoc()); 5999 DAG.getContext()->diagnose(BadIntrin); 6000 return DAG.getUNDEF(VT); 6001 } 6002 6003 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 6004 EVT VT) { 6005 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 6006 "intrinsic not supported on subtarget", 6007 DL.getDebugLoc()); 6008 DAG.getContext()->diagnose(BadIntrin); 6009 return DAG.getUNDEF(VT); 6010 } 6011 6012 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 6013 ArrayRef<SDValue> Elts) { 6014 assert(!Elts.empty()); 6015 MVT Type; 6016 unsigned NumElts = Elts.size(); 6017 6018 if (NumElts <= 8) { 6019 Type = MVT::getVectorVT(MVT::f32, NumElts); 6020 } else { 6021 assert(Elts.size() <= 16); 6022 Type = MVT::v16f32; 6023 NumElts = 16; 6024 } 6025 6026 SmallVector<SDValue, 16> VecElts(NumElts); 6027 for (unsigned i = 0; i < Elts.size(); ++i) { 6028 SDValue Elt = Elts[i]; 6029 if (Elt.getValueType() != MVT::f32) 6030 Elt = DAG.getBitcast(MVT::f32, Elt); 6031 VecElts[i] = Elt; 6032 } 6033 for (unsigned i = Elts.size(); i < NumElts; ++i) 6034 VecElts[i] = DAG.getUNDEF(MVT::f32); 6035 6036 if (NumElts == 1) 6037 return VecElts[0]; 6038 return DAG.getBuildVector(Type, DL, VecElts); 6039 } 6040 6041 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 6042 SDValue Src, int ExtraElts) { 6043 EVT SrcVT = Src.getValueType(); 6044 6045 SmallVector<SDValue, 8> Elts; 6046 6047 if (SrcVT.isVector()) 6048 DAG.ExtractVectorElements(Src, Elts); 6049 else 6050 Elts.push_back(Src); 6051 6052 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 6053 while (ExtraElts--) 6054 Elts.push_back(Undef); 6055 6056 return DAG.getBuildVector(CastVT, DL, Elts); 6057 } 6058 6059 // Re-construct the required return value for a image load intrinsic. 6060 // This is more complicated due to the optional use TexFailCtrl which means the required 6061 // return type is an aggregate 6062 static SDValue constructRetValue(SelectionDAG &DAG, 6063 MachineSDNode *Result, 6064 ArrayRef<EVT> ResultTypes, 6065 bool IsTexFail, bool Unpacked, bool IsD16, 6066 int DMaskPop, int NumVDataDwords, 6067 const SDLoc &DL) { 6068 // Determine the required return type. This is the same regardless of IsTexFail flag 6069 EVT ReqRetVT = ResultTypes[0]; 6070 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 6071 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 6072 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 6073 6074 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 6075 DMaskPop : (DMaskPop + 1) / 2; 6076 6077 MVT DataDwordVT = NumDataDwords == 1 ? 6078 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 6079 6080 MVT MaskPopVT = MaskPopDwords == 1 ? 6081 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 6082 6083 SDValue Data(Result, 0); 6084 SDValue TexFail; 6085 6086 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) { 6087 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 6088 if (MaskPopVT.isVector()) { 6089 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 6090 SDValue(Result, 0), ZeroIdx); 6091 } else { 6092 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 6093 SDValue(Result, 0), ZeroIdx); 6094 } 6095 } 6096 6097 if (DataDwordVT.isVector()) 6098 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 6099 NumDataDwords - MaskPopDwords); 6100 6101 if (IsD16) 6102 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 6103 6104 EVT LegalReqRetVT = ReqRetVT; 6105 if (!ReqRetVT.isVector()) { 6106 if (!Data.getValueType().isInteger()) 6107 Data = DAG.getNode(ISD::BITCAST, DL, 6108 Data.getValueType().changeTypeToInteger(), Data); 6109 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 6110 } else { 6111 // We need to widen the return vector to a legal type 6112 if ((ReqRetVT.getVectorNumElements() % 2) == 1 && 6113 ReqRetVT.getVectorElementType().getSizeInBits() == 16) { 6114 LegalReqRetVT = 6115 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(), 6116 ReqRetVT.getVectorNumElements() + 1); 6117 } 6118 } 6119 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data); 6120 6121 if (IsTexFail) { 6122 TexFail = 6123 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0), 6124 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 6125 6126 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 6127 } 6128 6129 if (Result->getNumValues() == 1) 6130 return Data; 6131 6132 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 6133 } 6134 6135 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 6136 SDValue *LWE, bool &IsTexFail) { 6137 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 6138 6139 uint64_t Value = TexFailCtrlConst->getZExtValue(); 6140 if (Value) { 6141 IsTexFail = true; 6142 } 6143 6144 SDLoc DL(TexFailCtrlConst); 6145 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 6146 Value &= ~(uint64_t)0x1; 6147 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 6148 Value &= ~(uint64_t)0x2; 6149 6150 return Value == 0; 6151 } 6152 6153 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op, 6154 MVT PackVectorVT, 6155 SmallVectorImpl<SDValue> &PackedAddrs, 6156 unsigned DimIdx, unsigned EndIdx, 6157 unsigned NumGradients) { 6158 SDLoc DL(Op); 6159 for (unsigned I = DimIdx; I < EndIdx; I++) { 6160 SDValue Addr = Op.getOperand(I); 6161 6162 // Gradients are packed with undef for each coordinate. 6163 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 6164 // 1D: undef,dx/dh; undef,dx/dv 6165 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 6166 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 6167 if (((I + 1) >= EndIdx) || 6168 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 6169 I == DimIdx + NumGradients - 1))) { 6170 if (Addr.getValueType() != MVT::i16) 6171 Addr = DAG.getBitcast(MVT::i16, Addr); 6172 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 6173 } else { 6174 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 6175 I++; 6176 } 6177 Addr = DAG.getBitcast(MVT::f32, Addr); 6178 PackedAddrs.push_back(Addr); 6179 } 6180 } 6181 6182 SDValue SITargetLowering::lowerImage(SDValue Op, 6183 const AMDGPU::ImageDimIntrinsicInfo *Intr, 6184 SelectionDAG &DAG, bool WithChain) const { 6185 SDLoc DL(Op); 6186 MachineFunction &MF = DAG.getMachineFunction(); 6187 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 6188 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 6189 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 6190 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 6191 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 6192 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 6193 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 6194 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 6195 unsigned IntrOpcode = Intr->BaseOpcode; 6196 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget); 6197 6198 SmallVector<EVT, 3> ResultTypes(Op->values()); 6199 SmallVector<EVT, 3> OrigResultTypes(Op->values()); 6200 bool IsD16 = false; 6201 bool IsG16 = false; 6202 bool IsA16 = false; 6203 SDValue VData; 6204 int NumVDataDwords; 6205 bool AdjustRetType = false; 6206 6207 // Offset of intrinsic arguments 6208 const unsigned ArgOffset = WithChain ? 2 : 1; 6209 6210 unsigned DMask; 6211 unsigned DMaskLanes = 0; 6212 6213 if (BaseOpcode->Atomic) { 6214 VData = Op.getOperand(2); 6215 6216 bool Is64Bit = VData.getValueType() == MVT::i64; 6217 if (BaseOpcode->AtomicX2) { 6218 SDValue VData2 = Op.getOperand(3); 6219 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 6220 {VData, VData2}); 6221 if (Is64Bit) 6222 VData = DAG.getBitcast(MVT::v4i32, VData); 6223 6224 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 6225 DMask = Is64Bit ? 0xf : 0x3; 6226 NumVDataDwords = Is64Bit ? 4 : 2; 6227 } else { 6228 DMask = Is64Bit ? 0x3 : 0x1; 6229 NumVDataDwords = Is64Bit ? 2 : 1; 6230 } 6231 } else { 6232 auto *DMaskConst = 6233 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex)); 6234 DMask = DMaskConst->getZExtValue(); 6235 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 6236 6237 if (BaseOpcode->Store) { 6238 VData = Op.getOperand(2); 6239 6240 MVT StoreVT = VData.getSimpleValueType(); 6241 if (StoreVT.getScalarType() == MVT::f16) { 6242 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6243 return Op; // D16 is unsupported for this instruction 6244 6245 IsD16 = true; 6246 VData = handleD16VData(VData, DAG, true); 6247 } 6248 6249 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 6250 } else { 6251 // Work out the num dwords based on the dmask popcount and underlying type 6252 // and whether packing is supported. 6253 MVT LoadVT = ResultTypes[0].getSimpleVT(); 6254 if (LoadVT.getScalarType() == MVT::f16) { 6255 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6256 return Op; // D16 is unsupported for this instruction 6257 6258 IsD16 = true; 6259 } 6260 6261 // Confirm that the return type is large enough for the dmask specified 6262 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 6263 (!LoadVT.isVector() && DMaskLanes > 1)) 6264 return Op; 6265 6266 // The sq block of gfx8 and gfx9 do not estimate register use correctly 6267 // for d16 image_gather4, image_gather4_l, and image_gather4_lz 6268 // instructions. 6269 if (IsD16 && !Subtarget->hasUnpackedD16VMem() && 6270 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug())) 6271 NumVDataDwords = (DMaskLanes + 1) / 2; 6272 else 6273 NumVDataDwords = DMaskLanes; 6274 6275 AdjustRetType = true; 6276 } 6277 } 6278 6279 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd; 6280 SmallVector<SDValue, 4> VAddrs; 6281 6282 // Optimize _L to _LZ when _L is zero 6283 if (LZMappingInfo) { 6284 if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>( 6285 Op.getOperand(ArgOffset + Intr->LodIndex))) { 6286 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 6287 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 6288 VAddrEnd--; // remove 'lod' 6289 } 6290 } 6291 } 6292 6293 // Optimize _mip away, when 'lod' is zero 6294 if (MIPMappingInfo) { 6295 if (auto *ConstantLod = dyn_cast<ConstantSDNode>( 6296 Op.getOperand(ArgOffset + Intr->MipIndex))) { 6297 if (ConstantLod->isZero()) { 6298 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 6299 VAddrEnd--; // remove 'mip' 6300 } 6301 } 6302 } 6303 6304 // Check for 16 bit addresses or derivatives and pack if true. 6305 MVT VAddrVT = 6306 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType(); 6307 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6308 MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6309 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6310 6311 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType(); 6312 VAddrScalarVT = VAddrVT.getScalarType(); 6313 MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6314 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6315 6316 // Push back extra arguments. 6317 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) { 6318 if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) { 6319 // Special handling of bias when A16 is on. Bias is of type half but 6320 // occupies full 32-bit. 6321 SDValue bias = DAG.getBuildVector( MVT::v2f16, DL, {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)}); 6322 VAddrs.push_back(bias); 6323 } else 6324 VAddrs.push_back(Op.getOperand(ArgOffset + I)); 6325 } 6326 6327 if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) { 6328 // 16 bit gradients are supported, but are tied to the A16 control 6329 // so both gradients and addresses must be 16 bit 6330 LLVM_DEBUG( 6331 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6332 "require 16 bit args for both gradients and addresses"); 6333 return Op; 6334 } 6335 6336 if (IsA16) { 6337 if (!ST->hasA16()) { 6338 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6339 "support 16 bit addresses\n"); 6340 return Op; 6341 } 6342 } 6343 6344 // We've dealt with incorrect input so we know that if IsA16, IsG16 6345 // are set then we have to compress/pack operands (either address, 6346 // gradient or both) 6347 // In the case where a16 and gradients are tied (no G16 support) then we 6348 // have already verified that both IsA16 and IsG16 are true 6349 if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) { 6350 // Activate g16 6351 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6352 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6353 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6354 } 6355 6356 // Add gradients (packed or unpacked) 6357 if (IsG16) { 6358 // Pack the gradients 6359 // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart); 6360 packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs, 6361 ArgOffset + Intr->GradientStart, 6362 ArgOffset + Intr->CoordStart, Intr->NumGradients); 6363 } else { 6364 for (unsigned I = ArgOffset + Intr->GradientStart; 6365 I < ArgOffset + Intr->CoordStart; I++) 6366 VAddrs.push_back(Op.getOperand(I)); 6367 } 6368 6369 // Add addresses (packed or unpacked) 6370 if (IsA16) { 6371 packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs, 6372 ArgOffset + Intr->CoordStart, VAddrEnd, 6373 0 /* No gradients */); 6374 } else { 6375 // Add uncompressed address 6376 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++) 6377 VAddrs.push_back(Op.getOperand(I)); 6378 } 6379 6380 // If the register allocator cannot place the address registers contiguously 6381 // without introducing moves, then using the non-sequential address encoding 6382 // is always preferable, since it saves VALU instructions and is usually a 6383 // wash in terms of code size or even better. 6384 // 6385 // However, we currently have no way of hinting to the register allocator that 6386 // MIMG addresses should be placed contiguously when it is possible to do so, 6387 // so force non-NSA for the common 2-address case as a heuristic. 6388 // 6389 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6390 // allocation when possible. 6391 bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) && 6392 VAddrs.size() >= 3 && 6393 VAddrs.size() <= (unsigned)ST->getNSAMaxSize(); 6394 SDValue VAddr; 6395 if (!UseNSA) 6396 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6397 6398 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6399 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6400 SDValue Unorm; 6401 if (!BaseOpcode->Sampler) { 6402 Unorm = True; 6403 } else { 6404 auto UnormConst = 6405 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex)); 6406 6407 Unorm = UnormConst->getZExtValue() ? True : False; 6408 } 6409 6410 SDValue TFE; 6411 SDValue LWE; 6412 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex); 6413 bool IsTexFail = false; 6414 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6415 return Op; 6416 6417 if (IsTexFail) { 6418 if (!DMaskLanes) { 6419 // Expecting to get an error flag since TFC is on - and dmask is 0 6420 // Force dmask to be at least 1 otherwise the instruction will fail 6421 DMask = 0x1; 6422 DMaskLanes = 1; 6423 NumVDataDwords = 1; 6424 } 6425 NumVDataDwords += 1; 6426 AdjustRetType = true; 6427 } 6428 6429 // Has something earlier tagged that the return type needs adjusting 6430 // This happens if the instruction is a load or has set TexFailCtrl flags 6431 if (AdjustRetType) { 6432 // NumVDataDwords reflects the true number of dwords required in the return type 6433 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6434 // This is a no-op load. This can be eliminated 6435 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6436 if (isa<MemSDNode>(Op)) 6437 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6438 return Undef; 6439 } 6440 6441 EVT NewVT = NumVDataDwords > 1 ? 6442 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6443 : MVT::i32; 6444 6445 ResultTypes[0] = NewVT; 6446 if (ResultTypes.size() == 3) { 6447 // Original result was aggregate type used for TexFailCtrl results 6448 // The actual instruction returns as a vector type which has now been 6449 // created. Remove the aggregate result. 6450 ResultTypes.erase(&ResultTypes[1]); 6451 } 6452 } 6453 6454 unsigned CPol = cast<ConstantSDNode>( 6455 Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue(); 6456 if (BaseOpcode->Atomic) 6457 CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization 6458 if (CPol & ~AMDGPU::CPol::ALL) 6459 return Op; 6460 6461 SmallVector<SDValue, 26> Ops; 6462 if (BaseOpcode->Store || BaseOpcode->Atomic) 6463 Ops.push_back(VData); // vdata 6464 if (UseNSA) 6465 append_range(Ops, VAddrs); 6466 else 6467 Ops.push_back(VAddr); 6468 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex)); 6469 if (BaseOpcode->Sampler) 6470 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex)); 6471 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6472 if (IsGFX10Plus) 6473 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6474 Ops.push_back(Unorm); 6475 Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32)); 6476 Ops.push_back(IsA16 && // r128, a16 for gfx9 6477 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6478 if (IsGFX10Plus) 6479 Ops.push_back(IsA16 ? True : False); 6480 if (!Subtarget->hasGFX90AInsts()) { 6481 Ops.push_back(TFE); //tfe 6482 } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) { 6483 report_fatal_error("TFE is not supported on this GPU"); 6484 } 6485 Ops.push_back(LWE); // lwe 6486 if (!IsGFX10Plus) 6487 Ops.push_back(DimInfo->DA ? True : False); 6488 if (BaseOpcode->HasD16) 6489 Ops.push_back(IsD16 ? True : False); 6490 if (isa<MemSDNode>(Op)) 6491 Ops.push_back(Op.getOperand(0)); // chain 6492 6493 int NumVAddrDwords = 6494 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6495 int Opcode = -1; 6496 6497 if (IsGFX10Plus) { 6498 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6499 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6500 : AMDGPU::MIMGEncGfx10Default, 6501 NumVDataDwords, NumVAddrDwords); 6502 } else { 6503 if (Subtarget->hasGFX90AInsts()) { 6504 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a, 6505 NumVDataDwords, NumVAddrDwords); 6506 if (Opcode == -1) 6507 report_fatal_error( 6508 "requested image instruction is not supported on this GPU"); 6509 } 6510 if (Opcode == -1 && 6511 Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6512 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6513 NumVDataDwords, NumVAddrDwords); 6514 if (Opcode == -1) 6515 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6516 NumVDataDwords, NumVAddrDwords); 6517 } 6518 assert(Opcode != -1); 6519 6520 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6521 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6522 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6523 DAG.setNodeMemRefs(NewNode, {MemRef}); 6524 } 6525 6526 if (BaseOpcode->AtomicX2) { 6527 SmallVector<SDValue, 1> Elt; 6528 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6529 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6530 } 6531 if (BaseOpcode->Store) 6532 return SDValue(NewNode, 0); 6533 return constructRetValue(DAG, NewNode, 6534 OrigResultTypes, IsTexFail, 6535 Subtarget->hasUnpackedD16VMem(), IsD16, 6536 DMaskLanes, NumVDataDwords, DL); 6537 } 6538 6539 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6540 SDValue Offset, SDValue CachePolicy, 6541 SelectionDAG &DAG) const { 6542 MachineFunction &MF = DAG.getMachineFunction(); 6543 6544 const DataLayout &DataLayout = DAG.getDataLayout(); 6545 Align Alignment = 6546 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6547 6548 MachineMemOperand *MMO = MF.getMachineMemOperand( 6549 MachinePointerInfo(), 6550 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6551 MachineMemOperand::MOInvariant, 6552 VT.getStoreSize(), Alignment); 6553 6554 if (!Offset->isDivergent()) { 6555 SDValue Ops[] = { 6556 Rsrc, 6557 Offset, // Offset 6558 CachePolicy 6559 }; 6560 6561 // Widen vec3 load to vec4. 6562 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6563 EVT WidenedVT = 6564 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6565 auto WidenedOp = DAG.getMemIntrinsicNode( 6566 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6567 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6568 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6569 DAG.getVectorIdxConstant(0, DL)); 6570 return Subvector; 6571 } 6572 6573 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6574 DAG.getVTList(VT), Ops, VT, MMO); 6575 } 6576 6577 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6578 // assume that the buffer is unswizzled. 6579 SmallVector<SDValue, 4> Loads; 6580 unsigned NumLoads = 1; 6581 MVT LoadVT = VT.getSimpleVT(); 6582 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6583 assert((LoadVT.getScalarType() == MVT::i32 || 6584 LoadVT.getScalarType() == MVT::f32)); 6585 6586 if (NumElts == 8 || NumElts == 16) { 6587 NumLoads = NumElts / 4; 6588 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6589 } 6590 6591 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6592 SDValue Ops[] = { 6593 DAG.getEntryNode(), // Chain 6594 Rsrc, // rsrc 6595 DAG.getConstant(0, DL, MVT::i32), // vindex 6596 {}, // voffset 6597 {}, // soffset 6598 {}, // offset 6599 CachePolicy, // cachepolicy 6600 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6601 }; 6602 6603 // Use the alignment to ensure that the required offsets will fit into the 6604 // immediate offsets. 6605 setBufferOffsets(Offset, DAG, &Ops[3], 6606 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6607 6608 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6609 for (unsigned i = 0; i < NumLoads; ++i) { 6610 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6611 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6612 LoadVT, MMO, DAG)); 6613 } 6614 6615 if (NumElts == 8 || NumElts == 16) 6616 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6617 6618 return Loads[0]; 6619 } 6620 6621 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6622 SelectionDAG &DAG) const { 6623 MachineFunction &MF = DAG.getMachineFunction(); 6624 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6625 6626 EVT VT = Op.getValueType(); 6627 SDLoc DL(Op); 6628 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6629 6630 // TODO: Should this propagate fast-math-flags? 6631 6632 switch (IntrinsicID) { 6633 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6634 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6635 return emitNonHSAIntrinsicError(DAG, DL, VT); 6636 return getPreloadedValue(DAG, *MFI, VT, 6637 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6638 } 6639 case Intrinsic::amdgcn_dispatch_ptr: 6640 case Intrinsic::amdgcn_queue_ptr: { 6641 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6642 DiagnosticInfoUnsupported BadIntrin( 6643 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6644 DL.getDebugLoc()); 6645 DAG.getContext()->diagnose(BadIntrin); 6646 return DAG.getUNDEF(VT); 6647 } 6648 6649 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6650 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6651 return getPreloadedValue(DAG, *MFI, VT, RegID); 6652 } 6653 case Intrinsic::amdgcn_implicitarg_ptr: { 6654 if (MFI->isEntryFunction()) 6655 return getImplicitArgPtr(DAG, DL); 6656 return getPreloadedValue(DAG, *MFI, VT, 6657 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6658 } 6659 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6660 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6661 // This only makes sense to call in a kernel, so just lower to null. 6662 return DAG.getConstant(0, DL, VT); 6663 } 6664 6665 return getPreloadedValue(DAG, *MFI, VT, 6666 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6667 } 6668 case Intrinsic::amdgcn_dispatch_id: { 6669 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6670 } 6671 case Intrinsic::amdgcn_rcp: 6672 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6673 case Intrinsic::amdgcn_rsq: 6674 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6675 case Intrinsic::amdgcn_rsq_legacy: 6676 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6677 return emitRemovedIntrinsicError(DAG, DL, VT); 6678 return SDValue(); 6679 case Intrinsic::amdgcn_rcp_legacy: 6680 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6681 return emitRemovedIntrinsicError(DAG, DL, VT); 6682 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6683 case Intrinsic::amdgcn_rsq_clamp: { 6684 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6685 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6686 6687 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6688 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6689 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6690 6691 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6692 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6693 DAG.getConstantFP(Max, DL, VT)); 6694 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6695 DAG.getConstantFP(Min, DL, VT)); 6696 } 6697 case Intrinsic::r600_read_ngroups_x: 6698 if (Subtarget->isAmdHsaOS()) 6699 return emitNonHSAIntrinsicError(DAG, DL, VT); 6700 6701 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6702 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6703 false); 6704 case Intrinsic::r600_read_ngroups_y: 6705 if (Subtarget->isAmdHsaOS()) 6706 return emitNonHSAIntrinsicError(DAG, DL, VT); 6707 6708 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6709 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6710 false); 6711 case Intrinsic::r600_read_ngroups_z: 6712 if (Subtarget->isAmdHsaOS()) 6713 return emitNonHSAIntrinsicError(DAG, DL, VT); 6714 6715 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6716 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6717 false); 6718 case Intrinsic::r600_read_global_size_x: 6719 if (Subtarget->isAmdHsaOS()) 6720 return emitNonHSAIntrinsicError(DAG, DL, VT); 6721 6722 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6723 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6724 Align(4), false); 6725 case Intrinsic::r600_read_global_size_y: 6726 if (Subtarget->isAmdHsaOS()) 6727 return emitNonHSAIntrinsicError(DAG, DL, VT); 6728 6729 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6730 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6731 Align(4), false); 6732 case Intrinsic::r600_read_global_size_z: 6733 if (Subtarget->isAmdHsaOS()) 6734 return emitNonHSAIntrinsicError(DAG, DL, VT); 6735 6736 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6737 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6738 Align(4), false); 6739 case Intrinsic::r600_read_local_size_x: 6740 if (Subtarget->isAmdHsaOS()) 6741 return emitNonHSAIntrinsicError(DAG, DL, VT); 6742 6743 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6744 SI::KernelInputOffsets::LOCAL_SIZE_X); 6745 case Intrinsic::r600_read_local_size_y: 6746 if (Subtarget->isAmdHsaOS()) 6747 return emitNonHSAIntrinsicError(DAG, DL, VT); 6748 6749 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6750 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6751 case Intrinsic::r600_read_local_size_z: 6752 if (Subtarget->isAmdHsaOS()) 6753 return emitNonHSAIntrinsicError(DAG, DL, VT); 6754 6755 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6756 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6757 case Intrinsic::amdgcn_workgroup_id_x: 6758 return getPreloadedValue(DAG, *MFI, VT, 6759 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6760 case Intrinsic::amdgcn_workgroup_id_y: 6761 return getPreloadedValue(DAG, *MFI, VT, 6762 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6763 case Intrinsic::amdgcn_workgroup_id_z: 6764 return getPreloadedValue(DAG, *MFI, VT, 6765 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6766 case Intrinsic::amdgcn_workitem_id_x: 6767 if (Subtarget->getMaxWorkitemID(MF.getFunction(), 0) == 0) 6768 return DAG.getConstant(0, DL, MVT::i32); 6769 6770 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6771 SDLoc(DAG.getEntryNode()), 6772 MFI->getArgInfo().WorkItemIDX); 6773 case Intrinsic::amdgcn_workitem_id_y: 6774 if (Subtarget->getMaxWorkitemID(MF.getFunction(), 1) == 0) 6775 return DAG.getConstant(0, DL, MVT::i32); 6776 6777 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6778 SDLoc(DAG.getEntryNode()), 6779 MFI->getArgInfo().WorkItemIDY); 6780 case Intrinsic::amdgcn_workitem_id_z: 6781 if (Subtarget->getMaxWorkitemID(MF.getFunction(), 2) == 0) 6782 return DAG.getConstant(0, DL, MVT::i32); 6783 6784 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6785 SDLoc(DAG.getEntryNode()), 6786 MFI->getArgInfo().WorkItemIDZ); 6787 case Intrinsic::amdgcn_wavefrontsize: 6788 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6789 SDLoc(Op), MVT::i32); 6790 case Intrinsic::amdgcn_s_buffer_load: { 6791 unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 6792 if (CPol & ~AMDGPU::CPol::ALL) 6793 return Op; 6794 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6795 DAG); 6796 } 6797 case Intrinsic::amdgcn_fdiv_fast: 6798 return lowerFDIV_FAST(Op, DAG); 6799 case Intrinsic::amdgcn_sin: 6800 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6801 6802 case Intrinsic::amdgcn_cos: 6803 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6804 6805 case Intrinsic::amdgcn_mul_u24: 6806 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6807 case Intrinsic::amdgcn_mul_i24: 6808 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6809 6810 case Intrinsic::amdgcn_log_clamp: { 6811 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6812 return SDValue(); 6813 6814 return emitRemovedIntrinsicError(DAG, DL, VT); 6815 } 6816 case Intrinsic::amdgcn_ldexp: 6817 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6818 Op.getOperand(1), Op.getOperand(2)); 6819 6820 case Intrinsic::amdgcn_fract: 6821 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6822 6823 case Intrinsic::amdgcn_class: 6824 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6825 Op.getOperand(1), Op.getOperand(2)); 6826 case Intrinsic::amdgcn_div_fmas: 6827 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6828 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6829 Op.getOperand(4)); 6830 6831 case Intrinsic::amdgcn_div_fixup: 6832 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6833 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6834 6835 case Intrinsic::amdgcn_div_scale: { 6836 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6837 6838 // Translate to the operands expected by the machine instruction. The 6839 // first parameter must be the same as the first instruction. 6840 SDValue Numerator = Op.getOperand(1); 6841 SDValue Denominator = Op.getOperand(2); 6842 6843 // Note this order is opposite of the machine instruction's operations, 6844 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6845 // intrinsic has the numerator as the first operand to match a normal 6846 // division operation. 6847 6848 SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator; 6849 6850 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6851 Denominator, Numerator); 6852 } 6853 case Intrinsic::amdgcn_icmp: { 6854 // There is a Pat that handles this variant, so return it as-is. 6855 if (Op.getOperand(1).getValueType() == MVT::i1 && 6856 Op.getConstantOperandVal(2) == 0 && 6857 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6858 return Op; 6859 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6860 } 6861 case Intrinsic::amdgcn_fcmp: { 6862 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6863 } 6864 case Intrinsic::amdgcn_ballot: 6865 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6866 case Intrinsic::amdgcn_fmed3: 6867 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6868 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6869 case Intrinsic::amdgcn_fdot2: 6870 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6871 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6872 Op.getOperand(4)); 6873 case Intrinsic::amdgcn_fmul_legacy: 6874 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6875 Op.getOperand(1), Op.getOperand(2)); 6876 case Intrinsic::amdgcn_sffbh: 6877 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6878 case Intrinsic::amdgcn_sbfe: 6879 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6880 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6881 case Intrinsic::amdgcn_ubfe: 6882 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6883 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6884 case Intrinsic::amdgcn_cvt_pkrtz: 6885 case Intrinsic::amdgcn_cvt_pknorm_i16: 6886 case Intrinsic::amdgcn_cvt_pknorm_u16: 6887 case Intrinsic::amdgcn_cvt_pk_i16: 6888 case Intrinsic::amdgcn_cvt_pk_u16: { 6889 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6890 EVT VT = Op.getValueType(); 6891 unsigned Opcode; 6892 6893 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6894 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6895 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6896 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6897 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6898 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6899 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6900 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6901 else 6902 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6903 6904 if (isTypeLegal(VT)) 6905 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6906 6907 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6908 Op.getOperand(1), Op.getOperand(2)); 6909 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6910 } 6911 case Intrinsic::amdgcn_fmad_ftz: 6912 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6913 Op.getOperand(2), Op.getOperand(3)); 6914 6915 case Intrinsic::amdgcn_if_break: 6916 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6917 Op->getOperand(1), Op->getOperand(2)), 0); 6918 6919 case Intrinsic::amdgcn_groupstaticsize: { 6920 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6921 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6922 return Op; 6923 6924 const Module *M = MF.getFunction().getParent(); 6925 const GlobalValue *GV = 6926 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6927 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6928 SIInstrInfo::MO_ABS32_LO); 6929 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6930 } 6931 case Intrinsic::amdgcn_is_shared: 6932 case Intrinsic::amdgcn_is_private: { 6933 SDLoc SL(Op); 6934 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6935 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6936 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6937 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6938 Op.getOperand(1)); 6939 6940 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6941 DAG.getConstant(1, SL, MVT::i32)); 6942 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6943 } 6944 case Intrinsic::amdgcn_alignbit: 6945 return DAG.getNode(ISD::FSHR, DL, VT, 6946 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6947 case Intrinsic::amdgcn_perm: 6948 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1), 6949 Op.getOperand(2), Op.getOperand(3)); 6950 case Intrinsic::amdgcn_reloc_constant: { 6951 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6952 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6953 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6954 auto RelocSymbol = cast<GlobalVariable>( 6955 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6956 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6957 SIInstrInfo::MO_ABS32_LO); 6958 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6959 } 6960 default: 6961 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6962 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6963 return lowerImage(Op, ImageDimIntr, DAG, false); 6964 6965 return Op; 6966 } 6967 } 6968 6969 /// Update \p MMO based on the offset inputs to an intrinsic. 6970 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset, 6971 SDValue SOffset, SDValue Offset, 6972 SDValue VIndex = SDValue()) { 6973 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6974 !isa<ConstantSDNode>(Offset)) { 6975 // The combined offset is not known to be constant, so we cannot represent 6976 // it in the MMO. Give up. 6977 MMO->setValue((Value *)nullptr); 6978 return; 6979 } 6980 6981 if (VIndex && (!isa<ConstantSDNode>(VIndex) || 6982 !cast<ConstantSDNode>(VIndex)->isZero())) { 6983 // The strided index component of the address is not known to be zero, so we 6984 // cannot represent it in the MMO. Give up. 6985 MMO->setValue((Value *)nullptr); 6986 return; 6987 } 6988 6989 MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() + 6990 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6991 cast<ConstantSDNode>(Offset)->getSExtValue()); 6992 } 6993 6994 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 6995 SelectionDAG &DAG, 6996 unsigned NewOpcode) const { 6997 SDLoc DL(Op); 6998 6999 SDValue VData = Op.getOperand(2); 7000 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7001 SDValue Ops[] = { 7002 Op.getOperand(0), // Chain 7003 VData, // vdata 7004 Op.getOperand(3), // rsrc 7005 DAG.getConstant(0, DL, MVT::i32), // vindex 7006 Offsets.first, // voffset 7007 Op.getOperand(5), // soffset 7008 Offsets.second, // offset 7009 Op.getOperand(6), // cachepolicy 7010 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7011 }; 7012 7013 auto *M = cast<MemSDNode>(Op); 7014 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 7015 7016 EVT MemVT = VData.getValueType(); 7017 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 7018 M->getMemOperand()); 7019 } 7020 7021 // Return a value to use for the idxen operand by examining the vindex operand. 7022 static unsigned getIdxEn(SDValue VIndex) { 7023 if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex)) 7024 // No need to set idxen if vindex is known to be zero. 7025 return VIndexC->getZExtValue() != 0; 7026 return 1; 7027 } 7028 7029 SDValue 7030 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 7031 unsigned NewOpcode) const { 7032 SDLoc DL(Op); 7033 7034 SDValue VData = Op.getOperand(2); 7035 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7036 SDValue Ops[] = { 7037 Op.getOperand(0), // Chain 7038 VData, // vdata 7039 Op.getOperand(3), // rsrc 7040 Op.getOperand(4), // vindex 7041 Offsets.first, // voffset 7042 Op.getOperand(6), // soffset 7043 Offsets.second, // offset 7044 Op.getOperand(7), // cachepolicy 7045 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7046 }; 7047 7048 auto *M = cast<MemSDNode>(Op); 7049 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7050 7051 EVT MemVT = VData.getValueType(); 7052 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 7053 M->getMemOperand()); 7054 } 7055 7056 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 7057 SelectionDAG &DAG) const { 7058 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7059 SDLoc DL(Op); 7060 7061 switch (IntrID) { 7062 case Intrinsic::amdgcn_ds_ordered_add: 7063 case Intrinsic::amdgcn_ds_ordered_swap: { 7064 MemSDNode *M = cast<MemSDNode>(Op); 7065 SDValue Chain = M->getOperand(0); 7066 SDValue M0 = M->getOperand(2); 7067 SDValue Value = M->getOperand(3); 7068 unsigned IndexOperand = M->getConstantOperandVal(7); 7069 unsigned WaveRelease = M->getConstantOperandVal(8); 7070 unsigned WaveDone = M->getConstantOperandVal(9); 7071 7072 unsigned OrderedCountIndex = IndexOperand & 0x3f; 7073 IndexOperand &= ~0x3f; 7074 unsigned CountDw = 0; 7075 7076 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 7077 CountDw = (IndexOperand >> 24) & 0xf; 7078 IndexOperand &= ~(0xf << 24); 7079 7080 if (CountDw < 1 || CountDw > 4) { 7081 report_fatal_error( 7082 "ds_ordered_count: dword count must be between 1 and 4"); 7083 } 7084 } 7085 7086 if (IndexOperand) 7087 report_fatal_error("ds_ordered_count: bad index operand"); 7088 7089 if (WaveDone && !WaveRelease) 7090 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 7091 7092 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 7093 unsigned ShaderType = 7094 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 7095 unsigned Offset0 = OrderedCountIndex << 2; 7096 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 7097 (Instruction << 4); 7098 7099 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 7100 Offset1 |= (CountDw - 1) << 6; 7101 7102 unsigned Offset = Offset0 | (Offset1 << 8); 7103 7104 SDValue Ops[] = { 7105 Chain, 7106 Value, 7107 DAG.getTargetConstant(Offset, DL, MVT::i16), 7108 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 7109 }; 7110 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 7111 M->getVTList(), Ops, M->getMemoryVT(), 7112 M->getMemOperand()); 7113 } 7114 case Intrinsic::amdgcn_ds_fadd: { 7115 MemSDNode *M = cast<MemSDNode>(Op); 7116 unsigned Opc; 7117 switch (IntrID) { 7118 case Intrinsic::amdgcn_ds_fadd: 7119 Opc = ISD::ATOMIC_LOAD_FADD; 7120 break; 7121 } 7122 7123 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 7124 M->getOperand(0), M->getOperand(2), M->getOperand(3), 7125 M->getMemOperand()); 7126 } 7127 case Intrinsic::amdgcn_atomic_inc: 7128 case Intrinsic::amdgcn_atomic_dec: 7129 case Intrinsic::amdgcn_ds_fmin: 7130 case Intrinsic::amdgcn_ds_fmax: { 7131 MemSDNode *M = cast<MemSDNode>(Op); 7132 unsigned Opc; 7133 switch (IntrID) { 7134 case Intrinsic::amdgcn_atomic_inc: 7135 Opc = AMDGPUISD::ATOMIC_INC; 7136 break; 7137 case Intrinsic::amdgcn_atomic_dec: 7138 Opc = AMDGPUISD::ATOMIC_DEC; 7139 break; 7140 case Intrinsic::amdgcn_ds_fmin: 7141 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 7142 break; 7143 case Intrinsic::amdgcn_ds_fmax: 7144 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 7145 break; 7146 default: 7147 llvm_unreachable("Unknown intrinsic!"); 7148 } 7149 SDValue Ops[] = { 7150 M->getOperand(0), // Chain 7151 M->getOperand(2), // Ptr 7152 M->getOperand(3) // Value 7153 }; 7154 7155 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 7156 M->getMemoryVT(), M->getMemOperand()); 7157 } 7158 case Intrinsic::amdgcn_buffer_load: 7159 case Intrinsic::amdgcn_buffer_load_format: { 7160 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 7161 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7162 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7163 SDValue Ops[] = { 7164 Op.getOperand(0), // Chain 7165 Op.getOperand(2), // rsrc 7166 Op.getOperand(3), // vindex 7167 SDValue(), // voffset -- will be set by setBufferOffsets 7168 SDValue(), // soffset -- will be set by setBufferOffsets 7169 SDValue(), // offset -- will be set by setBufferOffsets 7170 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7171 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7172 }; 7173 setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 7174 7175 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 7176 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 7177 7178 EVT VT = Op.getValueType(); 7179 EVT IntVT = VT.changeTypeToInteger(); 7180 auto *M = cast<MemSDNode>(Op); 7181 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7182 EVT LoadVT = Op.getValueType(); 7183 7184 if (LoadVT.getScalarType() == MVT::f16) 7185 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 7186 M, DAG, Ops); 7187 7188 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 7189 if (LoadVT.getScalarType() == MVT::i8 || 7190 LoadVT.getScalarType() == MVT::i16) 7191 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 7192 7193 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 7194 M->getMemOperand(), DAG); 7195 } 7196 case Intrinsic::amdgcn_raw_buffer_load: 7197 case Intrinsic::amdgcn_raw_buffer_load_format: { 7198 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 7199 7200 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7201 SDValue Ops[] = { 7202 Op.getOperand(0), // Chain 7203 Op.getOperand(2), // rsrc 7204 DAG.getConstant(0, DL, MVT::i32), // vindex 7205 Offsets.first, // voffset 7206 Op.getOperand(4), // soffset 7207 Offsets.second, // offset 7208 Op.getOperand(5), // cachepolicy, swizzled buffer 7209 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7210 }; 7211 7212 auto *M = cast<MemSDNode>(Op); 7213 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]); 7214 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 7215 } 7216 case Intrinsic::amdgcn_struct_buffer_load: 7217 case Intrinsic::amdgcn_struct_buffer_load_format: { 7218 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 7219 7220 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7221 SDValue Ops[] = { 7222 Op.getOperand(0), // Chain 7223 Op.getOperand(2), // rsrc 7224 Op.getOperand(3), // vindex 7225 Offsets.first, // voffset 7226 Op.getOperand(5), // soffset 7227 Offsets.second, // offset 7228 Op.getOperand(6), // cachepolicy, swizzled buffer 7229 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7230 }; 7231 7232 auto *M = cast<MemSDNode>(Op); 7233 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7234 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 7235 } 7236 case Intrinsic::amdgcn_tbuffer_load: { 7237 MemSDNode *M = cast<MemSDNode>(Op); 7238 EVT LoadVT = Op.getValueType(); 7239 7240 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7241 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7242 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7243 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7244 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7245 SDValue Ops[] = { 7246 Op.getOperand(0), // Chain 7247 Op.getOperand(2), // rsrc 7248 Op.getOperand(3), // vindex 7249 Op.getOperand(4), // voffset 7250 Op.getOperand(5), // soffset 7251 Op.getOperand(6), // offset 7252 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7253 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7254 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 7255 }; 7256 7257 if (LoadVT.getScalarType() == MVT::f16) 7258 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7259 M, DAG, Ops); 7260 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7261 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7262 DAG); 7263 } 7264 case Intrinsic::amdgcn_raw_tbuffer_load: { 7265 MemSDNode *M = cast<MemSDNode>(Op); 7266 EVT LoadVT = Op.getValueType(); 7267 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7268 7269 SDValue Ops[] = { 7270 Op.getOperand(0), // Chain 7271 Op.getOperand(2), // rsrc 7272 DAG.getConstant(0, DL, MVT::i32), // vindex 7273 Offsets.first, // voffset 7274 Op.getOperand(4), // soffset 7275 Offsets.second, // offset 7276 Op.getOperand(5), // format 7277 Op.getOperand(6), // cachepolicy, swizzled buffer 7278 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7279 }; 7280 7281 if (LoadVT.getScalarType() == MVT::f16) 7282 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7283 M, DAG, Ops); 7284 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7285 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7286 DAG); 7287 } 7288 case Intrinsic::amdgcn_struct_tbuffer_load: { 7289 MemSDNode *M = cast<MemSDNode>(Op); 7290 EVT LoadVT = Op.getValueType(); 7291 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7292 7293 SDValue Ops[] = { 7294 Op.getOperand(0), // Chain 7295 Op.getOperand(2), // rsrc 7296 Op.getOperand(3), // vindex 7297 Offsets.first, // voffset 7298 Op.getOperand(5), // soffset 7299 Offsets.second, // offset 7300 Op.getOperand(6), // format 7301 Op.getOperand(7), // cachepolicy, swizzled buffer 7302 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7303 }; 7304 7305 if (LoadVT.getScalarType() == MVT::f16) 7306 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7307 M, DAG, Ops); 7308 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7309 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7310 DAG); 7311 } 7312 case Intrinsic::amdgcn_buffer_atomic_swap: 7313 case Intrinsic::amdgcn_buffer_atomic_add: 7314 case Intrinsic::amdgcn_buffer_atomic_sub: 7315 case Intrinsic::amdgcn_buffer_atomic_csub: 7316 case Intrinsic::amdgcn_buffer_atomic_smin: 7317 case Intrinsic::amdgcn_buffer_atomic_umin: 7318 case Intrinsic::amdgcn_buffer_atomic_smax: 7319 case Intrinsic::amdgcn_buffer_atomic_umax: 7320 case Intrinsic::amdgcn_buffer_atomic_and: 7321 case Intrinsic::amdgcn_buffer_atomic_or: 7322 case Intrinsic::amdgcn_buffer_atomic_xor: 7323 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7324 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7325 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7326 SDValue Ops[] = { 7327 Op.getOperand(0), // Chain 7328 Op.getOperand(2), // vdata 7329 Op.getOperand(3), // rsrc 7330 Op.getOperand(4), // vindex 7331 SDValue(), // voffset -- will be set by setBufferOffsets 7332 SDValue(), // soffset -- will be set by setBufferOffsets 7333 SDValue(), // offset -- will be set by setBufferOffsets 7334 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7335 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7336 }; 7337 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7338 7339 EVT VT = Op.getValueType(); 7340 7341 auto *M = cast<MemSDNode>(Op); 7342 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7343 unsigned Opcode = 0; 7344 7345 switch (IntrID) { 7346 case Intrinsic::amdgcn_buffer_atomic_swap: 7347 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7348 break; 7349 case Intrinsic::amdgcn_buffer_atomic_add: 7350 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7351 break; 7352 case Intrinsic::amdgcn_buffer_atomic_sub: 7353 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7354 break; 7355 case Intrinsic::amdgcn_buffer_atomic_csub: 7356 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7357 break; 7358 case Intrinsic::amdgcn_buffer_atomic_smin: 7359 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7360 break; 7361 case Intrinsic::amdgcn_buffer_atomic_umin: 7362 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7363 break; 7364 case Intrinsic::amdgcn_buffer_atomic_smax: 7365 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7366 break; 7367 case Intrinsic::amdgcn_buffer_atomic_umax: 7368 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7369 break; 7370 case Intrinsic::amdgcn_buffer_atomic_and: 7371 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7372 break; 7373 case Intrinsic::amdgcn_buffer_atomic_or: 7374 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7375 break; 7376 case Intrinsic::amdgcn_buffer_atomic_xor: 7377 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7378 break; 7379 case Intrinsic::amdgcn_buffer_atomic_fadd: 7380 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7381 DiagnosticInfoUnsupported 7382 NoFpRet(DAG.getMachineFunction().getFunction(), 7383 "return versions of fp atomics not supported", 7384 DL.getDebugLoc(), DS_Error); 7385 DAG.getContext()->diagnose(NoFpRet); 7386 return SDValue(); 7387 } 7388 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7389 break; 7390 default: 7391 llvm_unreachable("unhandled atomic opcode"); 7392 } 7393 7394 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7395 M->getMemOperand()); 7396 } 7397 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7398 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7399 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7400 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7401 case Intrinsic::amdgcn_raw_buffer_atomic_fmin: 7402 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7403 case Intrinsic::amdgcn_struct_buffer_atomic_fmin: 7404 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7405 case Intrinsic::amdgcn_raw_buffer_atomic_fmax: 7406 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7407 case Intrinsic::amdgcn_struct_buffer_atomic_fmax: 7408 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7409 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7410 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7411 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7412 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7413 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7414 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7415 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7416 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7417 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7418 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7419 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7420 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7421 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7422 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7423 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7424 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7425 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7426 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7427 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7428 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7429 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7430 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7431 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7432 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7433 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7434 return lowerStructBufferAtomicIntrin(Op, DAG, 7435 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7436 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7437 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7438 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7439 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7440 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7441 return lowerStructBufferAtomicIntrin(Op, DAG, 7442 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7443 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7444 return lowerStructBufferAtomicIntrin(Op, DAG, 7445 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7446 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7447 return lowerStructBufferAtomicIntrin(Op, DAG, 7448 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7449 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7450 return lowerStructBufferAtomicIntrin(Op, DAG, 7451 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7452 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7453 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7454 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7455 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7456 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7457 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7458 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7459 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7460 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7461 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7462 7463 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7464 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7465 unsigned IdxEn = getIdxEn(Op.getOperand(5)); 7466 SDValue Ops[] = { 7467 Op.getOperand(0), // Chain 7468 Op.getOperand(2), // src 7469 Op.getOperand(3), // cmp 7470 Op.getOperand(4), // rsrc 7471 Op.getOperand(5), // vindex 7472 SDValue(), // voffset -- will be set by setBufferOffsets 7473 SDValue(), // soffset -- will be set by setBufferOffsets 7474 SDValue(), // offset -- will be set by setBufferOffsets 7475 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7476 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7477 }; 7478 setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7479 7480 EVT VT = Op.getValueType(); 7481 auto *M = cast<MemSDNode>(Op); 7482 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7483 7484 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7485 Op->getVTList(), Ops, VT, M->getMemOperand()); 7486 } 7487 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7488 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7489 SDValue Ops[] = { 7490 Op.getOperand(0), // Chain 7491 Op.getOperand(2), // src 7492 Op.getOperand(3), // cmp 7493 Op.getOperand(4), // rsrc 7494 DAG.getConstant(0, DL, MVT::i32), // vindex 7495 Offsets.first, // voffset 7496 Op.getOperand(6), // soffset 7497 Offsets.second, // offset 7498 Op.getOperand(7), // cachepolicy 7499 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7500 }; 7501 EVT VT = Op.getValueType(); 7502 auto *M = cast<MemSDNode>(Op); 7503 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]); 7504 7505 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7506 Op->getVTList(), Ops, VT, M->getMemOperand()); 7507 } 7508 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7509 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7510 SDValue Ops[] = { 7511 Op.getOperand(0), // Chain 7512 Op.getOperand(2), // src 7513 Op.getOperand(3), // cmp 7514 Op.getOperand(4), // rsrc 7515 Op.getOperand(5), // vindex 7516 Offsets.first, // voffset 7517 Op.getOperand(7), // soffset 7518 Offsets.second, // offset 7519 Op.getOperand(8), // cachepolicy 7520 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7521 }; 7522 EVT VT = Op.getValueType(); 7523 auto *M = cast<MemSDNode>(Op); 7524 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7525 7526 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7527 Op->getVTList(), Ops, VT, M->getMemOperand()); 7528 } 7529 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 7530 MemSDNode *M = cast<MemSDNode>(Op); 7531 SDValue NodePtr = M->getOperand(2); 7532 SDValue RayExtent = M->getOperand(3); 7533 SDValue RayOrigin = M->getOperand(4); 7534 SDValue RayDir = M->getOperand(5); 7535 SDValue RayInvDir = M->getOperand(6); 7536 SDValue TDescr = M->getOperand(7); 7537 7538 assert(NodePtr.getValueType() == MVT::i32 || 7539 NodePtr.getValueType() == MVT::i64); 7540 assert(RayDir.getValueType() == MVT::v3f16 || 7541 RayDir.getValueType() == MVT::v3f32); 7542 7543 if (!Subtarget->hasGFX10_AEncoding()) { 7544 emitRemovedIntrinsicError(DAG, DL, Op.getValueType()); 7545 return SDValue(); 7546 } 7547 7548 const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16; 7549 const bool Is64 = NodePtr.getValueType() == MVT::i64; 7550 const unsigned NumVDataDwords = 4; 7551 const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11); 7552 const bool UseNSA = Subtarget->hasNSAEncoding() && 7553 NumVAddrDwords <= Subtarget->getNSAMaxSize(); 7554 const unsigned BaseOpcodes[2][2] = { 7555 {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16}, 7556 {AMDGPU::IMAGE_BVH64_INTERSECT_RAY, 7557 AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}}; 7558 int Opcode; 7559 if (UseNSA) { 7560 Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16], 7561 AMDGPU::MIMGEncGfx10NSA, NumVDataDwords, 7562 NumVAddrDwords); 7563 } else { 7564 Opcode = AMDGPU::getMIMGOpcode( 7565 BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords, 7566 PowerOf2Ceil(NumVAddrDwords)); 7567 } 7568 assert(Opcode != -1); 7569 7570 SmallVector<SDValue, 16> Ops; 7571 7572 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) { 7573 SmallVector<SDValue, 3> Lanes; 7574 DAG.ExtractVectorElements(Op, Lanes, 0, 3); 7575 if (Lanes[0].getValueSizeInBits() == 32) { 7576 for (unsigned I = 0; I < 3; ++I) 7577 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I])); 7578 } else { 7579 if (IsAligned) { 7580 Ops.push_back( 7581 DAG.getBitcast(MVT::i32, 7582 DAG.getBuildVector(MVT::v2f16, DL, 7583 { Lanes[0], Lanes[1] }))); 7584 Ops.push_back(Lanes[2]); 7585 } else { 7586 SDValue Elt0 = Ops.pop_back_val(); 7587 Ops.push_back( 7588 DAG.getBitcast(MVT::i32, 7589 DAG.getBuildVector(MVT::v2f16, DL, 7590 { Elt0, Lanes[0] }))); 7591 Ops.push_back( 7592 DAG.getBitcast(MVT::i32, 7593 DAG.getBuildVector(MVT::v2f16, DL, 7594 { Lanes[1], Lanes[2] }))); 7595 } 7596 } 7597 }; 7598 7599 if (Is64) 7600 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2); 7601 else 7602 Ops.push_back(NodePtr); 7603 7604 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7605 packLanes(RayOrigin, true); 7606 packLanes(RayDir, true); 7607 packLanes(RayInvDir, false); 7608 7609 if (!UseNSA) { 7610 // Build a single vector containing all the operands so far prepared. 7611 if (NumVAddrDwords > 8) { 7612 SDValue Undef = DAG.getUNDEF(MVT::i32); 7613 Ops.append(16 - Ops.size(), Undef); 7614 } 7615 assert(Ops.size() == 8 || Ops.size() == 16); 7616 SDValue MergedOps = DAG.getBuildVector( 7617 Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops); 7618 Ops.clear(); 7619 Ops.push_back(MergedOps); 7620 } 7621 7622 Ops.push_back(TDescr); 7623 if (IsA16) 7624 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1)); 7625 Ops.push_back(M->getChain()); 7626 7627 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops); 7628 MachineMemOperand *MemRef = M->getMemOperand(); 7629 DAG.setNodeMemRefs(NewNode, {MemRef}); 7630 return SDValue(NewNode, 0); 7631 } 7632 case Intrinsic::amdgcn_global_atomic_fadd: 7633 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7634 DiagnosticInfoUnsupported 7635 NoFpRet(DAG.getMachineFunction().getFunction(), 7636 "return versions of fp atomics not supported", 7637 DL.getDebugLoc(), DS_Error); 7638 DAG.getContext()->diagnose(NoFpRet); 7639 return SDValue(); 7640 } 7641 LLVM_FALLTHROUGH; 7642 case Intrinsic::amdgcn_global_atomic_fmin: 7643 case Intrinsic::amdgcn_global_atomic_fmax: 7644 case Intrinsic::amdgcn_flat_atomic_fadd: 7645 case Intrinsic::amdgcn_flat_atomic_fmin: 7646 case Intrinsic::amdgcn_flat_atomic_fmax: { 7647 MemSDNode *M = cast<MemSDNode>(Op); 7648 SDValue Ops[] = { 7649 M->getOperand(0), // Chain 7650 M->getOperand(2), // Ptr 7651 M->getOperand(3) // Value 7652 }; 7653 unsigned Opcode = 0; 7654 switch (IntrID) { 7655 case Intrinsic::amdgcn_global_atomic_fadd: 7656 case Intrinsic::amdgcn_flat_atomic_fadd: { 7657 EVT VT = Op.getOperand(3).getValueType(); 7658 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7659 DAG.getVTList(VT, MVT::Other), Ops, 7660 M->getMemOperand()); 7661 } 7662 case Intrinsic::amdgcn_global_atomic_fmin: 7663 case Intrinsic::amdgcn_flat_atomic_fmin: { 7664 Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN; 7665 break; 7666 } 7667 case Intrinsic::amdgcn_global_atomic_fmax: 7668 case Intrinsic::amdgcn_flat_atomic_fmax: { 7669 Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX; 7670 break; 7671 } 7672 default: 7673 llvm_unreachable("unhandled atomic opcode"); 7674 } 7675 return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op), 7676 M->getVTList(), Ops, M->getMemoryVT(), 7677 M->getMemOperand()); 7678 } 7679 default: 7680 7681 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7682 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7683 return lowerImage(Op, ImageDimIntr, DAG, true); 7684 7685 return SDValue(); 7686 } 7687 } 7688 7689 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7690 // dwordx4 if on SI. 7691 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7692 SDVTList VTList, 7693 ArrayRef<SDValue> Ops, EVT MemVT, 7694 MachineMemOperand *MMO, 7695 SelectionDAG &DAG) const { 7696 EVT VT = VTList.VTs[0]; 7697 EVT WidenedVT = VT; 7698 EVT WidenedMemVT = MemVT; 7699 if (!Subtarget->hasDwordx3LoadStores() && 7700 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7701 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7702 WidenedVT.getVectorElementType(), 4); 7703 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7704 WidenedMemVT.getVectorElementType(), 4); 7705 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7706 } 7707 7708 assert(VTList.NumVTs == 2); 7709 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7710 7711 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7712 WidenedMemVT, MMO); 7713 if (WidenedVT != VT) { 7714 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7715 DAG.getVectorIdxConstant(0, DL)); 7716 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7717 } 7718 return NewOp; 7719 } 7720 7721 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG, 7722 bool ImageStore) const { 7723 EVT StoreVT = VData.getValueType(); 7724 7725 // No change for f16 and legal vector D16 types. 7726 if (!StoreVT.isVector()) 7727 return VData; 7728 7729 SDLoc DL(VData); 7730 unsigned NumElements = StoreVT.getVectorNumElements(); 7731 7732 if (Subtarget->hasUnpackedD16VMem()) { 7733 // We need to unpack the packed data to store. 7734 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7735 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7736 7737 EVT EquivStoreVT = 7738 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements); 7739 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7740 return DAG.UnrollVectorOp(ZExt.getNode()); 7741 } 7742 7743 // The sq block of gfx8.1 does not estimate register use correctly for d16 7744 // image store instructions. The data operand is computed as if it were not a 7745 // d16 image instruction. 7746 if (ImageStore && Subtarget->hasImageStoreD16Bug()) { 7747 // Bitcast to i16 7748 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7749 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7750 7751 // Decompose into scalars 7752 SmallVector<SDValue, 4> Elts; 7753 DAG.ExtractVectorElements(IntVData, Elts); 7754 7755 // Group pairs of i16 into v2i16 and bitcast to i32 7756 SmallVector<SDValue, 4> PackedElts; 7757 for (unsigned I = 0; I < Elts.size() / 2; I += 1) { 7758 SDValue Pair = 7759 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]}); 7760 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7761 PackedElts.push_back(IntPair); 7762 } 7763 if ((NumElements % 2) == 1) { 7764 // Handle v3i16 7765 unsigned I = Elts.size() / 2; 7766 SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL, 7767 {Elts[I * 2], DAG.getUNDEF(MVT::i16)}); 7768 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7769 PackedElts.push_back(IntPair); 7770 } 7771 7772 // Pad using UNDEF 7773 PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32)); 7774 7775 // Build final vector 7776 EVT VecVT = 7777 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size()); 7778 return DAG.getBuildVector(VecVT, DL, PackedElts); 7779 } 7780 7781 if (NumElements == 3) { 7782 EVT IntStoreVT = 7783 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits()); 7784 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7785 7786 EVT WidenedStoreVT = EVT::getVectorVT( 7787 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1); 7788 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(), 7789 WidenedStoreVT.getStoreSizeInBits()); 7790 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData); 7791 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt); 7792 } 7793 7794 assert(isTypeLegal(StoreVT)); 7795 return VData; 7796 } 7797 7798 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7799 SelectionDAG &DAG) const { 7800 SDLoc DL(Op); 7801 SDValue Chain = Op.getOperand(0); 7802 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7803 MachineFunction &MF = DAG.getMachineFunction(); 7804 7805 switch (IntrinsicID) { 7806 case Intrinsic::amdgcn_exp_compr: { 7807 SDValue Src0 = Op.getOperand(4); 7808 SDValue Src1 = Op.getOperand(5); 7809 // Hack around illegal type on SI by directly selecting it. 7810 if (isTypeLegal(Src0.getValueType())) 7811 return SDValue(); 7812 7813 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7814 SDValue Undef = DAG.getUNDEF(MVT::f32); 7815 const SDValue Ops[] = { 7816 Op.getOperand(2), // tgt 7817 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7818 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7819 Undef, // src2 7820 Undef, // src3 7821 Op.getOperand(7), // vm 7822 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7823 Op.getOperand(3), // en 7824 Op.getOperand(0) // Chain 7825 }; 7826 7827 unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7828 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7829 } 7830 case Intrinsic::amdgcn_s_barrier: { 7831 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7832 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7833 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7834 if (WGSize <= ST.getWavefrontSize()) 7835 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7836 Op.getOperand(0)), 0); 7837 } 7838 return SDValue(); 7839 }; 7840 case Intrinsic::amdgcn_tbuffer_store: { 7841 SDValue VData = Op.getOperand(2); 7842 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7843 if (IsD16) 7844 VData = handleD16VData(VData, DAG); 7845 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7846 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7847 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7848 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7849 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7850 SDValue Ops[] = { 7851 Chain, 7852 VData, // vdata 7853 Op.getOperand(3), // rsrc 7854 Op.getOperand(4), // vindex 7855 Op.getOperand(5), // voffset 7856 Op.getOperand(6), // soffset 7857 Op.getOperand(7), // offset 7858 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7859 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7860 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7861 }; 7862 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7863 AMDGPUISD::TBUFFER_STORE_FORMAT; 7864 MemSDNode *M = cast<MemSDNode>(Op); 7865 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7866 M->getMemoryVT(), M->getMemOperand()); 7867 } 7868 7869 case Intrinsic::amdgcn_struct_tbuffer_store: { 7870 SDValue VData = Op.getOperand(2); 7871 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7872 if (IsD16) 7873 VData = handleD16VData(VData, DAG); 7874 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7875 SDValue Ops[] = { 7876 Chain, 7877 VData, // vdata 7878 Op.getOperand(3), // rsrc 7879 Op.getOperand(4), // vindex 7880 Offsets.first, // voffset 7881 Op.getOperand(6), // soffset 7882 Offsets.second, // offset 7883 Op.getOperand(7), // format 7884 Op.getOperand(8), // cachepolicy, swizzled buffer 7885 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7886 }; 7887 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7888 AMDGPUISD::TBUFFER_STORE_FORMAT; 7889 MemSDNode *M = cast<MemSDNode>(Op); 7890 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7891 M->getMemoryVT(), M->getMemOperand()); 7892 } 7893 7894 case Intrinsic::amdgcn_raw_tbuffer_store: { 7895 SDValue VData = Op.getOperand(2); 7896 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7897 if (IsD16) 7898 VData = handleD16VData(VData, DAG); 7899 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7900 SDValue Ops[] = { 7901 Chain, 7902 VData, // vdata 7903 Op.getOperand(3), // rsrc 7904 DAG.getConstant(0, DL, MVT::i32), // vindex 7905 Offsets.first, // voffset 7906 Op.getOperand(5), // soffset 7907 Offsets.second, // offset 7908 Op.getOperand(6), // format 7909 Op.getOperand(7), // cachepolicy, swizzled buffer 7910 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7911 }; 7912 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7913 AMDGPUISD::TBUFFER_STORE_FORMAT; 7914 MemSDNode *M = cast<MemSDNode>(Op); 7915 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7916 M->getMemoryVT(), M->getMemOperand()); 7917 } 7918 7919 case Intrinsic::amdgcn_buffer_store: 7920 case Intrinsic::amdgcn_buffer_store_format: { 7921 SDValue VData = Op.getOperand(2); 7922 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7923 if (IsD16) 7924 VData = handleD16VData(VData, DAG); 7925 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7926 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7927 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7928 SDValue Ops[] = { 7929 Chain, 7930 VData, 7931 Op.getOperand(3), // rsrc 7932 Op.getOperand(4), // vindex 7933 SDValue(), // voffset -- will be set by setBufferOffsets 7934 SDValue(), // soffset -- will be set by setBufferOffsets 7935 SDValue(), // offset -- will be set by setBufferOffsets 7936 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7937 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7938 }; 7939 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7940 7941 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7942 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7943 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7944 MemSDNode *M = cast<MemSDNode>(Op); 7945 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7946 7947 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7948 EVT VDataType = VData.getValueType().getScalarType(); 7949 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7950 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7951 7952 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7953 M->getMemoryVT(), M->getMemOperand()); 7954 } 7955 7956 case Intrinsic::amdgcn_raw_buffer_store: 7957 case Intrinsic::amdgcn_raw_buffer_store_format: { 7958 const bool IsFormat = 7959 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7960 7961 SDValue VData = Op.getOperand(2); 7962 EVT VDataVT = VData.getValueType(); 7963 EVT EltType = VDataVT.getScalarType(); 7964 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7965 if (IsD16) { 7966 VData = handleD16VData(VData, DAG); 7967 VDataVT = VData.getValueType(); 7968 } 7969 7970 if (!isTypeLegal(VDataVT)) { 7971 VData = 7972 DAG.getNode(ISD::BITCAST, DL, 7973 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7974 } 7975 7976 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7977 SDValue Ops[] = { 7978 Chain, 7979 VData, 7980 Op.getOperand(3), // rsrc 7981 DAG.getConstant(0, DL, MVT::i32), // vindex 7982 Offsets.first, // voffset 7983 Op.getOperand(5), // soffset 7984 Offsets.second, // offset 7985 Op.getOperand(6), // cachepolicy, swizzled buffer 7986 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7987 }; 7988 unsigned Opc = 7989 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7990 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7991 MemSDNode *M = cast<MemSDNode>(Op); 7992 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 7993 7994 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7995 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7996 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7997 7998 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7999 M->getMemoryVT(), M->getMemOperand()); 8000 } 8001 8002 case Intrinsic::amdgcn_struct_buffer_store: 8003 case Intrinsic::amdgcn_struct_buffer_store_format: { 8004 const bool IsFormat = 8005 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 8006 8007 SDValue VData = Op.getOperand(2); 8008 EVT VDataVT = VData.getValueType(); 8009 EVT EltType = VDataVT.getScalarType(); 8010 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 8011 8012 if (IsD16) { 8013 VData = handleD16VData(VData, DAG); 8014 VDataVT = VData.getValueType(); 8015 } 8016 8017 if (!isTypeLegal(VDataVT)) { 8018 VData = 8019 DAG.getNode(ISD::BITCAST, DL, 8020 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 8021 } 8022 8023 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 8024 SDValue Ops[] = { 8025 Chain, 8026 VData, 8027 Op.getOperand(3), // rsrc 8028 Op.getOperand(4), // vindex 8029 Offsets.first, // voffset 8030 Op.getOperand(6), // soffset 8031 Offsets.second, // offset 8032 Op.getOperand(7), // cachepolicy, swizzled buffer 8033 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 8034 }; 8035 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 8036 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 8037 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 8038 MemSDNode *M = cast<MemSDNode>(Op); 8039 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 8040 8041 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 8042 EVT VDataType = VData.getValueType().getScalarType(); 8043 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 8044 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 8045 8046 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8047 M->getMemoryVT(), M->getMemOperand()); 8048 } 8049 case Intrinsic::amdgcn_end_cf: 8050 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 8051 Op->getOperand(2), Chain), 0); 8052 8053 default: { 8054 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 8055 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 8056 return lowerImage(Op, ImageDimIntr, DAG, true); 8057 8058 return Op; 8059 } 8060 } 8061 } 8062 8063 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 8064 // offset (the offset that is included in bounds checking and swizzling, to be 8065 // split between the instruction's voffset and immoffset fields) and soffset 8066 // (the offset that is excluded from bounds checking and swizzling, to go in 8067 // the instruction's soffset field). This function takes the first kind of 8068 // offset and figures out how to split it between voffset and immoffset. 8069 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 8070 SDValue Offset, SelectionDAG &DAG) const { 8071 SDLoc DL(Offset); 8072 const unsigned MaxImm = 4095; 8073 SDValue N0 = Offset; 8074 ConstantSDNode *C1 = nullptr; 8075 8076 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 8077 N0 = SDValue(); 8078 else if (DAG.isBaseWithConstantOffset(N0)) { 8079 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 8080 N0 = N0.getOperand(0); 8081 } 8082 8083 if (C1) { 8084 unsigned ImmOffset = C1->getZExtValue(); 8085 // If the immediate value is too big for the immoffset field, put the value 8086 // and -4096 into the immoffset field so that the value that is copied/added 8087 // for the voffset field is a multiple of 4096, and it stands more chance 8088 // of being CSEd with the copy/add for another similar load/store. 8089 // However, do not do that rounding down to a multiple of 4096 if that is a 8090 // negative number, as it appears to be illegal to have a negative offset 8091 // in the vgpr, even if adding the immediate offset makes it positive. 8092 unsigned Overflow = ImmOffset & ~MaxImm; 8093 ImmOffset -= Overflow; 8094 if ((int32_t)Overflow < 0) { 8095 Overflow += ImmOffset; 8096 ImmOffset = 0; 8097 } 8098 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 8099 if (Overflow) { 8100 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 8101 if (!N0) 8102 N0 = OverflowVal; 8103 else { 8104 SDValue Ops[] = { N0, OverflowVal }; 8105 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 8106 } 8107 } 8108 } 8109 if (!N0) 8110 N0 = DAG.getConstant(0, DL, MVT::i32); 8111 if (!C1) 8112 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 8113 return {N0, SDValue(C1, 0)}; 8114 } 8115 8116 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 8117 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 8118 // pointed to by Offsets. 8119 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 8120 SelectionDAG &DAG, SDValue *Offsets, 8121 Align Alignment) const { 8122 SDLoc DL(CombinedOffset); 8123 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 8124 uint32_t Imm = C->getZExtValue(); 8125 uint32_t SOffset, ImmOffset; 8126 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 8127 Alignment)) { 8128 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 8129 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 8130 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 8131 return; 8132 } 8133 } 8134 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 8135 SDValue N0 = CombinedOffset.getOperand(0); 8136 SDValue N1 = CombinedOffset.getOperand(1); 8137 uint32_t SOffset, ImmOffset; 8138 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 8139 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 8140 Subtarget, Alignment)) { 8141 Offsets[0] = N0; 8142 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 8143 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 8144 return; 8145 } 8146 } 8147 Offsets[0] = CombinedOffset; 8148 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 8149 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 8150 } 8151 8152 // Handle 8 bit and 16 bit buffer loads 8153 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 8154 EVT LoadVT, SDLoc DL, 8155 ArrayRef<SDValue> Ops, 8156 MemSDNode *M) const { 8157 EVT IntVT = LoadVT.changeTypeToInteger(); 8158 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 8159 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 8160 8161 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 8162 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 8163 Ops, IntVT, 8164 M->getMemOperand()); 8165 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 8166 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 8167 8168 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 8169 } 8170 8171 // Handle 8 bit and 16 bit buffer stores 8172 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 8173 EVT VDataType, SDLoc DL, 8174 SDValue Ops[], 8175 MemSDNode *M) const { 8176 if (VDataType == MVT::f16) 8177 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 8178 8179 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 8180 Ops[1] = BufferStoreExt; 8181 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 8182 AMDGPUISD::BUFFER_STORE_SHORT; 8183 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 8184 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 8185 M->getMemOperand()); 8186 } 8187 8188 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 8189 ISD::LoadExtType ExtType, SDValue Op, 8190 const SDLoc &SL, EVT VT) { 8191 if (VT.bitsLT(Op.getValueType())) 8192 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 8193 8194 switch (ExtType) { 8195 case ISD::SEXTLOAD: 8196 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 8197 case ISD::ZEXTLOAD: 8198 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 8199 case ISD::EXTLOAD: 8200 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 8201 case ISD::NON_EXTLOAD: 8202 return Op; 8203 } 8204 8205 llvm_unreachable("invalid ext type"); 8206 } 8207 8208 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 8209 SelectionDAG &DAG = DCI.DAG; 8210 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 8211 return SDValue(); 8212 8213 // FIXME: Constant loads should all be marked invariant. 8214 unsigned AS = Ld->getAddressSpace(); 8215 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 8216 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 8217 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 8218 return SDValue(); 8219 8220 // Don't do this early, since it may interfere with adjacent load merging for 8221 // illegal types. We can avoid losing alignment information for exotic types 8222 // pre-legalize. 8223 EVT MemVT = Ld->getMemoryVT(); 8224 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 8225 MemVT.getSizeInBits() >= 32) 8226 return SDValue(); 8227 8228 SDLoc SL(Ld); 8229 8230 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 8231 "unexpected vector extload"); 8232 8233 // TODO: Drop only high part of range. 8234 SDValue Ptr = Ld->getBasePtr(); 8235 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 8236 MVT::i32, SL, Ld->getChain(), Ptr, 8237 Ld->getOffset(), 8238 Ld->getPointerInfo(), MVT::i32, 8239 Ld->getAlignment(), 8240 Ld->getMemOperand()->getFlags(), 8241 Ld->getAAInfo(), 8242 nullptr); // Drop ranges 8243 8244 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 8245 if (MemVT.isFloatingPoint()) { 8246 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 8247 "unexpected fp extload"); 8248 TruncVT = MemVT.changeTypeToInteger(); 8249 } 8250 8251 SDValue Cvt = NewLoad; 8252 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 8253 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 8254 DAG.getValueType(TruncVT)); 8255 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 8256 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 8257 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 8258 } else { 8259 assert(Ld->getExtensionType() == ISD::EXTLOAD); 8260 } 8261 8262 EVT VT = Ld->getValueType(0); 8263 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 8264 8265 DCI.AddToWorklist(Cvt.getNode()); 8266 8267 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 8268 // the appropriate extension from the 32-bit load. 8269 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 8270 DCI.AddToWorklist(Cvt.getNode()); 8271 8272 // Handle conversion back to floating point if necessary. 8273 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 8274 8275 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 8276 } 8277 8278 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 8279 SDLoc DL(Op); 8280 LoadSDNode *Load = cast<LoadSDNode>(Op); 8281 ISD::LoadExtType ExtType = Load->getExtensionType(); 8282 EVT MemVT = Load->getMemoryVT(); 8283 8284 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 8285 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 8286 return SDValue(); 8287 8288 // FIXME: Copied from PPC 8289 // First, load into 32 bits, then truncate to 1 bit. 8290 8291 SDValue Chain = Load->getChain(); 8292 SDValue BasePtr = Load->getBasePtr(); 8293 MachineMemOperand *MMO = Load->getMemOperand(); 8294 8295 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 8296 8297 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 8298 BasePtr, RealMemVT, MMO); 8299 8300 if (!MemVT.isVector()) { 8301 SDValue Ops[] = { 8302 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 8303 NewLD.getValue(1) 8304 }; 8305 8306 return DAG.getMergeValues(Ops, DL); 8307 } 8308 8309 SmallVector<SDValue, 3> Elts; 8310 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 8311 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 8312 DAG.getConstant(I, DL, MVT::i32)); 8313 8314 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 8315 } 8316 8317 SDValue Ops[] = { 8318 DAG.getBuildVector(MemVT, DL, Elts), 8319 NewLD.getValue(1) 8320 }; 8321 8322 return DAG.getMergeValues(Ops, DL); 8323 } 8324 8325 if (!MemVT.isVector()) 8326 return SDValue(); 8327 8328 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 8329 "Custom lowering for non-i32 vectors hasn't been implemented."); 8330 8331 unsigned Alignment = Load->getAlignment(); 8332 unsigned AS = Load->getAddressSpace(); 8333 if (Subtarget->hasLDSMisalignedBug() && 8334 AS == AMDGPUAS::FLAT_ADDRESS && 8335 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 8336 return SplitVectorLoad(Op, DAG); 8337 } 8338 8339 MachineFunction &MF = DAG.getMachineFunction(); 8340 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8341 // If there is a possibilty that flat instruction access scratch memory 8342 // then we need to use the same legalization rules we use for private. 8343 if (AS == AMDGPUAS::FLAT_ADDRESS && 8344 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8345 AS = MFI->hasFlatScratchInit() ? 8346 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8347 8348 unsigned NumElements = MemVT.getVectorNumElements(); 8349 8350 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8351 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 8352 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 8353 if (MemVT.isPow2VectorType()) 8354 return SDValue(); 8355 return WidenOrSplitVectorLoad(Op, DAG); 8356 } 8357 // Non-uniform loads will be selected to MUBUF instructions, so they 8358 // have the same legalization requirements as global and private 8359 // loads. 8360 // 8361 } 8362 8363 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8364 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8365 AS == AMDGPUAS::GLOBAL_ADDRESS) { 8366 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 8367 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 8368 Alignment >= 4 && NumElements < 32) { 8369 if (MemVT.isPow2VectorType()) 8370 return SDValue(); 8371 return WidenOrSplitVectorLoad(Op, DAG); 8372 } 8373 // Non-uniform loads will be selected to MUBUF instructions, so they 8374 // have the same legalization requirements as global and private 8375 // loads. 8376 // 8377 } 8378 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8379 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8380 AS == AMDGPUAS::GLOBAL_ADDRESS || 8381 AS == AMDGPUAS::FLAT_ADDRESS) { 8382 if (NumElements > 4) 8383 return SplitVectorLoad(Op, DAG); 8384 // v3 loads not supported on SI. 8385 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8386 return WidenOrSplitVectorLoad(Op, DAG); 8387 8388 // v3 and v4 loads are supported for private and global memory. 8389 return SDValue(); 8390 } 8391 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8392 // Depending on the setting of the private_element_size field in the 8393 // resource descriptor, we can only make private accesses up to a certain 8394 // size. 8395 switch (Subtarget->getMaxPrivateElementSize()) { 8396 case 4: { 8397 SDValue Ops[2]; 8398 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 8399 return DAG.getMergeValues(Ops, DL); 8400 } 8401 case 8: 8402 if (NumElements > 2) 8403 return SplitVectorLoad(Op, DAG); 8404 return SDValue(); 8405 case 16: 8406 // Same as global/flat 8407 if (NumElements > 4) 8408 return SplitVectorLoad(Op, DAG); 8409 // v3 loads not supported on SI. 8410 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8411 return WidenOrSplitVectorLoad(Op, DAG); 8412 8413 return SDValue(); 8414 default: 8415 llvm_unreachable("unsupported private_element_size"); 8416 } 8417 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8418 // Use ds_read_b128 or ds_read_b96 when possible. 8419 if (Subtarget->hasDS96AndDS128() && 8420 ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) || 8421 MemVT.getStoreSize() == 12) && 8422 allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 8423 Load->getAlign())) 8424 return SDValue(); 8425 8426 if (NumElements > 2) 8427 return SplitVectorLoad(Op, DAG); 8428 8429 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8430 // address is negative, then the instruction is incorrectly treated as 8431 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8432 // loads here to avoid emitting ds_read2_b32. We may re-combine the 8433 // load later in the SILoadStoreOptimizer. 8434 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 8435 NumElements == 2 && MemVT.getStoreSize() == 8 && 8436 Load->getAlignment() < 8) { 8437 return SplitVectorLoad(Op, DAG); 8438 } 8439 } 8440 8441 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8442 MemVT, *Load->getMemOperand())) { 8443 SDValue Ops[2]; 8444 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 8445 return DAG.getMergeValues(Ops, DL); 8446 } 8447 8448 return SDValue(); 8449 } 8450 8451 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8452 EVT VT = Op.getValueType(); 8453 assert(VT.getSizeInBits() == 64); 8454 8455 SDLoc DL(Op); 8456 SDValue Cond = Op.getOperand(0); 8457 8458 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8459 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8460 8461 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8462 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8463 8464 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8465 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8466 8467 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8468 8469 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8470 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8471 8472 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8473 8474 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8475 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8476 } 8477 8478 // Catch division cases where we can use shortcuts with rcp and rsq 8479 // instructions. 8480 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8481 SelectionDAG &DAG) const { 8482 SDLoc SL(Op); 8483 SDValue LHS = Op.getOperand(0); 8484 SDValue RHS = Op.getOperand(1); 8485 EVT VT = Op.getValueType(); 8486 const SDNodeFlags Flags = Op->getFlags(); 8487 8488 bool AllowInaccurateRcp = Flags.hasApproximateFuncs(); 8489 8490 // Without !fpmath accuracy information, we can't do more because we don't 8491 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8492 if (!AllowInaccurateRcp) 8493 return SDValue(); 8494 8495 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8496 if (CLHS->isExactlyValue(1.0)) { 8497 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8498 // the CI documentation has a worst case error of 1 ulp. 8499 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8500 // use it as long as we aren't trying to use denormals. 8501 // 8502 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8503 8504 // 1.0 / sqrt(x) -> rsq(x) 8505 8506 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8507 // error seems really high at 2^29 ULP. 8508 if (RHS.getOpcode() == ISD::FSQRT) 8509 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8510 8511 // 1.0 / x -> rcp(x) 8512 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8513 } 8514 8515 // Same as for 1.0, but expand the sign out of the constant. 8516 if (CLHS->isExactlyValue(-1.0)) { 8517 // -1.0 / x -> rcp (fneg x) 8518 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8519 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8520 } 8521 } 8522 8523 // Turn into multiply by the reciprocal. 8524 // x / y -> x * (1.0 / y) 8525 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8526 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8527 } 8528 8529 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op, 8530 SelectionDAG &DAG) const { 8531 SDLoc SL(Op); 8532 SDValue X = Op.getOperand(0); 8533 SDValue Y = Op.getOperand(1); 8534 EVT VT = Op.getValueType(); 8535 const SDNodeFlags Flags = Op->getFlags(); 8536 8537 bool AllowInaccurateDiv = Flags.hasApproximateFuncs() || 8538 DAG.getTarget().Options.UnsafeFPMath; 8539 if (!AllowInaccurateDiv) 8540 return SDValue(); 8541 8542 SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y); 8543 SDValue One = DAG.getConstantFP(1.0, SL, VT); 8544 8545 SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y); 8546 SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8547 8548 R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R); 8549 SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8550 R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R); 8551 SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R); 8552 SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X); 8553 return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret); 8554 } 8555 8556 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8557 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8558 SDNodeFlags Flags) { 8559 if (GlueChain->getNumValues() <= 1) { 8560 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8561 } 8562 8563 assert(GlueChain->getNumValues() == 3); 8564 8565 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8566 switch (Opcode) { 8567 default: llvm_unreachable("no chain equivalent for opcode"); 8568 case ISD::FMUL: 8569 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8570 break; 8571 } 8572 8573 return DAG.getNode(Opcode, SL, VTList, 8574 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8575 Flags); 8576 } 8577 8578 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8579 EVT VT, SDValue A, SDValue B, SDValue C, 8580 SDValue GlueChain, SDNodeFlags Flags) { 8581 if (GlueChain->getNumValues() <= 1) { 8582 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8583 } 8584 8585 assert(GlueChain->getNumValues() == 3); 8586 8587 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8588 switch (Opcode) { 8589 default: llvm_unreachable("no chain equivalent for opcode"); 8590 case ISD::FMA: 8591 Opcode = AMDGPUISD::FMA_W_CHAIN; 8592 break; 8593 } 8594 8595 return DAG.getNode(Opcode, SL, VTList, 8596 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8597 Flags); 8598 } 8599 8600 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8601 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8602 return FastLowered; 8603 8604 SDLoc SL(Op); 8605 SDValue Src0 = Op.getOperand(0); 8606 SDValue Src1 = Op.getOperand(1); 8607 8608 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8609 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8610 8611 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8612 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8613 8614 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8615 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8616 8617 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8618 } 8619 8620 // Faster 2.5 ULP division that does not support denormals. 8621 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8622 SDLoc SL(Op); 8623 SDValue LHS = Op.getOperand(1); 8624 SDValue RHS = Op.getOperand(2); 8625 8626 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8627 8628 const APFloat K0Val(BitsToFloat(0x6f800000)); 8629 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8630 8631 const APFloat K1Val(BitsToFloat(0x2f800000)); 8632 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8633 8634 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8635 8636 EVT SetCCVT = 8637 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8638 8639 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8640 8641 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8642 8643 // TODO: Should this propagate fast-math-flags? 8644 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8645 8646 // rcp does not support denormals. 8647 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8648 8649 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8650 8651 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8652 } 8653 8654 // Returns immediate value for setting the F32 denorm mode when using the 8655 // S_DENORM_MODE instruction. 8656 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8657 const SDLoc &SL, const GCNSubtarget *ST) { 8658 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8659 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8660 ? FP_DENORM_FLUSH_NONE 8661 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8662 8663 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8664 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8665 } 8666 8667 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8668 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8669 return FastLowered; 8670 8671 // The selection matcher assumes anything with a chain selecting to a 8672 // mayRaiseFPException machine instruction. Since we're introducing a chain 8673 // here, we need to explicitly report nofpexcept for the regular fdiv 8674 // lowering. 8675 SDNodeFlags Flags = Op->getFlags(); 8676 Flags.setNoFPExcept(true); 8677 8678 SDLoc SL(Op); 8679 SDValue LHS = Op.getOperand(0); 8680 SDValue RHS = Op.getOperand(1); 8681 8682 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8683 8684 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8685 8686 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8687 {RHS, RHS, LHS}, Flags); 8688 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8689 {LHS, RHS, LHS}, Flags); 8690 8691 // Denominator is scaled to not be denormal, so using rcp is ok. 8692 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8693 DenominatorScaled, Flags); 8694 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8695 DenominatorScaled, Flags); 8696 8697 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8698 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8699 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8700 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8701 8702 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8703 8704 if (!HasFP32Denormals) { 8705 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8706 // lowering. The chain dependence is insufficient, and we need glue. We do 8707 // not need the glue variants in a strictfp function. 8708 8709 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8710 8711 SDNode *EnableDenorm; 8712 if (Subtarget->hasDenormModeInst()) { 8713 const SDValue EnableDenormValue = 8714 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8715 8716 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8717 DAG.getEntryNode(), EnableDenormValue).getNode(); 8718 } else { 8719 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8720 SL, MVT::i32); 8721 EnableDenorm = 8722 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8723 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8724 } 8725 8726 SDValue Ops[3] = { 8727 NegDivScale0, 8728 SDValue(EnableDenorm, 0), 8729 SDValue(EnableDenorm, 1) 8730 }; 8731 8732 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8733 } 8734 8735 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8736 ApproxRcp, One, NegDivScale0, Flags); 8737 8738 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8739 ApproxRcp, Fma0, Flags); 8740 8741 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8742 Fma1, Fma1, Flags); 8743 8744 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8745 NumeratorScaled, Mul, Flags); 8746 8747 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8748 Fma2, Fma1, Mul, Fma2, Flags); 8749 8750 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8751 NumeratorScaled, Fma3, Flags); 8752 8753 if (!HasFP32Denormals) { 8754 SDNode *DisableDenorm; 8755 if (Subtarget->hasDenormModeInst()) { 8756 const SDValue DisableDenormValue = 8757 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8758 8759 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8760 Fma4.getValue(1), DisableDenormValue, 8761 Fma4.getValue(2)).getNode(); 8762 } else { 8763 const SDValue DisableDenormValue = 8764 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8765 8766 DisableDenorm = DAG.getMachineNode( 8767 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8768 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8769 } 8770 8771 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8772 SDValue(DisableDenorm, 0), DAG.getRoot()); 8773 DAG.setRoot(OutputChain); 8774 } 8775 8776 SDValue Scale = NumeratorScaled.getValue(1); 8777 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8778 {Fma4, Fma1, Fma3, Scale}, Flags); 8779 8780 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8781 } 8782 8783 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8784 if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG)) 8785 return FastLowered; 8786 8787 SDLoc SL(Op); 8788 SDValue X = Op.getOperand(0); 8789 SDValue Y = Op.getOperand(1); 8790 8791 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8792 8793 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8794 8795 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8796 8797 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8798 8799 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8800 8801 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8802 8803 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8804 8805 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8806 8807 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8808 8809 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8810 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8811 8812 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8813 NegDivScale0, Mul, DivScale1); 8814 8815 SDValue Scale; 8816 8817 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8818 // Workaround a hardware bug on SI where the condition output from div_scale 8819 // is not usable. 8820 8821 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8822 8823 // Figure out if the scale to use for div_fmas. 8824 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8825 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8826 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8827 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8828 8829 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8830 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8831 8832 SDValue Scale0Hi 8833 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8834 SDValue Scale1Hi 8835 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8836 8837 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8838 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8839 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8840 } else { 8841 Scale = DivScale1.getValue(1); 8842 } 8843 8844 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8845 Fma4, Fma3, Mul, Scale); 8846 8847 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8848 } 8849 8850 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8851 EVT VT = Op.getValueType(); 8852 8853 if (VT == MVT::f32) 8854 return LowerFDIV32(Op, DAG); 8855 8856 if (VT == MVT::f64) 8857 return LowerFDIV64(Op, DAG); 8858 8859 if (VT == MVT::f16) 8860 return LowerFDIV16(Op, DAG); 8861 8862 llvm_unreachable("Unexpected type for fdiv"); 8863 } 8864 8865 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8866 SDLoc DL(Op); 8867 StoreSDNode *Store = cast<StoreSDNode>(Op); 8868 EVT VT = Store->getMemoryVT(); 8869 8870 if (VT == MVT::i1) { 8871 return DAG.getTruncStore(Store->getChain(), DL, 8872 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8873 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8874 } 8875 8876 assert(VT.isVector() && 8877 Store->getValue().getValueType().getScalarType() == MVT::i32); 8878 8879 unsigned AS = Store->getAddressSpace(); 8880 if (Subtarget->hasLDSMisalignedBug() && 8881 AS == AMDGPUAS::FLAT_ADDRESS && 8882 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8883 return SplitVectorStore(Op, DAG); 8884 } 8885 8886 MachineFunction &MF = DAG.getMachineFunction(); 8887 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8888 // If there is a possibilty that flat instruction access scratch memory 8889 // then we need to use the same legalization rules we use for private. 8890 if (AS == AMDGPUAS::FLAT_ADDRESS && 8891 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8892 AS = MFI->hasFlatScratchInit() ? 8893 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8894 8895 unsigned NumElements = VT.getVectorNumElements(); 8896 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8897 AS == AMDGPUAS::FLAT_ADDRESS) { 8898 if (NumElements > 4) 8899 return SplitVectorStore(Op, DAG); 8900 // v3 stores not supported on SI. 8901 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8902 return SplitVectorStore(Op, DAG); 8903 8904 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8905 VT, *Store->getMemOperand())) 8906 return expandUnalignedStore(Store, DAG); 8907 8908 return SDValue(); 8909 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8910 switch (Subtarget->getMaxPrivateElementSize()) { 8911 case 4: 8912 return scalarizeVectorStore(Store, DAG); 8913 case 8: 8914 if (NumElements > 2) 8915 return SplitVectorStore(Op, DAG); 8916 return SDValue(); 8917 case 16: 8918 if (NumElements > 4 || 8919 (NumElements == 3 && !Subtarget->enableFlatScratch())) 8920 return SplitVectorStore(Op, DAG); 8921 return SDValue(); 8922 default: 8923 llvm_unreachable("unsupported private_element_size"); 8924 } 8925 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8926 // Use ds_write_b128 or ds_write_b96 when possible. 8927 if (Subtarget->hasDS96AndDS128() && 8928 ((Subtarget->useDS128() && VT.getStoreSize() == 16) || 8929 (VT.getStoreSize() == 12)) && 8930 allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 8931 Store->getAlign())) 8932 return SDValue(); 8933 8934 if (NumElements > 2) 8935 return SplitVectorStore(Op, DAG); 8936 8937 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8938 // address is negative, then the instruction is incorrectly treated as 8939 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8940 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8941 // store later in the SILoadStoreOptimizer. 8942 if (!Subtarget->hasUsableDSOffset() && 8943 NumElements == 2 && VT.getStoreSize() == 8 && 8944 Store->getAlignment() < 8) { 8945 return SplitVectorStore(Op, DAG); 8946 } 8947 8948 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8949 VT, *Store->getMemOperand())) { 8950 if (VT.isVector()) 8951 return SplitVectorStore(Op, DAG); 8952 return expandUnalignedStore(Store, DAG); 8953 } 8954 8955 return SDValue(); 8956 } else { 8957 llvm_unreachable("unhandled address space"); 8958 } 8959 } 8960 8961 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8962 SDLoc DL(Op); 8963 EVT VT = Op.getValueType(); 8964 SDValue Arg = Op.getOperand(0); 8965 SDValue TrigVal; 8966 8967 // Propagate fast-math flags so that the multiply we introduce can be folded 8968 // if Arg is already the result of a multiply by constant. 8969 auto Flags = Op->getFlags(); 8970 8971 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 8972 8973 if (Subtarget->hasTrigReducedRange()) { 8974 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8975 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 8976 } else { 8977 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8978 } 8979 8980 switch (Op.getOpcode()) { 8981 case ISD::FCOS: 8982 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 8983 case ISD::FSIN: 8984 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 8985 default: 8986 llvm_unreachable("Wrong trig opcode"); 8987 } 8988 } 8989 8990 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8991 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8992 assert(AtomicNode->isCompareAndSwap()); 8993 unsigned AS = AtomicNode->getAddressSpace(); 8994 8995 // No custom lowering required for local address space 8996 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 8997 return Op; 8998 8999 // Non-local address space requires custom lowering for atomic compare 9000 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 9001 SDLoc DL(Op); 9002 SDValue ChainIn = Op.getOperand(0); 9003 SDValue Addr = Op.getOperand(1); 9004 SDValue Old = Op.getOperand(2); 9005 SDValue New = Op.getOperand(3); 9006 EVT VT = Op.getValueType(); 9007 MVT SimpleVT = VT.getSimpleVT(); 9008 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 9009 9010 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 9011 SDValue Ops[] = { ChainIn, Addr, NewOld }; 9012 9013 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 9014 Ops, VT, AtomicNode->getMemOperand()); 9015 } 9016 9017 //===----------------------------------------------------------------------===// 9018 // Custom DAG optimizations 9019 //===----------------------------------------------------------------------===// 9020 9021 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 9022 DAGCombinerInfo &DCI) const { 9023 EVT VT = N->getValueType(0); 9024 EVT ScalarVT = VT.getScalarType(); 9025 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 9026 return SDValue(); 9027 9028 SelectionDAG &DAG = DCI.DAG; 9029 SDLoc DL(N); 9030 9031 SDValue Src = N->getOperand(0); 9032 EVT SrcVT = Src.getValueType(); 9033 9034 // TODO: We could try to match extracting the higher bytes, which would be 9035 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 9036 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 9037 // about in practice. 9038 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 9039 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 9040 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 9041 DCI.AddToWorklist(Cvt.getNode()); 9042 9043 // For the f16 case, fold to a cast to f32 and then cast back to f16. 9044 if (ScalarVT != MVT::f32) { 9045 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 9046 DAG.getTargetConstant(0, DL, MVT::i32)); 9047 } 9048 return Cvt; 9049 } 9050 } 9051 9052 return SDValue(); 9053 } 9054 9055 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 9056 9057 // This is a variant of 9058 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 9059 // 9060 // The normal DAG combiner will do this, but only if the add has one use since 9061 // that would increase the number of instructions. 9062 // 9063 // This prevents us from seeing a constant offset that can be folded into a 9064 // memory instruction's addressing mode. If we know the resulting add offset of 9065 // a pointer can be folded into an addressing offset, we can replace the pointer 9066 // operand with the add of new constant offset. This eliminates one of the uses, 9067 // and may allow the remaining use to also be simplified. 9068 // 9069 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 9070 unsigned AddrSpace, 9071 EVT MemVT, 9072 DAGCombinerInfo &DCI) const { 9073 SDValue N0 = N->getOperand(0); 9074 SDValue N1 = N->getOperand(1); 9075 9076 // We only do this to handle cases where it's profitable when there are 9077 // multiple uses of the add, so defer to the standard combine. 9078 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 9079 N0->hasOneUse()) 9080 return SDValue(); 9081 9082 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 9083 if (!CN1) 9084 return SDValue(); 9085 9086 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 9087 if (!CAdd) 9088 return SDValue(); 9089 9090 // If the resulting offset is too large, we can't fold it into the addressing 9091 // mode offset. 9092 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 9093 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 9094 9095 AddrMode AM; 9096 AM.HasBaseReg = true; 9097 AM.BaseOffs = Offset.getSExtValue(); 9098 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 9099 return SDValue(); 9100 9101 SelectionDAG &DAG = DCI.DAG; 9102 SDLoc SL(N); 9103 EVT VT = N->getValueType(0); 9104 9105 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 9106 SDValue COffset = DAG.getConstant(Offset, SL, VT); 9107 9108 SDNodeFlags Flags; 9109 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 9110 (N0.getOpcode() == ISD::OR || 9111 N0->getFlags().hasNoUnsignedWrap())); 9112 9113 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 9114 } 9115 9116 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 9117 /// by the chain and intrinsic ID. Theoretically we would also need to check the 9118 /// specific intrinsic, but they all place the pointer operand first. 9119 static unsigned getBasePtrIndex(const MemSDNode *N) { 9120 switch (N->getOpcode()) { 9121 case ISD::STORE: 9122 case ISD::INTRINSIC_W_CHAIN: 9123 case ISD::INTRINSIC_VOID: 9124 return 2; 9125 default: 9126 return 1; 9127 } 9128 } 9129 9130 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 9131 DAGCombinerInfo &DCI) const { 9132 SelectionDAG &DAG = DCI.DAG; 9133 SDLoc SL(N); 9134 9135 unsigned PtrIdx = getBasePtrIndex(N); 9136 SDValue Ptr = N->getOperand(PtrIdx); 9137 9138 // TODO: We could also do this for multiplies. 9139 if (Ptr.getOpcode() == ISD::SHL) { 9140 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 9141 N->getMemoryVT(), DCI); 9142 if (NewPtr) { 9143 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 9144 9145 NewOps[PtrIdx] = NewPtr; 9146 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 9147 } 9148 } 9149 9150 return SDValue(); 9151 } 9152 9153 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 9154 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 9155 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 9156 (Opc == ISD::XOR && Val == 0); 9157 } 9158 9159 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 9160 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 9161 // integer combine opportunities since most 64-bit operations are decomposed 9162 // this way. TODO: We won't want this for SALU especially if it is an inline 9163 // immediate. 9164 SDValue SITargetLowering::splitBinaryBitConstantOp( 9165 DAGCombinerInfo &DCI, 9166 const SDLoc &SL, 9167 unsigned Opc, SDValue LHS, 9168 const ConstantSDNode *CRHS) const { 9169 uint64_t Val = CRHS->getZExtValue(); 9170 uint32_t ValLo = Lo_32(Val); 9171 uint32_t ValHi = Hi_32(Val); 9172 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9173 9174 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 9175 bitOpWithConstantIsReducible(Opc, ValHi)) || 9176 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 9177 // If we need to materialize a 64-bit immediate, it will be split up later 9178 // anyway. Avoid creating the harder to understand 64-bit immediate 9179 // materialization. 9180 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 9181 } 9182 9183 return SDValue(); 9184 } 9185 9186 // Returns true if argument is a boolean value which is not serialized into 9187 // memory or argument and does not require v_cndmask_b32 to be deserialized. 9188 static bool isBoolSGPR(SDValue V) { 9189 if (V.getValueType() != MVT::i1) 9190 return false; 9191 switch (V.getOpcode()) { 9192 default: 9193 break; 9194 case ISD::SETCC: 9195 case AMDGPUISD::FP_CLASS: 9196 return true; 9197 case ISD::AND: 9198 case ISD::OR: 9199 case ISD::XOR: 9200 return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1)); 9201 } 9202 return false; 9203 } 9204 9205 // If a constant has all zeroes or all ones within each byte return it. 9206 // Otherwise return 0. 9207 static uint32_t getConstantPermuteMask(uint32_t C) { 9208 // 0xff for any zero byte in the mask 9209 uint32_t ZeroByteMask = 0; 9210 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 9211 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 9212 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 9213 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 9214 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 9215 if ((NonZeroByteMask & C) != NonZeroByteMask) 9216 return 0; // Partial bytes selected. 9217 return C; 9218 } 9219 9220 // Check if a node selects whole bytes from its operand 0 starting at a byte 9221 // boundary while masking the rest. Returns select mask as in the v_perm_b32 9222 // or -1 if not succeeded. 9223 // Note byte select encoding: 9224 // value 0-3 selects corresponding source byte; 9225 // value 0xc selects zero; 9226 // value 0xff selects 0xff. 9227 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 9228 assert(V.getValueSizeInBits() == 32); 9229 9230 if (V.getNumOperands() != 2) 9231 return ~0; 9232 9233 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 9234 if (!N1) 9235 return ~0; 9236 9237 uint32_t C = N1->getZExtValue(); 9238 9239 switch (V.getOpcode()) { 9240 default: 9241 break; 9242 case ISD::AND: 9243 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9244 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 9245 } 9246 break; 9247 9248 case ISD::OR: 9249 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9250 return (0x03020100 & ~ConstMask) | ConstMask; 9251 } 9252 break; 9253 9254 case ISD::SHL: 9255 if (C % 8) 9256 return ~0; 9257 9258 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 9259 9260 case ISD::SRL: 9261 if (C % 8) 9262 return ~0; 9263 9264 return uint32_t(0x0c0c0c0c03020100ull >> C); 9265 } 9266 9267 return ~0; 9268 } 9269 9270 SDValue SITargetLowering::performAndCombine(SDNode *N, 9271 DAGCombinerInfo &DCI) const { 9272 if (DCI.isBeforeLegalize()) 9273 return SDValue(); 9274 9275 SelectionDAG &DAG = DCI.DAG; 9276 EVT VT = N->getValueType(0); 9277 SDValue LHS = N->getOperand(0); 9278 SDValue RHS = N->getOperand(1); 9279 9280 9281 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9282 if (VT == MVT::i64 && CRHS) { 9283 if (SDValue Split 9284 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 9285 return Split; 9286 } 9287 9288 if (CRHS && VT == MVT::i32) { 9289 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 9290 // nb = number of trailing zeroes in mask 9291 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 9292 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 9293 uint64_t Mask = CRHS->getZExtValue(); 9294 unsigned Bits = countPopulation(Mask); 9295 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 9296 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 9297 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 9298 unsigned Shift = CShift->getZExtValue(); 9299 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 9300 unsigned Offset = NB + Shift; 9301 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 9302 SDLoc SL(N); 9303 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 9304 LHS->getOperand(0), 9305 DAG.getConstant(Offset, SL, MVT::i32), 9306 DAG.getConstant(Bits, SL, MVT::i32)); 9307 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9308 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 9309 DAG.getValueType(NarrowVT)); 9310 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 9311 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 9312 return Shl; 9313 } 9314 } 9315 } 9316 9317 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9318 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 9319 isa<ConstantSDNode>(LHS.getOperand(2))) { 9320 uint32_t Sel = getConstantPermuteMask(Mask); 9321 if (!Sel) 9322 return SDValue(); 9323 9324 // Select 0xc for all zero bytes 9325 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 9326 SDLoc DL(N); 9327 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9328 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9329 } 9330 } 9331 9332 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 9333 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 9334 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 9335 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9336 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 9337 9338 SDValue X = LHS.getOperand(0); 9339 SDValue Y = RHS.getOperand(0); 9340 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 9341 return SDValue(); 9342 9343 if (LCC == ISD::SETO) { 9344 if (X != LHS.getOperand(1)) 9345 return SDValue(); 9346 9347 if (RCC == ISD::SETUNE) { 9348 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 9349 if (!C1 || !C1->isInfinity() || C1->isNegative()) 9350 return SDValue(); 9351 9352 const uint32_t Mask = SIInstrFlags::N_NORMAL | 9353 SIInstrFlags::N_SUBNORMAL | 9354 SIInstrFlags::N_ZERO | 9355 SIInstrFlags::P_ZERO | 9356 SIInstrFlags::P_SUBNORMAL | 9357 SIInstrFlags::P_NORMAL; 9358 9359 static_assert(((~(SIInstrFlags::S_NAN | 9360 SIInstrFlags::Q_NAN | 9361 SIInstrFlags::N_INFINITY | 9362 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 9363 "mask not equal"); 9364 9365 SDLoc DL(N); 9366 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9367 X, DAG.getConstant(Mask, DL, MVT::i32)); 9368 } 9369 } 9370 } 9371 9372 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 9373 std::swap(LHS, RHS); 9374 9375 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 9376 RHS.hasOneUse()) { 9377 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9378 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 9379 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 9380 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9381 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 9382 (RHS.getOperand(0) == LHS.getOperand(0) && 9383 LHS.getOperand(0) == LHS.getOperand(1))) { 9384 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 9385 unsigned NewMask = LCC == ISD::SETO ? 9386 Mask->getZExtValue() & ~OrdMask : 9387 Mask->getZExtValue() & OrdMask; 9388 9389 SDLoc DL(N); 9390 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 9391 DAG.getConstant(NewMask, DL, MVT::i32)); 9392 } 9393 } 9394 9395 if (VT == MVT::i32 && 9396 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 9397 // and x, (sext cc from i1) => select cc, x, 0 9398 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 9399 std::swap(LHS, RHS); 9400 if (isBoolSGPR(RHS.getOperand(0))) 9401 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 9402 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 9403 } 9404 9405 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9406 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9407 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9408 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9409 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9410 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9411 if (LHSMask != ~0u && RHSMask != ~0u) { 9412 // Canonicalize the expression in an attempt to have fewer unique masks 9413 // and therefore fewer registers used to hold the masks. 9414 if (LHSMask > RHSMask) { 9415 std::swap(LHSMask, RHSMask); 9416 std::swap(LHS, RHS); 9417 } 9418 9419 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9420 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9421 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9422 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9423 9424 // Check of we need to combine values from two sources within a byte. 9425 if (!(LHSUsedLanes & RHSUsedLanes) && 9426 // If we select high and lower word keep it for SDWA. 9427 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9428 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9429 // Each byte in each mask is either selector mask 0-3, or has higher 9430 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 9431 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 9432 // mask which is not 0xff wins. By anding both masks we have a correct 9433 // result except that 0x0c shall be corrected to give 0x0c only. 9434 uint32_t Mask = LHSMask & RHSMask; 9435 for (unsigned I = 0; I < 32; I += 8) { 9436 uint32_t ByteSel = 0xff << I; 9437 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 9438 Mask &= (0x0c << I) & 0xffffffff; 9439 } 9440 9441 // Add 4 to each active LHS lane. It will not affect any existing 0xff 9442 // or 0x0c. 9443 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 9444 SDLoc DL(N); 9445 9446 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9447 LHS.getOperand(0), RHS.getOperand(0), 9448 DAG.getConstant(Sel, DL, MVT::i32)); 9449 } 9450 } 9451 } 9452 9453 return SDValue(); 9454 } 9455 9456 SDValue SITargetLowering::performOrCombine(SDNode *N, 9457 DAGCombinerInfo &DCI) const { 9458 SelectionDAG &DAG = DCI.DAG; 9459 SDValue LHS = N->getOperand(0); 9460 SDValue RHS = N->getOperand(1); 9461 9462 EVT VT = N->getValueType(0); 9463 if (VT == MVT::i1) { 9464 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 9465 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 9466 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 9467 SDValue Src = LHS.getOperand(0); 9468 if (Src != RHS.getOperand(0)) 9469 return SDValue(); 9470 9471 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9472 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9473 if (!CLHS || !CRHS) 9474 return SDValue(); 9475 9476 // Only 10 bits are used. 9477 static const uint32_t MaxMask = 0x3ff; 9478 9479 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 9480 SDLoc DL(N); 9481 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9482 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 9483 } 9484 9485 return SDValue(); 9486 } 9487 9488 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9489 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 9490 LHS.getOpcode() == AMDGPUISD::PERM && 9491 isa<ConstantSDNode>(LHS.getOperand(2))) { 9492 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 9493 if (!Sel) 9494 return SDValue(); 9495 9496 Sel |= LHS.getConstantOperandVal(2); 9497 SDLoc DL(N); 9498 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9499 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9500 } 9501 9502 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9503 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9504 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9505 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9506 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9507 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9508 if (LHSMask != ~0u && RHSMask != ~0u) { 9509 // Canonicalize the expression in an attempt to have fewer unique masks 9510 // and therefore fewer registers used to hold the masks. 9511 if (LHSMask > RHSMask) { 9512 std::swap(LHSMask, RHSMask); 9513 std::swap(LHS, RHS); 9514 } 9515 9516 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9517 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9518 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9519 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9520 9521 // Check of we need to combine values from two sources within a byte. 9522 if (!(LHSUsedLanes & RHSUsedLanes) && 9523 // If we select high and lower word keep it for SDWA. 9524 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9525 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9526 // Kill zero bytes selected by other mask. Zero value is 0xc. 9527 LHSMask &= ~RHSUsedLanes; 9528 RHSMask &= ~LHSUsedLanes; 9529 // Add 4 to each active LHS lane 9530 LHSMask |= LHSUsedLanes & 0x04040404; 9531 // Combine masks 9532 uint32_t Sel = LHSMask | RHSMask; 9533 SDLoc DL(N); 9534 9535 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9536 LHS.getOperand(0), RHS.getOperand(0), 9537 DAG.getConstant(Sel, DL, MVT::i32)); 9538 } 9539 } 9540 } 9541 9542 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9543 return SDValue(); 9544 9545 // TODO: This could be a generic combine with a predicate for extracting the 9546 // high half of an integer being free. 9547 9548 // (or i64:x, (zero_extend i32:y)) -> 9549 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9550 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9551 RHS.getOpcode() != ISD::ZERO_EXTEND) 9552 std::swap(LHS, RHS); 9553 9554 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9555 SDValue ExtSrc = RHS.getOperand(0); 9556 EVT SrcVT = ExtSrc.getValueType(); 9557 if (SrcVT == MVT::i32) { 9558 SDLoc SL(N); 9559 SDValue LowLHS, HiBits; 9560 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9561 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9562 9563 DCI.AddToWorklist(LowOr.getNode()); 9564 DCI.AddToWorklist(HiBits.getNode()); 9565 9566 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9567 LowOr, HiBits); 9568 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9569 } 9570 } 9571 9572 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9573 if (CRHS) { 9574 if (SDValue Split 9575 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, 9576 N->getOperand(0), CRHS)) 9577 return Split; 9578 } 9579 9580 return SDValue(); 9581 } 9582 9583 SDValue SITargetLowering::performXorCombine(SDNode *N, 9584 DAGCombinerInfo &DCI) const { 9585 EVT VT = N->getValueType(0); 9586 if (VT != MVT::i64) 9587 return SDValue(); 9588 9589 SDValue LHS = N->getOperand(0); 9590 SDValue RHS = N->getOperand(1); 9591 9592 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9593 if (CRHS) { 9594 if (SDValue Split 9595 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9596 return Split; 9597 } 9598 9599 return SDValue(); 9600 } 9601 9602 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9603 DAGCombinerInfo &DCI) const { 9604 if (!Subtarget->has16BitInsts() || 9605 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9606 return SDValue(); 9607 9608 EVT VT = N->getValueType(0); 9609 if (VT != MVT::i32) 9610 return SDValue(); 9611 9612 SDValue Src = N->getOperand(0); 9613 if (Src.getValueType() != MVT::i16) 9614 return SDValue(); 9615 9616 return SDValue(); 9617 } 9618 9619 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9620 DAGCombinerInfo &DCI) 9621 const { 9622 SDValue Src = N->getOperand(0); 9623 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9624 9625 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9626 VTSign->getVT() == MVT::i8) || 9627 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9628 VTSign->getVT() == MVT::i16)) && 9629 Src.hasOneUse()) { 9630 auto *M = cast<MemSDNode>(Src); 9631 SDValue Ops[] = { 9632 Src.getOperand(0), // Chain 9633 Src.getOperand(1), // rsrc 9634 Src.getOperand(2), // vindex 9635 Src.getOperand(3), // voffset 9636 Src.getOperand(4), // soffset 9637 Src.getOperand(5), // offset 9638 Src.getOperand(6), 9639 Src.getOperand(7) 9640 }; 9641 // replace with BUFFER_LOAD_BYTE/SHORT 9642 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9643 Src.getOperand(0).getValueType()); 9644 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9645 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9646 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9647 ResList, 9648 Ops, M->getMemoryVT(), 9649 M->getMemOperand()); 9650 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9651 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9652 } 9653 return SDValue(); 9654 } 9655 9656 SDValue SITargetLowering::performClassCombine(SDNode *N, 9657 DAGCombinerInfo &DCI) const { 9658 SelectionDAG &DAG = DCI.DAG; 9659 SDValue Mask = N->getOperand(1); 9660 9661 // fp_class x, 0 -> false 9662 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9663 if (CMask->isZero()) 9664 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9665 } 9666 9667 if (N->getOperand(0).isUndef()) 9668 return DAG.getUNDEF(MVT::i1); 9669 9670 return SDValue(); 9671 } 9672 9673 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9674 DAGCombinerInfo &DCI) const { 9675 EVT VT = N->getValueType(0); 9676 SDValue N0 = N->getOperand(0); 9677 9678 if (N0.isUndef()) 9679 return N0; 9680 9681 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9682 N0.getOpcode() == ISD::SINT_TO_FP)) { 9683 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9684 N->getFlags()); 9685 } 9686 9687 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9688 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9689 N0.getOperand(0), N->getFlags()); 9690 } 9691 9692 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9693 } 9694 9695 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9696 unsigned MaxDepth) const { 9697 unsigned Opcode = Op.getOpcode(); 9698 if (Opcode == ISD::FCANONICALIZE) 9699 return true; 9700 9701 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9702 auto F = CFP->getValueAPF(); 9703 if (F.isNaN() && F.isSignaling()) 9704 return false; 9705 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9706 } 9707 9708 // If source is a result of another standard FP operation it is already in 9709 // canonical form. 9710 if (MaxDepth == 0) 9711 return false; 9712 9713 switch (Opcode) { 9714 // These will flush denorms if required. 9715 case ISD::FADD: 9716 case ISD::FSUB: 9717 case ISD::FMUL: 9718 case ISD::FCEIL: 9719 case ISD::FFLOOR: 9720 case ISD::FMA: 9721 case ISD::FMAD: 9722 case ISD::FSQRT: 9723 case ISD::FDIV: 9724 case ISD::FREM: 9725 case ISD::FP_ROUND: 9726 case ISD::FP_EXTEND: 9727 case AMDGPUISD::FMUL_LEGACY: 9728 case AMDGPUISD::FMAD_FTZ: 9729 case AMDGPUISD::RCP: 9730 case AMDGPUISD::RSQ: 9731 case AMDGPUISD::RSQ_CLAMP: 9732 case AMDGPUISD::RCP_LEGACY: 9733 case AMDGPUISD::RCP_IFLAG: 9734 case AMDGPUISD::DIV_SCALE: 9735 case AMDGPUISD::DIV_FMAS: 9736 case AMDGPUISD::DIV_FIXUP: 9737 case AMDGPUISD::FRACT: 9738 case AMDGPUISD::LDEXP: 9739 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9740 case AMDGPUISD::CVT_F32_UBYTE0: 9741 case AMDGPUISD::CVT_F32_UBYTE1: 9742 case AMDGPUISD::CVT_F32_UBYTE2: 9743 case AMDGPUISD::CVT_F32_UBYTE3: 9744 return true; 9745 9746 // It can/will be lowered or combined as a bit operation. 9747 // Need to check their input recursively to handle. 9748 case ISD::FNEG: 9749 case ISD::FABS: 9750 case ISD::FCOPYSIGN: 9751 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9752 9753 case ISD::FSIN: 9754 case ISD::FCOS: 9755 case ISD::FSINCOS: 9756 return Op.getValueType().getScalarType() != MVT::f16; 9757 9758 case ISD::FMINNUM: 9759 case ISD::FMAXNUM: 9760 case ISD::FMINNUM_IEEE: 9761 case ISD::FMAXNUM_IEEE: 9762 case AMDGPUISD::CLAMP: 9763 case AMDGPUISD::FMED3: 9764 case AMDGPUISD::FMAX3: 9765 case AMDGPUISD::FMIN3: { 9766 // FIXME: Shouldn't treat the generic operations different based these. 9767 // However, we aren't really required to flush the result from 9768 // minnum/maxnum.. 9769 9770 // snans will be quieted, so we only need to worry about denormals. 9771 if (Subtarget->supportsMinMaxDenormModes() || 9772 denormalsEnabledForType(DAG, Op.getValueType())) 9773 return true; 9774 9775 // Flushing may be required. 9776 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9777 // targets need to check their input recursively. 9778 9779 // FIXME: Does this apply with clamp? It's implemented with max. 9780 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9781 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9782 return false; 9783 } 9784 9785 return true; 9786 } 9787 case ISD::SELECT: { 9788 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9789 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9790 } 9791 case ISD::BUILD_VECTOR: { 9792 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9793 SDValue SrcOp = Op.getOperand(i); 9794 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9795 return false; 9796 } 9797 9798 return true; 9799 } 9800 case ISD::EXTRACT_VECTOR_ELT: 9801 case ISD::EXTRACT_SUBVECTOR: { 9802 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9803 } 9804 case ISD::INSERT_VECTOR_ELT: { 9805 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9806 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9807 } 9808 case ISD::UNDEF: 9809 // Could be anything. 9810 return false; 9811 9812 case ISD::BITCAST: 9813 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9814 case ISD::TRUNCATE: { 9815 // Hack round the mess we make when legalizing extract_vector_elt 9816 if (Op.getValueType() == MVT::i16) { 9817 SDValue TruncSrc = Op.getOperand(0); 9818 if (TruncSrc.getValueType() == MVT::i32 && 9819 TruncSrc.getOpcode() == ISD::BITCAST && 9820 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9821 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9822 } 9823 } 9824 return false; 9825 } 9826 case ISD::INTRINSIC_WO_CHAIN: { 9827 unsigned IntrinsicID 9828 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9829 // TODO: Handle more intrinsics 9830 switch (IntrinsicID) { 9831 case Intrinsic::amdgcn_cvt_pkrtz: 9832 case Intrinsic::amdgcn_cubeid: 9833 case Intrinsic::amdgcn_frexp_mant: 9834 case Intrinsic::amdgcn_fdot2: 9835 case Intrinsic::amdgcn_rcp: 9836 case Intrinsic::amdgcn_rsq: 9837 case Intrinsic::amdgcn_rsq_clamp: 9838 case Intrinsic::amdgcn_rcp_legacy: 9839 case Intrinsic::amdgcn_rsq_legacy: 9840 case Intrinsic::amdgcn_trig_preop: 9841 return true; 9842 default: 9843 break; 9844 } 9845 9846 LLVM_FALLTHROUGH; 9847 } 9848 default: 9849 return denormalsEnabledForType(DAG, Op.getValueType()) && 9850 DAG.isKnownNeverSNaN(Op); 9851 } 9852 9853 llvm_unreachable("invalid operation"); 9854 } 9855 9856 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF, 9857 unsigned MaxDepth) const { 9858 MachineRegisterInfo &MRI = MF.getRegInfo(); 9859 MachineInstr *MI = MRI.getVRegDef(Reg); 9860 unsigned Opcode = MI->getOpcode(); 9861 9862 if (Opcode == AMDGPU::G_FCANONICALIZE) 9863 return true; 9864 9865 Optional<FPValueAndVReg> FCR; 9866 // Constant splat (can be padded with undef) or scalar constant. 9867 if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) { 9868 if (FCR->Value.isSignaling()) 9869 return false; 9870 return !FCR->Value.isDenormal() || 9871 denormalsEnabledForType(MRI.getType(FCR->VReg), MF); 9872 } 9873 9874 if (MaxDepth == 0) 9875 return false; 9876 9877 switch (Opcode) { 9878 case AMDGPU::G_FMINNUM_IEEE: 9879 case AMDGPU::G_FMAXNUM_IEEE: { 9880 if (Subtarget->supportsMinMaxDenormModes() || 9881 denormalsEnabledForType(MRI.getType(Reg), MF)) 9882 return true; 9883 for (const MachineOperand &MO : llvm::drop_begin(MI->operands())) 9884 if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1)) 9885 return false; 9886 return true; 9887 } 9888 default: 9889 return denormalsEnabledForType(MRI.getType(Reg), MF) && 9890 isKnownNeverSNaN(Reg, MRI); 9891 } 9892 9893 llvm_unreachable("invalid operation"); 9894 } 9895 9896 // Constant fold canonicalize. 9897 SDValue SITargetLowering::getCanonicalConstantFP( 9898 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9899 // Flush denormals to 0 if not enabled. 9900 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9901 return DAG.getConstantFP(0.0, SL, VT); 9902 9903 if (C.isNaN()) { 9904 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9905 if (C.isSignaling()) { 9906 // Quiet a signaling NaN. 9907 // FIXME: Is this supposed to preserve payload bits? 9908 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9909 } 9910 9911 // Make sure it is the canonical NaN bitpattern. 9912 // 9913 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9914 // immediate? 9915 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9916 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9917 } 9918 9919 // Already canonical. 9920 return DAG.getConstantFP(C, SL, VT); 9921 } 9922 9923 static bool vectorEltWillFoldAway(SDValue Op) { 9924 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9925 } 9926 9927 SDValue SITargetLowering::performFCanonicalizeCombine( 9928 SDNode *N, 9929 DAGCombinerInfo &DCI) const { 9930 SelectionDAG &DAG = DCI.DAG; 9931 SDValue N0 = N->getOperand(0); 9932 EVT VT = N->getValueType(0); 9933 9934 // fcanonicalize undef -> qnan 9935 if (N0.isUndef()) { 9936 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9937 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9938 } 9939 9940 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9941 EVT VT = N->getValueType(0); 9942 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9943 } 9944 9945 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9946 // (fcanonicalize k) 9947 // 9948 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9949 9950 // TODO: This could be better with wider vectors that will be split to v2f16, 9951 // and to consider uses since there aren't that many packed operations. 9952 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9953 isTypeLegal(MVT::v2f16)) { 9954 SDLoc SL(N); 9955 SDValue NewElts[2]; 9956 SDValue Lo = N0.getOperand(0); 9957 SDValue Hi = N0.getOperand(1); 9958 EVT EltVT = Lo.getValueType(); 9959 9960 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9961 for (unsigned I = 0; I != 2; ++I) { 9962 SDValue Op = N0.getOperand(I); 9963 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9964 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9965 CFP->getValueAPF()); 9966 } else if (Op.isUndef()) { 9967 // Handled below based on what the other operand is. 9968 NewElts[I] = Op; 9969 } else { 9970 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9971 } 9972 } 9973 9974 // If one half is undef, and one is constant, perfer a splat vector rather 9975 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9976 // cheaper to use and may be free with a packed operation. 9977 if (NewElts[0].isUndef()) { 9978 if (isa<ConstantFPSDNode>(NewElts[1])) 9979 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9980 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9981 } 9982 9983 if (NewElts[1].isUndef()) { 9984 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9985 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9986 } 9987 9988 return DAG.getBuildVector(VT, SL, NewElts); 9989 } 9990 } 9991 9992 unsigned SrcOpc = N0.getOpcode(); 9993 9994 // If it's free to do so, push canonicalizes further up the source, which may 9995 // find a canonical source. 9996 // 9997 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9998 // sNaNs. 9999 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 10000 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 10001 if (CRHS && N0.hasOneUse()) { 10002 SDLoc SL(N); 10003 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 10004 N0.getOperand(0)); 10005 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 10006 DCI.AddToWorklist(Canon0.getNode()); 10007 10008 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 10009 } 10010 } 10011 10012 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 10013 } 10014 10015 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 10016 switch (Opc) { 10017 case ISD::FMAXNUM: 10018 case ISD::FMAXNUM_IEEE: 10019 return AMDGPUISD::FMAX3; 10020 case ISD::SMAX: 10021 return AMDGPUISD::SMAX3; 10022 case ISD::UMAX: 10023 return AMDGPUISD::UMAX3; 10024 case ISD::FMINNUM: 10025 case ISD::FMINNUM_IEEE: 10026 return AMDGPUISD::FMIN3; 10027 case ISD::SMIN: 10028 return AMDGPUISD::SMIN3; 10029 case ISD::UMIN: 10030 return AMDGPUISD::UMIN3; 10031 default: 10032 llvm_unreachable("Not a min/max opcode"); 10033 } 10034 } 10035 10036 SDValue SITargetLowering::performIntMed3ImmCombine( 10037 SelectionDAG &DAG, const SDLoc &SL, 10038 SDValue Op0, SDValue Op1, bool Signed) const { 10039 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 10040 if (!K1) 10041 return SDValue(); 10042 10043 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 10044 if (!K0) 10045 return SDValue(); 10046 10047 if (Signed) { 10048 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 10049 return SDValue(); 10050 } else { 10051 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 10052 return SDValue(); 10053 } 10054 10055 EVT VT = K0->getValueType(0); 10056 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 10057 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 10058 return DAG.getNode(Med3Opc, SL, VT, 10059 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 10060 } 10061 10062 // If there isn't a 16-bit med3 operation, convert to 32-bit. 10063 if (VT == MVT::i16) { 10064 MVT NVT = MVT::i32; 10065 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 10066 10067 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 10068 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 10069 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 10070 10071 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 10072 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 10073 } 10074 10075 return SDValue(); 10076 } 10077 10078 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 10079 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 10080 return C; 10081 10082 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 10083 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 10084 return C; 10085 } 10086 10087 return nullptr; 10088 } 10089 10090 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 10091 const SDLoc &SL, 10092 SDValue Op0, 10093 SDValue Op1) const { 10094 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 10095 if (!K1) 10096 return SDValue(); 10097 10098 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 10099 if (!K0) 10100 return SDValue(); 10101 10102 // Ordered >= (although NaN inputs should have folded away by now). 10103 if (K0->getValueAPF() > K1->getValueAPF()) 10104 return SDValue(); 10105 10106 const MachineFunction &MF = DAG.getMachineFunction(); 10107 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10108 10109 // TODO: Check IEEE bit enabled? 10110 EVT VT = Op0.getValueType(); 10111 if (Info->getMode().DX10Clamp) { 10112 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 10113 // hardware fmed3 behavior converting to a min. 10114 // FIXME: Should this be allowing -0.0? 10115 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 10116 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 10117 } 10118 10119 // med3 for f16 is only available on gfx9+, and not available for v2f16. 10120 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 10121 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 10122 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 10123 // then give the other result, which is different from med3 with a NaN 10124 // input. 10125 SDValue Var = Op0.getOperand(0); 10126 if (!DAG.isKnownNeverSNaN(Var)) 10127 return SDValue(); 10128 10129 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10130 10131 if ((!K0->hasOneUse() || 10132 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 10133 (!K1->hasOneUse() || 10134 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 10135 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 10136 Var, SDValue(K0, 0), SDValue(K1, 0)); 10137 } 10138 } 10139 10140 return SDValue(); 10141 } 10142 10143 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 10144 DAGCombinerInfo &DCI) const { 10145 SelectionDAG &DAG = DCI.DAG; 10146 10147 EVT VT = N->getValueType(0); 10148 unsigned Opc = N->getOpcode(); 10149 SDValue Op0 = N->getOperand(0); 10150 SDValue Op1 = N->getOperand(1); 10151 10152 // Only do this if the inner op has one use since this will just increases 10153 // register pressure for no benefit. 10154 10155 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 10156 !VT.isVector() && 10157 (VT == MVT::i32 || VT == MVT::f32 || 10158 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 10159 // max(max(a, b), c) -> max3(a, b, c) 10160 // min(min(a, b), c) -> min3(a, b, c) 10161 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 10162 SDLoc DL(N); 10163 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10164 DL, 10165 N->getValueType(0), 10166 Op0.getOperand(0), 10167 Op0.getOperand(1), 10168 Op1); 10169 } 10170 10171 // Try commuted. 10172 // max(a, max(b, c)) -> max3(a, b, c) 10173 // min(a, min(b, c)) -> min3(a, b, c) 10174 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 10175 SDLoc DL(N); 10176 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10177 DL, 10178 N->getValueType(0), 10179 Op0, 10180 Op1.getOperand(0), 10181 Op1.getOperand(1)); 10182 } 10183 } 10184 10185 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 10186 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 10187 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 10188 return Med3; 10189 } 10190 10191 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 10192 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 10193 return Med3; 10194 } 10195 10196 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 10197 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 10198 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 10199 (Opc == AMDGPUISD::FMIN_LEGACY && 10200 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 10201 (VT == MVT::f32 || VT == MVT::f64 || 10202 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 10203 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 10204 Op0.hasOneUse()) { 10205 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 10206 return Res; 10207 } 10208 10209 return SDValue(); 10210 } 10211 10212 static bool isClampZeroToOne(SDValue A, SDValue B) { 10213 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 10214 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 10215 // FIXME: Should this be allowing -0.0? 10216 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 10217 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 10218 } 10219 } 10220 10221 return false; 10222 } 10223 10224 // FIXME: Should only worry about snans for version with chain. 10225 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 10226 DAGCombinerInfo &DCI) const { 10227 EVT VT = N->getValueType(0); 10228 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 10229 // NaNs. With a NaN input, the order of the operands may change the result. 10230 10231 SelectionDAG &DAG = DCI.DAG; 10232 SDLoc SL(N); 10233 10234 SDValue Src0 = N->getOperand(0); 10235 SDValue Src1 = N->getOperand(1); 10236 SDValue Src2 = N->getOperand(2); 10237 10238 if (isClampZeroToOne(Src0, Src1)) { 10239 // const_a, const_b, x -> clamp is safe in all cases including signaling 10240 // nans. 10241 // FIXME: Should this be allowing -0.0? 10242 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 10243 } 10244 10245 const MachineFunction &MF = DAG.getMachineFunction(); 10246 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10247 10248 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 10249 // handling no dx10-clamp? 10250 if (Info->getMode().DX10Clamp) { 10251 // If NaNs is clamped to 0, we are free to reorder the inputs. 10252 10253 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10254 std::swap(Src0, Src1); 10255 10256 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 10257 std::swap(Src1, Src2); 10258 10259 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10260 std::swap(Src0, Src1); 10261 10262 if (isClampZeroToOne(Src1, Src2)) 10263 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 10264 } 10265 10266 return SDValue(); 10267 } 10268 10269 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 10270 DAGCombinerInfo &DCI) const { 10271 SDValue Src0 = N->getOperand(0); 10272 SDValue Src1 = N->getOperand(1); 10273 if (Src0.isUndef() && Src1.isUndef()) 10274 return DCI.DAG.getUNDEF(N->getValueType(0)); 10275 return SDValue(); 10276 } 10277 10278 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 10279 // expanded into a set of cmp/select instructions. 10280 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 10281 unsigned NumElem, 10282 bool IsDivergentIdx) { 10283 if (UseDivergentRegisterIndexing) 10284 return false; 10285 10286 unsigned VecSize = EltSize * NumElem; 10287 10288 // Sub-dword vectors of size 2 dword or less have better implementation. 10289 if (VecSize <= 64 && EltSize < 32) 10290 return false; 10291 10292 // Always expand the rest of sub-dword instructions, otherwise it will be 10293 // lowered via memory. 10294 if (EltSize < 32) 10295 return true; 10296 10297 // Always do this if var-idx is divergent, otherwise it will become a loop. 10298 if (IsDivergentIdx) 10299 return true; 10300 10301 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 10302 unsigned NumInsts = NumElem /* Number of compares */ + 10303 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 10304 return NumInsts <= 16; 10305 } 10306 10307 static bool shouldExpandVectorDynExt(SDNode *N) { 10308 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 10309 if (isa<ConstantSDNode>(Idx)) 10310 return false; 10311 10312 SDValue Vec = N->getOperand(0); 10313 EVT VecVT = Vec.getValueType(); 10314 EVT EltVT = VecVT.getVectorElementType(); 10315 unsigned EltSize = EltVT.getSizeInBits(); 10316 unsigned NumElem = VecVT.getVectorNumElements(); 10317 10318 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 10319 Idx->isDivergent()); 10320 } 10321 10322 SDValue SITargetLowering::performExtractVectorEltCombine( 10323 SDNode *N, DAGCombinerInfo &DCI) const { 10324 SDValue Vec = N->getOperand(0); 10325 SelectionDAG &DAG = DCI.DAG; 10326 10327 EVT VecVT = Vec.getValueType(); 10328 EVT EltVT = VecVT.getVectorElementType(); 10329 10330 if ((Vec.getOpcode() == ISD::FNEG || 10331 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 10332 SDLoc SL(N); 10333 EVT EltVT = N->getValueType(0); 10334 SDValue Idx = N->getOperand(1); 10335 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10336 Vec.getOperand(0), Idx); 10337 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 10338 } 10339 10340 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 10341 // => 10342 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 10343 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 10344 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 10345 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 10346 SDLoc SL(N); 10347 EVT EltVT = N->getValueType(0); 10348 SDValue Idx = N->getOperand(1); 10349 unsigned Opc = Vec.getOpcode(); 10350 10351 switch(Opc) { 10352 default: 10353 break; 10354 // TODO: Support other binary operations. 10355 case ISD::FADD: 10356 case ISD::FSUB: 10357 case ISD::FMUL: 10358 case ISD::ADD: 10359 case ISD::UMIN: 10360 case ISD::UMAX: 10361 case ISD::SMIN: 10362 case ISD::SMAX: 10363 case ISD::FMAXNUM: 10364 case ISD::FMINNUM: 10365 case ISD::FMAXNUM_IEEE: 10366 case ISD::FMINNUM_IEEE: { 10367 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10368 Vec.getOperand(0), Idx); 10369 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10370 Vec.getOperand(1), Idx); 10371 10372 DCI.AddToWorklist(Elt0.getNode()); 10373 DCI.AddToWorklist(Elt1.getNode()); 10374 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 10375 } 10376 } 10377 } 10378 10379 unsigned VecSize = VecVT.getSizeInBits(); 10380 unsigned EltSize = EltVT.getSizeInBits(); 10381 10382 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 10383 if (::shouldExpandVectorDynExt(N)) { 10384 SDLoc SL(N); 10385 SDValue Idx = N->getOperand(1); 10386 SDValue V; 10387 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10388 SDValue IC = DAG.getVectorIdxConstant(I, SL); 10389 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10390 if (I == 0) 10391 V = Elt; 10392 else 10393 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 10394 } 10395 return V; 10396 } 10397 10398 if (!DCI.isBeforeLegalize()) 10399 return SDValue(); 10400 10401 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 10402 // elements. This exposes more load reduction opportunities by replacing 10403 // multiple small extract_vector_elements with a single 32-bit extract. 10404 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10405 if (isa<MemSDNode>(Vec) && 10406 EltSize <= 16 && 10407 EltVT.isByteSized() && 10408 VecSize > 32 && 10409 VecSize % 32 == 0 && 10410 Idx) { 10411 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 10412 10413 unsigned BitIndex = Idx->getZExtValue() * EltSize; 10414 unsigned EltIdx = BitIndex / 32; 10415 unsigned LeftoverBitIdx = BitIndex % 32; 10416 SDLoc SL(N); 10417 10418 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 10419 DCI.AddToWorklist(Cast.getNode()); 10420 10421 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 10422 DAG.getConstant(EltIdx, SL, MVT::i32)); 10423 DCI.AddToWorklist(Elt.getNode()); 10424 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 10425 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 10426 DCI.AddToWorklist(Srl.getNode()); 10427 10428 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 10429 DCI.AddToWorklist(Trunc.getNode()); 10430 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 10431 } 10432 10433 return SDValue(); 10434 } 10435 10436 SDValue 10437 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 10438 DAGCombinerInfo &DCI) const { 10439 SDValue Vec = N->getOperand(0); 10440 SDValue Idx = N->getOperand(2); 10441 EVT VecVT = Vec.getValueType(); 10442 EVT EltVT = VecVT.getVectorElementType(); 10443 10444 // INSERT_VECTOR_ELT (<n x e>, var-idx) 10445 // => BUILD_VECTOR n x select (e, const-idx) 10446 if (!::shouldExpandVectorDynExt(N)) 10447 return SDValue(); 10448 10449 SelectionDAG &DAG = DCI.DAG; 10450 SDLoc SL(N); 10451 SDValue Ins = N->getOperand(1); 10452 EVT IdxVT = Idx.getValueType(); 10453 10454 SmallVector<SDValue, 16> Ops; 10455 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10456 SDValue IC = DAG.getConstant(I, SL, IdxVT); 10457 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10458 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 10459 Ops.push_back(V); 10460 } 10461 10462 return DAG.getBuildVector(VecVT, SL, Ops); 10463 } 10464 10465 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 10466 const SDNode *N0, 10467 const SDNode *N1) const { 10468 EVT VT = N0->getValueType(0); 10469 10470 // Only do this if we are not trying to support denormals. v_mad_f32 does not 10471 // support denormals ever. 10472 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 10473 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 10474 getSubtarget()->hasMadF16())) && 10475 isOperationLegal(ISD::FMAD, VT)) 10476 return ISD::FMAD; 10477 10478 const TargetOptions &Options = DAG.getTarget().Options; 10479 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10480 (N0->getFlags().hasAllowContract() && 10481 N1->getFlags().hasAllowContract())) && 10482 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10483 return ISD::FMA; 10484 } 10485 10486 return 0; 10487 } 10488 10489 // For a reassociatable opcode perform: 10490 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10491 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10492 SelectionDAG &DAG) const { 10493 EVT VT = N->getValueType(0); 10494 if (VT != MVT::i32 && VT != MVT::i64) 10495 return SDValue(); 10496 10497 unsigned Opc = N->getOpcode(); 10498 SDValue Op0 = N->getOperand(0); 10499 SDValue Op1 = N->getOperand(1); 10500 10501 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10502 return SDValue(); 10503 10504 if (Op0->isDivergent()) 10505 std::swap(Op0, Op1); 10506 10507 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10508 return SDValue(); 10509 10510 SDValue Op2 = Op1.getOperand(1); 10511 Op1 = Op1.getOperand(0); 10512 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10513 return SDValue(); 10514 10515 if (Op1->isDivergent()) 10516 std::swap(Op1, Op2); 10517 10518 // If either operand is constant this will conflict with 10519 // DAGCombiner::ReassociateOps(). 10520 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 10521 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 10522 return SDValue(); 10523 10524 SDLoc SL(N); 10525 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10526 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10527 } 10528 10529 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10530 EVT VT, 10531 SDValue N0, SDValue N1, SDValue N2, 10532 bool Signed) { 10533 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10534 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10535 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10536 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10537 } 10538 10539 SDValue SITargetLowering::performAddCombine(SDNode *N, 10540 DAGCombinerInfo &DCI) const { 10541 SelectionDAG &DAG = DCI.DAG; 10542 EVT VT = N->getValueType(0); 10543 SDLoc SL(N); 10544 SDValue LHS = N->getOperand(0); 10545 SDValue RHS = N->getOperand(1); 10546 10547 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10548 && Subtarget->hasMad64_32() && 10549 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10550 VT.getScalarSizeInBits() <= 64) { 10551 if (LHS.getOpcode() != ISD::MUL) 10552 std::swap(LHS, RHS); 10553 10554 SDValue MulLHS = LHS.getOperand(0); 10555 SDValue MulRHS = LHS.getOperand(1); 10556 SDValue AddRHS = RHS; 10557 10558 // TODO: Maybe restrict if SGPR inputs. 10559 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10560 numBitsUnsigned(MulRHS, DAG) <= 32) { 10561 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10562 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10563 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10564 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10565 } 10566 10567 if (numBitsSigned(MulLHS, DAG) <= 32 && numBitsSigned(MulRHS, DAG) <= 32) { 10568 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10569 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10570 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10571 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10572 } 10573 10574 return SDValue(); 10575 } 10576 10577 if (SDValue V = reassociateScalarOps(N, DAG)) { 10578 return V; 10579 } 10580 10581 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10582 return SDValue(); 10583 10584 // add x, zext (setcc) => addcarry x, 0, setcc 10585 // add x, sext (setcc) => subcarry x, 0, setcc 10586 unsigned Opc = LHS.getOpcode(); 10587 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10588 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10589 std::swap(RHS, LHS); 10590 10591 Opc = RHS.getOpcode(); 10592 switch (Opc) { 10593 default: break; 10594 case ISD::ZERO_EXTEND: 10595 case ISD::SIGN_EXTEND: 10596 case ISD::ANY_EXTEND: { 10597 auto Cond = RHS.getOperand(0); 10598 // If this won't be a real VOPC output, we would still need to insert an 10599 // extra instruction anyway. 10600 if (!isBoolSGPR(Cond)) 10601 break; 10602 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10603 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10604 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10605 return DAG.getNode(Opc, SL, VTList, Args); 10606 } 10607 case ISD::ADDCARRY: { 10608 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10609 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10610 if (!C || C->getZExtValue() != 0) break; 10611 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10612 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10613 } 10614 } 10615 return SDValue(); 10616 } 10617 10618 SDValue SITargetLowering::performSubCombine(SDNode *N, 10619 DAGCombinerInfo &DCI) const { 10620 SelectionDAG &DAG = DCI.DAG; 10621 EVT VT = N->getValueType(0); 10622 10623 if (VT != MVT::i32) 10624 return SDValue(); 10625 10626 SDLoc SL(N); 10627 SDValue LHS = N->getOperand(0); 10628 SDValue RHS = N->getOperand(1); 10629 10630 // sub x, zext (setcc) => subcarry x, 0, setcc 10631 // sub x, sext (setcc) => addcarry x, 0, setcc 10632 unsigned Opc = RHS.getOpcode(); 10633 switch (Opc) { 10634 default: break; 10635 case ISD::ZERO_EXTEND: 10636 case ISD::SIGN_EXTEND: 10637 case ISD::ANY_EXTEND: { 10638 auto Cond = RHS.getOperand(0); 10639 // If this won't be a real VOPC output, we would still need to insert an 10640 // extra instruction anyway. 10641 if (!isBoolSGPR(Cond)) 10642 break; 10643 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10644 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10645 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10646 return DAG.getNode(Opc, SL, VTList, Args); 10647 } 10648 } 10649 10650 if (LHS.getOpcode() == ISD::SUBCARRY) { 10651 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10652 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10653 if (!C || !C->isZero()) 10654 return SDValue(); 10655 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10656 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10657 } 10658 return SDValue(); 10659 } 10660 10661 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10662 DAGCombinerInfo &DCI) const { 10663 10664 if (N->getValueType(0) != MVT::i32) 10665 return SDValue(); 10666 10667 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10668 if (!C || C->getZExtValue() != 0) 10669 return SDValue(); 10670 10671 SelectionDAG &DAG = DCI.DAG; 10672 SDValue LHS = N->getOperand(0); 10673 10674 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10675 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10676 unsigned LHSOpc = LHS.getOpcode(); 10677 unsigned Opc = N->getOpcode(); 10678 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10679 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10680 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10681 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10682 } 10683 return SDValue(); 10684 } 10685 10686 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10687 DAGCombinerInfo &DCI) const { 10688 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10689 return SDValue(); 10690 10691 SelectionDAG &DAG = DCI.DAG; 10692 EVT VT = N->getValueType(0); 10693 10694 SDLoc SL(N); 10695 SDValue LHS = N->getOperand(0); 10696 SDValue RHS = N->getOperand(1); 10697 10698 // These should really be instruction patterns, but writing patterns with 10699 // source modiifiers is a pain. 10700 10701 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10702 if (LHS.getOpcode() == ISD::FADD) { 10703 SDValue A = LHS.getOperand(0); 10704 if (A == LHS.getOperand(1)) { 10705 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10706 if (FusedOp != 0) { 10707 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10708 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10709 } 10710 } 10711 } 10712 10713 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10714 if (RHS.getOpcode() == ISD::FADD) { 10715 SDValue A = RHS.getOperand(0); 10716 if (A == RHS.getOperand(1)) { 10717 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10718 if (FusedOp != 0) { 10719 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10720 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10721 } 10722 } 10723 } 10724 10725 return SDValue(); 10726 } 10727 10728 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10729 DAGCombinerInfo &DCI) const { 10730 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10731 return SDValue(); 10732 10733 SelectionDAG &DAG = DCI.DAG; 10734 SDLoc SL(N); 10735 EVT VT = N->getValueType(0); 10736 assert(!VT.isVector()); 10737 10738 // Try to get the fneg to fold into the source modifier. This undoes generic 10739 // DAG combines and folds them into the mad. 10740 // 10741 // Only do this if we are not trying to support denormals. v_mad_f32 does 10742 // not support denormals ever. 10743 SDValue LHS = N->getOperand(0); 10744 SDValue RHS = N->getOperand(1); 10745 if (LHS.getOpcode() == ISD::FADD) { 10746 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10747 SDValue A = LHS.getOperand(0); 10748 if (A == LHS.getOperand(1)) { 10749 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10750 if (FusedOp != 0){ 10751 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10752 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10753 10754 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10755 } 10756 } 10757 } 10758 10759 if (RHS.getOpcode() == ISD::FADD) { 10760 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10761 10762 SDValue A = RHS.getOperand(0); 10763 if (A == RHS.getOperand(1)) { 10764 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10765 if (FusedOp != 0){ 10766 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10767 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10768 } 10769 } 10770 } 10771 10772 return SDValue(); 10773 } 10774 10775 SDValue SITargetLowering::performFMACombine(SDNode *N, 10776 DAGCombinerInfo &DCI) const { 10777 SelectionDAG &DAG = DCI.DAG; 10778 EVT VT = N->getValueType(0); 10779 SDLoc SL(N); 10780 10781 if (!Subtarget->hasDot7Insts() || VT != MVT::f32) 10782 return SDValue(); 10783 10784 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10785 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10786 SDValue Op1 = N->getOperand(0); 10787 SDValue Op2 = N->getOperand(1); 10788 SDValue FMA = N->getOperand(2); 10789 10790 if (FMA.getOpcode() != ISD::FMA || 10791 Op1.getOpcode() != ISD::FP_EXTEND || 10792 Op2.getOpcode() != ISD::FP_EXTEND) 10793 return SDValue(); 10794 10795 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10796 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10797 // is sufficient to allow generaing fdot2. 10798 const TargetOptions &Options = DAG.getTarget().Options; 10799 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10800 (N->getFlags().hasAllowContract() && 10801 FMA->getFlags().hasAllowContract())) { 10802 Op1 = Op1.getOperand(0); 10803 Op2 = Op2.getOperand(0); 10804 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10805 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10806 return SDValue(); 10807 10808 SDValue Vec1 = Op1.getOperand(0); 10809 SDValue Idx1 = Op1.getOperand(1); 10810 SDValue Vec2 = Op2.getOperand(0); 10811 10812 SDValue FMAOp1 = FMA.getOperand(0); 10813 SDValue FMAOp2 = FMA.getOperand(1); 10814 SDValue FMAAcc = FMA.getOperand(2); 10815 10816 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10817 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10818 return SDValue(); 10819 10820 FMAOp1 = FMAOp1.getOperand(0); 10821 FMAOp2 = FMAOp2.getOperand(0); 10822 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10823 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10824 return SDValue(); 10825 10826 SDValue Vec3 = FMAOp1.getOperand(0); 10827 SDValue Vec4 = FMAOp2.getOperand(0); 10828 SDValue Idx2 = FMAOp1.getOperand(1); 10829 10830 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10831 // Idx1 and Idx2 cannot be the same. 10832 Idx1 == Idx2) 10833 return SDValue(); 10834 10835 if (Vec1 == Vec2 || Vec3 == Vec4) 10836 return SDValue(); 10837 10838 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10839 return SDValue(); 10840 10841 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10842 (Vec1 == Vec4 && Vec2 == Vec3)) { 10843 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10844 DAG.getTargetConstant(0, SL, MVT::i1)); 10845 } 10846 } 10847 return SDValue(); 10848 } 10849 10850 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10851 DAGCombinerInfo &DCI) const { 10852 SelectionDAG &DAG = DCI.DAG; 10853 SDLoc SL(N); 10854 10855 SDValue LHS = N->getOperand(0); 10856 SDValue RHS = N->getOperand(1); 10857 EVT VT = LHS.getValueType(); 10858 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10859 10860 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10861 if (!CRHS) { 10862 CRHS = dyn_cast<ConstantSDNode>(LHS); 10863 if (CRHS) { 10864 std::swap(LHS, RHS); 10865 CC = getSetCCSwappedOperands(CC); 10866 } 10867 } 10868 10869 if (CRHS) { 10870 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10871 isBoolSGPR(LHS.getOperand(0))) { 10872 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10873 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10874 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10875 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10876 if ((CRHS->isAllOnes() && 10877 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10878 (CRHS->isZero() && 10879 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10880 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10881 DAG.getConstant(-1, SL, MVT::i1)); 10882 if ((CRHS->isAllOnes() && 10883 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10884 (CRHS->isZero() && 10885 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10886 return LHS.getOperand(0); 10887 } 10888 10889 const APInt &CRHSVal = CRHS->getAPIntValue(); 10890 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10891 LHS.getOpcode() == ISD::SELECT && 10892 isa<ConstantSDNode>(LHS.getOperand(1)) && 10893 isa<ConstantSDNode>(LHS.getOperand(2)) && 10894 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10895 isBoolSGPR(LHS.getOperand(0))) { 10896 // Given CT != FT: 10897 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10898 // setcc (select cc, CT, CF), CF, ne => cc 10899 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10900 // setcc (select cc, CT, CF), CT, eq => cc 10901 const APInt &CT = LHS.getConstantOperandAPInt(1); 10902 const APInt &CF = LHS.getConstantOperandAPInt(2); 10903 10904 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10905 (CT == CRHSVal && CC == ISD::SETNE)) 10906 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10907 DAG.getConstant(-1, SL, MVT::i1)); 10908 if ((CF == CRHSVal && CC == ISD::SETNE) || 10909 (CT == CRHSVal && CC == ISD::SETEQ)) 10910 return LHS.getOperand(0); 10911 } 10912 } 10913 10914 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10915 VT != MVT::f16)) 10916 return SDValue(); 10917 10918 // Match isinf/isfinite pattern 10919 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10920 // (fcmp one (fabs x), inf) -> (fp_class x, 10921 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10922 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10923 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10924 if (!CRHS) 10925 return SDValue(); 10926 10927 const APFloat &APF = CRHS->getValueAPF(); 10928 if (APF.isInfinity() && !APF.isNegative()) { 10929 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10930 SIInstrFlags::N_INFINITY; 10931 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10932 SIInstrFlags::P_ZERO | 10933 SIInstrFlags::N_NORMAL | 10934 SIInstrFlags::P_NORMAL | 10935 SIInstrFlags::N_SUBNORMAL | 10936 SIInstrFlags::P_SUBNORMAL; 10937 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10938 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10939 DAG.getConstant(Mask, SL, MVT::i32)); 10940 } 10941 } 10942 10943 return SDValue(); 10944 } 10945 10946 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10947 DAGCombinerInfo &DCI) const { 10948 SelectionDAG &DAG = DCI.DAG; 10949 SDLoc SL(N); 10950 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10951 10952 SDValue Src = N->getOperand(0); 10953 SDValue Shift = N->getOperand(0); 10954 10955 // TODO: Extend type shouldn't matter (assuming legal types). 10956 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10957 Shift = Shift.getOperand(0); 10958 10959 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10960 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10961 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10962 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10963 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10964 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10965 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10966 SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0), 10967 SDLoc(Shift.getOperand(0)), MVT::i32); 10968 10969 unsigned ShiftOffset = 8 * Offset; 10970 if (Shift.getOpcode() == ISD::SHL) 10971 ShiftOffset -= C->getZExtValue(); 10972 else 10973 ShiftOffset += C->getZExtValue(); 10974 10975 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10976 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10977 MVT::f32, Shifted); 10978 } 10979 } 10980 } 10981 10982 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10983 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10984 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10985 // We simplified Src. If this node is not dead, visit it again so it is 10986 // folded properly. 10987 if (N->getOpcode() != ISD::DELETED_NODE) 10988 DCI.AddToWorklist(N); 10989 return SDValue(N, 0); 10990 } 10991 10992 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10993 if (SDValue DemandedSrc = 10994 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10995 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10996 10997 return SDValue(); 10998 } 10999 11000 SDValue SITargetLowering::performClampCombine(SDNode *N, 11001 DAGCombinerInfo &DCI) const { 11002 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 11003 if (!CSrc) 11004 return SDValue(); 11005 11006 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 11007 const APFloat &F = CSrc->getValueAPF(); 11008 APFloat Zero = APFloat::getZero(F.getSemantics()); 11009 if (F < Zero || 11010 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 11011 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 11012 } 11013 11014 APFloat One(F.getSemantics(), "1.0"); 11015 if (F > One) 11016 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 11017 11018 return SDValue(CSrc, 0); 11019 } 11020 11021 11022 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 11023 DAGCombinerInfo &DCI) const { 11024 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 11025 return SDValue(); 11026 switch (N->getOpcode()) { 11027 case ISD::ADD: 11028 return performAddCombine(N, DCI); 11029 case ISD::SUB: 11030 return performSubCombine(N, DCI); 11031 case ISD::ADDCARRY: 11032 case ISD::SUBCARRY: 11033 return performAddCarrySubCarryCombine(N, DCI); 11034 case ISD::FADD: 11035 return performFAddCombine(N, DCI); 11036 case ISD::FSUB: 11037 return performFSubCombine(N, DCI); 11038 case ISD::SETCC: 11039 return performSetCCCombine(N, DCI); 11040 case ISD::FMAXNUM: 11041 case ISD::FMINNUM: 11042 case ISD::FMAXNUM_IEEE: 11043 case ISD::FMINNUM_IEEE: 11044 case ISD::SMAX: 11045 case ISD::SMIN: 11046 case ISD::UMAX: 11047 case ISD::UMIN: 11048 case AMDGPUISD::FMIN_LEGACY: 11049 case AMDGPUISD::FMAX_LEGACY: 11050 return performMinMaxCombine(N, DCI); 11051 case ISD::FMA: 11052 return performFMACombine(N, DCI); 11053 case ISD::AND: 11054 return performAndCombine(N, DCI); 11055 case ISD::OR: 11056 return performOrCombine(N, DCI); 11057 case ISD::XOR: 11058 return performXorCombine(N, DCI); 11059 case ISD::ZERO_EXTEND: 11060 return performZeroExtendCombine(N, DCI); 11061 case ISD::SIGN_EXTEND_INREG: 11062 return performSignExtendInRegCombine(N , DCI); 11063 case AMDGPUISD::FP_CLASS: 11064 return performClassCombine(N, DCI); 11065 case ISD::FCANONICALIZE: 11066 return performFCanonicalizeCombine(N, DCI); 11067 case AMDGPUISD::RCP: 11068 return performRcpCombine(N, DCI); 11069 case AMDGPUISD::FRACT: 11070 case AMDGPUISD::RSQ: 11071 case AMDGPUISD::RCP_LEGACY: 11072 case AMDGPUISD::RCP_IFLAG: 11073 case AMDGPUISD::RSQ_CLAMP: 11074 case AMDGPUISD::LDEXP: { 11075 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 11076 SDValue Src = N->getOperand(0); 11077 if (Src.isUndef()) 11078 return Src; 11079 break; 11080 } 11081 case ISD::SINT_TO_FP: 11082 case ISD::UINT_TO_FP: 11083 return performUCharToFloatCombine(N, DCI); 11084 case AMDGPUISD::CVT_F32_UBYTE0: 11085 case AMDGPUISD::CVT_F32_UBYTE1: 11086 case AMDGPUISD::CVT_F32_UBYTE2: 11087 case AMDGPUISD::CVT_F32_UBYTE3: 11088 return performCvtF32UByteNCombine(N, DCI); 11089 case AMDGPUISD::FMED3: 11090 return performFMed3Combine(N, DCI); 11091 case AMDGPUISD::CVT_PKRTZ_F16_F32: 11092 return performCvtPkRTZCombine(N, DCI); 11093 case AMDGPUISD::CLAMP: 11094 return performClampCombine(N, DCI); 11095 case ISD::SCALAR_TO_VECTOR: { 11096 SelectionDAG &DAG = DCI.DAG; 11097 EVT VT = N->getValueType(0); 11098 11099 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 11100 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 11101 SDLoc SL(N); 11102 SDValue Src = N->getOperand(0); 11103 EVT EltVT = Src.getValueType(); 11104 if (EltVT == MVT::f16) 11105 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 11106 11107 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 11108 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 11109 } 11110 11111 break; 11112 } 11113 case ISD::EXTRACT_VECTOR_ELT: 11114 return performExtractVectorEltCombine(N, DCI); 11115 case ISD::INSERT_VECTOR_ELT: 11116 return performInsertVectorEltCombine(N, DCI); 11117 case ISD::LOAD: { 11118 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 11119 return Widended; 11120 LLVM_FALLTHROUGH; 11121 } 11122 default: { 11123 if (!DCI.isBeforeLegalize()) { 11124 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 11125 return performMemSDNodeCombine(MemNode, DCI); 11126 } 11127 11128 break; 11129 } 11130 } 11131 11132 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 11133 } 11134 11135 /// Helper function for adjustWritemask 11136 static unsigned SubIdx2Lane(unsigned Idx) { 11137 switch (Idx) { 11138 default: return ~0u; 11139 case AMDGPU::sub0: return 0; 11140 case AMDGPU::sub1: return 1; 11141 case AMDGPU::sub2: return 2; 11142 case AMDGPU::sub3: return 3; 11143 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 11144 } 11145 } 11146 11147 /// Adjust the writemask of MIMG instructions 11148 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 11149 SelectionDAG &DAG) const { 11150 unsigned Opcode = Node->getMachineOpcode(); 11151 11152 // Subtract 1 because the vdata output is not a MachineSDNode operand. 11153 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 11154 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 11155 return Node; // not implemented for D16 11156 11157 SDNode *Users[5] = { nullptr }; 11158 unsigned Lane = 0; 11159 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 11160 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 11161 unsigned NewDmask = 0; 11162 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 11163 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 11164 bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) || 11165 Node->getConstantOperandVal(LWEIdx)) 11166 ? true 11167 : false; 11168 unsigned TFCLane = 0; 11169 bool HasChain = Node->getNumValues() > 1; 11170 11171 if (OldDmask == 0) { 11172 // These are folded out, but on the chance it happens don't assert. 11173 return Node; 11174 } 11175 11176 unsigned OldBitsSet = countPopulation(OldDmask); 11177 // Work out which is the TFE/LWE lane if that is enabled. 11178 if (UsesTFC) { 11179 TFCLane = OldBitsSet; 11180 } 11181 11182 // Try to figure out the used register components 11183 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 11184 I != E; ++I) { 11185 11186 // Don't look at users of the chain. 11187 if (I.getUse().getResNo() != 0) 11188 continue; 11189 11190 // Abort if we can't understand the usage 11191 if (!I->isMachineOpcode() || 11192 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 11193 return Node; 11194 11195 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 11196 // Note that subregs are packed, i.e. Lane==0 is the first bit set 11197 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 11198 // set, etc. 11199 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 11200 if (Lane == ~0u) 11201 return Node; 11202 11203 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 11204 if (UsesTFC && Lane == TFCLane) { 11205 Users[Lane] = *I; 11206 } else { 11207 // Set which texture component corresponds to the lane. 11208 unsigned Comp; 11209 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 11210 Comp = countTrailingZeros(Dmask); 11211 Dmask &= ~(1 << Comp); 11212 } 11213 11214 // Abort if we have more than one user per component. 11215 if (Users[Lane]) 11216 return Node; 11217 11218 Users[Lane] = *I; 11219 NewDmask |= 1 << Comp; 11220 } 11221 } 11222 11223 // Don't allow 0 dmask, as hardware assumes one channel enabled. 11224 bool NoChannels = !NewDmask; 11225 if (NoChannels) { 11226 if (!UsesTFC) { 11227 // No uses of the result and not using TFC. Then do nothing. 11228 return Node; 11229 } 11230 // If the original dmask has one channel - then nothing to do 11231 if (OldBitsSet == 1) 11232 return Node; 11233 // Use an arbitrary dmask - required for the instruction to work 11234 NewDmask = 1; 11235 } 11236 // Abort if there's no change 11237 if (NewDmask == OldDmask) 11238 return Node; 11239 11240 unsigned BitsSet = countPopulation(NewDmask); 11241 11242 // Check for TFE or LWE - increase the number of channels by one to account 11243 // for the extra return value 11244 // This will need adjustment for D16 if this is also included in 11245 // adjustWriteMask (this function) but at present D16 are excluded. 11246 unsigned NewChannels = BitsSet + UsesTFC; 11247 11248 int NewOpcode = 11249 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 11250 assert(NewOpcode != -1 && 11251 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 11252 "failed to find equivalent MIMG op"); 11253 11254 // Adjust the writemask in the node 11255 SmallVector<SDValue, 12> Ops; 11256 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 11257 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 11258 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 11259 11260 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 11261 11262 MVT ResultVT = NewChannels == 1 ? 11263 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 11264 NewChannels == 5 ? 8 : NewChannels); 11265 SDVTList NewVTList = HasChain ? 11266 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 11267 11268 11269 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 11270 NewVTList, Ops); 11271 11272 if (HasChain) { 11273 // Update chain. 11274 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 11275 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 11276 } 11277 11278 if (NewChannels == 1) { 11279 assert(Node->hasNUsesOfValue(1, 0)); 11280 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 11281 SDLoc(Node), Users[Lane]->getValueType(0), 11282 SDValue(NewNode, 0)); 11283 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 11284 return nullptr; 11285 } 11286 11287 // Update the users of the node with the new indices 11288 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 11289 SDNode *User = Users[i]; 11290 if (!User) { 11291 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 11292 // Users[0] is still nullptr because channel 0 doesn't really have a use. 11293 if (i || !NoChannels) 11294 continue; 11295 } else { 11296 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 11297 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 11298 } 11299 11300 switch (Idx) { 11301 default: break; 11302 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 11303 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 11304 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 11305 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 11306 } 11307 } 11308 11309 DAG.RemoveDeadNode(Node); 11310 return nullptr; 11311 } 11312 11313 static bool isFrameIndexOp(SDValue Op) { 11314 if (Op.getOpcode() == ISD::AssertZext) 11315 Op = Op.getOperand(0); 11316 11317 return isa<FrameIndexSDNode>(Op); 11318 } 11319 11320 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 11321 /// with frame index operands. 11322 /// LLVM assumes that inputs are to these instructions are registers. 11323 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 11324 SelectionDAG &DAG) const { 11325 if (Node->getOpcode() == ISD::CopyToReg) { 11326 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 11327 SDValue SrcVal = Node->getOperand(2); 11328 11329 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 11330 // to try understanding copies to physical registers. 11331 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 11332 SDLoc SL(Node); 11333 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11334 SDValue VReg = DAG.getRegister( 11335 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 11336 11337 SDNode *Glued = Node->getGluedNode(); 11338 SDValue ToVReg 11339 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 11340 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 11341 SDValue ToResultReg 11342 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 11343 VReg, ToVReg.getValue(1)); 11344 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 11345 DAG.RemoveDeadNode(Node); 11346 return ToResultReg.getNode(); 11347 } 11348 } 11349 11350 SmallVector<SDValue, 8> Ops; 11351 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 11352 if (!isFrameIndexOp(Node->getOperand(i))) { 11353 Ops.push_back(Node->getOperand(i)); 11354 continue; 11355 } 11356 11357 SDLoc DL(Node); 11358 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 11359 Node->getOperand(i).getValueType(), 11360 Node->getOperand(i)), 0)); 11361 } 11362 11363 return DAG.UpdateNodeOperands(Node, Ops); 11364 } 11365 11366 /// Fold the instructions after selecting them. 11367 /// Returns null if users were already updated. 11368 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 11369 SelectionDAG &DAG) const { 11370 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11371 unsigned Opcode = Node->getMachineOpcode(); 11372 11373 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 11374 !TII->isGather4(Opcode) && 11375 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) { 11376 return adjustWritemask(Node, DAG); 11377 } 11378 11379 if (Opcode == AMDGPU::INSERT_SUBREG || 11380 Opcode == AMDGPU::REG_SEQUENCE) { 11381 legalizeTargetIndependentNode(Node, DAG); 11382 return Node; 11383 } 11384 11385 switch (Opcode) { 11386 case AMDGPU::V_DIV_SCALE_F32_e64: 11387 case AMDGPU::V_DIV_SCALE_F64_e64: { 11388 // Satisfy the operand register constraint when one of the inputs is 11389 // undefined. Ordinarily each undef value will have its own implicit_def of 11390 // a vreg, so force these to use a single register. 11391 SDValue Src0 = Node->getOperand(1); 11392 SDValue Src1 = Node->getOperand(3); 11393 SDValue Src2 = Node->getOperand(5); 11394 11395 if ((Src0.isMachineOpcode() && 11396 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 11397 (Src0 == Src1 || Src0 == Src2)) 11398 break; 11399 11400 MVT VT = Src0.getValueType().getSimpleVT(); 11401 const TargetRegisterClass *RC = 11402 getRegClassFor(VT, Src0.getNode()->isDivergent()); 11403 11404 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11405 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 11406 11407 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 11408 UndefReg, Src0, SDValue()); 11409 11410 // src0 must be the same register as src1 or src2, even if the value is 11411 // undefined, so make sure we don't violate this constraint. 11412 if (Src0.isMachineOpcode() && 11413 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 11414 if (Src1.isMachineOpcode() && 11415 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11416 Src0 = Src1; 11417 else if (Src2.isMachineOpcode() && 11418 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11419 Src0 = Src2; 11420 else { 11421 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 11422 Src0 = UndefReg; 11423 Src1 = UndefReg; 11424 } 11425 } else 11426 break; 11427 11428 SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end()); 11429 Ops[1] = Src0; 11430 Ops[3] = Src1; 11431 Ops[5] = Src2; 11432 Ops.push_back(ImpDef.getValue(1)); 11433 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 11434 } 11435 default: 11436 break; 11437 } 11438 11439 return Node; 11440 } 11441 11442 // Any MIMG instructions that use tfe or lwe require an initialization of the 11443 // result register that will be written in the case of a memory access failure. 11444 // The required code is also added to tie this init code to the result of the 11445 // img instruction. 11446 void SITargetLowering::AddIMGInit(MachineInstr &MI) const { 11447 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11448 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 11449 MachineRegisterInfo &MRI = MI.getMF()->getRegInfo(); 11450 MachineBasicBlock &MBB = *MI.getParent(); 11451 11452 MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe); 11453 MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe); 11454 MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16); 11455 11456 if (!TFE && !LWE) // intersect_ray 11457 return; 11458 11459 unsigned TFEVal = TFE ? TFE->getImm() : 0; 11460 unsigned LWEVal = LWE->getImm(); 11461 unsigned D16Val = D16 ? D16->getImm() : 0; 11462 11463 if (!TFEVal && !LWEVal) 11464 return; 11465 11466 // At least one of TFE or LWE are non-zero 11467 // We have to insert a suitable initialization of the result value and 11468 // tie this to the dest of the image instruction. 11469 11470 const DebugLoc &DL = MI.getDebugLoc(); 11471 11472 int DstIdx = 11473 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata); 11474 11475 // Calculate which dword we have to initialize to 0. 11476 MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask); 11477 11478 // check that dmask operand is found. 11479 assert(MO_Dmask && "Expected dmask operand in instruction"); 11480 11481 unsigned dmask = MO_Dmask->getImm(); 11482 // Determine the number of active lanes taking into account the 11483 // Gather4 special case 11484 unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask); 11485 11486 bool Packed = !Subtarget->hasUnpackedD16VMem(); 11487 11488 unsigned InitIdx = 11489 D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1; 11490 11491 // Abandon attempt if the dst size isn't large enough 11492 // - this is in fact an error but this is picked up elsewhere and 11493 // reported correctly. 11494 uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32; 11495 if (DstSize < InitIdx) 11496 return; 11497 11498 // Create a register for the intialization value. 11499 Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11500 unsigned NewDst = 0; // Final initialized value will be in here 11501 11502 // If PRTStrictNull feature is enabled (the default) then initialize 11503 // all the result registers to 0, otherwise just the error indication 11504 // register (VGPRn+1) 11505 unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1; 11506 unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1); 11507 11508 BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst); 11509 for (; SizeLeft; SizeLeft--, CurrIdx++) { 11510 NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11511 // Initialize dword 11512 Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 11513 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg) 11514 .addImm(0); 11515 // Insert into the super-reg 11516 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst) 11517 .addReg(PrevDst) 11518 .addReg(SubReg) 11519 .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx)); 11520 11521 PrevDst = NewDst; 11522 } 11523 11524 // Add as an implicit operand 11525 MI.addOperand(MachineOperand::CreateReg(NewDst, false, true)); 11526 11527 // Tie the just added implicit operand to the dst 11528 MI.tieOperands(DstIdx, MI.getNumOperands() - 1); 11529 } 11530 11531 /// Assign the register class depending on the number of 11532 /// bits set in the writemask 11533 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11534 SDNode *Node) const { 11535 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11536 11537 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 11538 11539 if (TII->isVOP3(MI.getOpcode())) { 11540 // Make sure constant bus requirements are respected. 11541 TII->legalizeOperandsVOP3(MRI, MI); 11542 11543 // Prefer VGPRs over AGPRs in mAI instructions where possible. 11544 // This saves a chain-copy of registers and better ballance register 11545 // use between vgpr and agpr as agpr tuples tend to be big. 11546 if (MI.getDesc().OpInfo) { 11547 unsigned Opc = MI.getOpcode(); 11548 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11549 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 11550 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 11551 if (I == -1) 11552 break; 11553 MachineOperand &Op = MI.getOperand(I); 11554 if (!Op.isReg() || !Op.getReg().isVirtual()) 11555 continue; 11556 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11557 if (!TRI->hasAGPRs(RC)) 11558 continue; 11559 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11560 if (!Src || !Src->isCopy() || 11561 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11562 continue; 11563 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11564 // All uses of agpr64 and agpr32 can also accept vgpr except for 11565 // v_accvgpr_read, but we do not produce agpr reads during selection, 11566 // so no use checks are needed. 11567 MRI.setRegClass(Op.getReg(), NewRC); 11568 } 11569 } 11570 11571 return; 11572 } 11573 11574 // Replace unused atomics with the no return version. 11575 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 11576 if (NoRetAtomicOp != -1) { 11577 if (!Node->hasAnyUseOfValue(0)) { 11578 int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), 11579 AMDGPU::OpName::cpol); 11580 if (CPolIdx != -1) { 11581 MachineOperand &CPol = MI.getOperand(CPolIdx); 11582 CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC); 11583 } 11584 MI.RemoveOperand(0); 11585 MI.setDesc(TII->get(NoRetAtomicOp)); 11586 return; 11587 } 11588 11589 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 11590 // instruction, because the return type of these instructions is a vec2 of 11591 // the memory type, so it can be tied to the input operand. 11592 // This means these instructions always have a use, so we need to add a 11593 // special case to check if the atomic has only one extract_subreg use, 11594 // which itself has no uses. 11595 if ((Node->hasNUsesOfValue(1, 0) && 11596 Node->use_begin()->isMachineOpcode() && 11597 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 11598 !Node->use_begin()->hasAnyUseOfValue(0))) { 11599 Register Def = MI.getOperand(0).getReg(); 11600 11601 // Change this into a noret atomic. 11602 MI.setDesc(TII->get(NoRetAtomicOp)); 11603 MI.RemoveOperand(0); 11604 11605 // If we only remove the def operand from the atomic instruction, the 11606 // extract_subreg will be left with a use of a vreg without a def. 11607 // So we need to insert an implicit_def to avoid machine verifier 11608 // errors. 11609 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 11610 TII->get(AMDGPU::IMPLICIT_DEF), Def); 11611 } 11612 return; 11613 } 11614 11615 if (TII->isMIMG(MI) && !MI.mayStore()) 11616 AddIMGInit(MI); 11617 } 11618 11619 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11620 uint64_t Val) { 11621 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11622 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11623 } 11624 11625 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11626 const SDLoc &DL, 11627 SDValue Ptr) const { 11628 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11629 11630 // Build the half of the subregister with the constants before building the 11631 // full 128-bit register. If we are building multiple resource descriptors, 11632 // this will allow CSEing of the 2-component register. 11633 const SDValue Ops0[] = { 11634 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11635 buildSMovImm32(DAG, DL, 0), 11636 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11637 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11638 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11639 }; 11640 11641 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11642 MVT::v2i32, Ops0), 0); 11643 11644 // Combine the constants and the pointer. 11645 const SDValue Ops1[] = { 11646 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11647 Ptr, 11648 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11649 SubRegHi, 11650 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11651 }; 11652 11653 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11654 } 11655 11656 /// Return a resource descriptor with the 'Add TID' bit enabled 11657 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11658 /// of the resource descriptor) to create an offset, which is added to 11659 /// the resource pointer. 11660 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11661 SDValue Ptr, uint32_t RsrcDword1, 11662 uint64_t RsrcDword2And3) const { 11663 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11664 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11665 if (RsrcDword1) { 11666 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11667 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11668 0); 11669 } 11670 11671 SDValue DataLo = buildSMovImm32(DAG, DL, 11672 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11673 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11674 11675 const SDValue Ops[] = { 11676 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11677 PtrLo, 11678 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11679 PtrHi, 11680 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11681 DataLo, 11682 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11683 DataHi, 11684 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11685 }; 11686 11687 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11688 } 11689 11690 //===----------------------------------------------------------------------===// 11691 // SI Inline Assembly Support 11692 //===----------------------------------------------------------------------===// 11693 11694 std::pair<unsigned, const TargetRegisterClass *> 11695 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_, 11696 StringRef Constraint, 11697 MVT VT) const { 11698 const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_); 11699 11700 const TargetRegisterClass *RC = nullptr; 11701 if (Constraint.size() == 1) { 11702 const unsigned BitWidth = VT.getSizeInBits(); 11703 switch (Constraint[0]) { 11704 default: 11705 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11706 case 's': 11707 case 'r': 11708 switch (BitWidth) { 11709 case 16: 11710 RC = &AMDGPU::SReg_32RegClass; 11711 break; 11712 case 64: 11713 RC = &AMDGPU::SGPR_64RegClass; 11714 break; 11715 default: 11716 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11717 if (!RC) 11718 return std::make_pair(0U, nullptr); 11719 break; 11720 } 11721 break; 11722 case 'v': 11723 switch (BitWidth) { 11724 case 16: 11725 RC = &AMDGPU::VGPR_32RegClass; 11726 break; 11727 default: 11728 RC = TRI->getVGPRClassForBitWidth(BitWidth); 11729 if (!RC) 11730 return std::make_pair(0U, nullptr); 11731 break; 11732 } 11733 break; 11734 case 'a': 11735 if (!Subtarget->hasMAIInsts()) 11736 break; 11737 switch (BitWidth) { 11738 case 16: 11739 RC = &AMDGPU::AGPR_32RegClass; 11740 break; 11741 default: 11742 RC = TRI->getAGPRClassForBitWidth(BitWidth); 11743 if (!RC) 11744 return std::make_pair(0U, nullptr); 11745 break; 11746 } 11747 break; 11748 } 11749 // We actually support i128, i16 and f16 as inline parameters 11750 // even if they are not reported as legal 11751 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11752 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11753 return std::make_pair(0U, RC); 11754 } 11755 11756 if (Constraint.startswith("{") && Constraint.endswith("}")) { 11757 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2); 11758 if (RegName.consume_front("v")) { 11759 RC = &AMDGPU::VGPR_32RegClass; 11760 } else if (RegName.consume_front("s")) { 11761 RC = &AMDGPU::SGPR_32RegClass; 11762 } else if (RegName.consume_front("a")) { 11763 RC = &AMDGPU::AGPR_32RegClass; 11764 } 11765 11766 if (RC) { 11767 uint32_t Idx; 11768 if (RegName.consume_front("[")) { 11769 uint32_t End; 11770 bool Failed = RegName.consumeInteger(10, Idx); 11771 Failed |= !RegName.consume_front(":"); 11772 Failed |= RegName.consumeInteger(10, End); 11773 Failed |= !RegName.consume_back("]"); 11774 if (!Failed) { 11775 uint32_t Width = (End - Idx + 1) * 32; 11776 MCRegister Reg = RC->getRegister(Idx); 11777 if (SIRegisterInfo::isVGPRClass(RC)) 11778 RC = TRI->getVGPRClassForBitWidth(Width); 11779 else if (SIRegisterInfo::isSGPRClass(RC)) 11780 RC = TRI->getSGPRClassForBitWidth(Width); 11781 else if (SIRegisterInfo::isAGPRClass(RC)) 11782 RC = TRI->getAGPRClassForBitWidth(Width); 11783 if (RC) { 11784 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC); 11785 return std::make_pair(Reg, RC); 11786 } 11787 } 11788 } else { 11789 bool Failed = RegName.getAsInteger(10, Idx); 11790 if (!Failed && Idx < RC->getNumRegs()) 11791 return std::make_pair(RC->getRegister(Idx), RC); 11792 } 11793 } 11794 } 11795 11796 auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11797 if (Ret.first) 11798 Ret.second = TRI->getPhysRegClass(Ret.first); 11799 11800 return Ret; 11801 } 11802 11803 static bool isImmConstraint(StringRef Constraint) { 11804 if (Constraint.size() == 1) { 11805 switch (Constraint[0]) { 11806 default: break; 11807 case 'I': 11808 case 'J': 11809 case 'A': 11810 case 'B': 11811 case 'C': 11812 return true; 11813 } 11814 } else if (Constraint == "DA" || 11815 Constraint == "DB") { 11816 return true; 11817 } 11818 return false; 11819 } 11820 11821 SITargetLowering::ConstraintType 11822 SITargetLowering::getConstraintType(StringRef Constraint) const { 11823 if (Constraint.size() == 1) { 11824 switch (Constraint[0]) { 11825 default: break; 11826 case 's': 11827 case 'v': 11828 case 'a': 11829 return C_RegisterClass; 11830 } 11831 } 11832 if (isImmConstraint(Constraint)) { 11833 return C_Other; 11834 } 11835 return TargetLowering::getConstraintType(Constraint); 11836 } 11837 11838 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11839 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11840 Val = Val & maskTrailingOnes<uint64_t>(Size); 11841 } 11842 return Val; 11843 } 11844 11845 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11846 std::string &Constraint, 11847 std::vector<SDValue> &Ops, 11848 SelectionDAG &DAG) const { 11849 if (isImmConstraint(Constraint)) { 11850 uint64_t Val; 11851 if (getAsmOperandConstVal(Op, Val) && 11852 checkAsmConstraintVal(Op, Constraint, Val)) { 11853 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11854 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11855 } 11856 } else { 11857 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11858 } 11859 } 11860 11861 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11862 unsigned Size = Op.getScalarValueSizeInBits(); 11863 if (Size > 64) 11864 return false; 11865 11866 if (Size == 16 && !Subtarget->has16BitInsts()) 11867 return false; 11868 11869 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11870 Val = C->getSExtValue(); 11871 return true; 11872 } 11873 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11874 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11875 return true; 11876 } 11877 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11878 if (Size != 16 || Op.getNumOperands() != 2) 11879 return false; 11880 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11881 return false; 11882 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11883 Val = C->getSExtValue(); 11884 return true; 11885 } 11886 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11887 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11888 return true; 11889 } 11890 } 11891 11892 return false; 11893 } 11894 11895 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 11896 const std::string &Constraint, 11897 uint64_t Val) const { 11898 if (Constraint.size() == 1) { 11899 switch (Constraint[0]) { 11900 case 'I': 11901 return AMDGPU::isInlinableIntLiteral(Val); 11902 case 'J': 11903 return isInt<16>(Val); 11904 case 'A': 11905 return checkAsmConstraintValA(Op, Val); 11906 case 'B': 11907 return isInt<32>(Val); 11908 case 'C': 11909 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 11910 AMDGPU::isInlinableIntLiteral(Val); 11911 default: 11912 break; 11913 } 11914 } else if (Constraint.size() == 2) { 11915 if (Constraint == "DA") { 11916 int64_t HiBits = static_cast<int32_t>(Val >> 32); 11917 int64_t LoBits = static_cast<int32_t>(Val); 11918 return checkAsmConstraintValA(Op, HiBits, 32) && 11919 checkAsmConstraintValA(Op, LoBits, 32); 11920 } 11921 if (Constraint == "DB") { 11922 return true; 11923 } 11924 } 11925 llvm_unreachable("Invalid asm constraint"); 11926 } 11927 11928 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 11929 uint64_t Val, 11930 unsigned MaxSize) const { 11931 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 11932 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11933 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11934 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11935 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11936 return true; 11937 } 11938 return false; 11939 } 11940 11941 static int getAlignedAGPRClassID(unsigned UnalignedClassID) { 11942 switch (UnalignedClassID) { 11943 case AMDGPU::VReg_64RegClassID: 11944 return AMDGPU::VReg_64_Align2RegClassID; 11945 case AMDGPU::VReg_96RegClassID: 11946 return AMDGPU::VReg_96_Align2RegClassID; 11947 case AMDGPU::VReg_128RegClassID: 11948 return AMDGPU::VReg_128_Align2RegClassID; 11949 case AMDGPU::VReg_160RegClassID: 11950 return AMDGPU::VReg_160_Align2RegClassID; 11951 case AMDGPU::VReg_192RegClassID: 11952 return AMDGPU::VReg_192_Align2RegClassID; 11953 case AMDGPU::VReg_224RegClassID: 11954 return AMDGPU::VReg_224_Align2RegClassID; 11955 case AMDGPU::VReg_256RegClassID: 11956 return AMDGPU::VReg_256_Align2RegClassID; 11957 case AMDGPU::VReg_512RegClassID: 11958 return AMDGPU::VReg_512_Align2RegClassID; 11959 case AMDGPU::VReg_1024RegClassID: 11960 return AMDGPU::VReg_1024_Align2RegClassID; 11961 case AMDGPU::AReg_64RegClassID: 11962 return AMDGPU::AReg_64_Align2RegClassID; 11963 case AMDGPU::AReg_96RegClassID: 11964 return AMDGPU::AReg_96_Align2RegClassID; 11965 case AMDGPU::AReg_128RegClassID: 11966 return AMDGPU::AReg_128_Align2RegClassID; 11967 case AMDGPU::AReg_160RegClassID: 11968 return AMDGPU::AReg_160_Align2RegClassID; 11969 case AMDGPU::AReg_192RegClassID: 11970 return AMDGPU::AReg_192_Align2RegClassID; 11971 case AMDGPU::AReg_256RegClassID: 11972 return AMDGPU::AReg_256_Align2RegClassID; 11973 case AMDGPU::AReg_512RegClassID: 11974 return AMDGPU::AReg_512_Align2RegClassID; 11975 case AMDGPU::AReg_1024RegClassID: 11976 return AMDGPU::AReg_1024_Align2RegClassID; 11977 default: 11978 return -1; 11979 } 11980 } 11981 11982 // Figure out which registers should be reserved for stack access. Only after 11983 // the function is legalized do we know all of the non-spill stack objects or if 11984 // calls are present. 11985 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 11986 MachineRegisterInfo &MRI = MF.getRegInfo(); 11987 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11988 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 11989 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11990 const SIInstrInfo *TII = ST.getInstrInfo(); 11991 11992 if (Info->isEntryFunction()) { 11993 // Callable functions have fixed registers used for stack access. 11994 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 11995 } 11996 11997 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 11998 Info->getStackPtrOffsetReg())); 11999 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 12000 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 12001 12002 // We need to worry about replacing the default register with itself in case 12003 // of MIR testcases missing the MFI. 12004 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 12005 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 12006 12007 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 12008 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 12009 12010 Info->limitOccupancy(MF); 12011 12012 if (ST.isWave32() && !MF.empty()) { 12013 for (auto &MBB : MF) { 12014 for (auto &MI : MBB) { 12015 TII->fixImplicitOperands(MI); 12016 } 12017 } 12018 } 12019 12020 // FIXME: This is a hack to fixup AGPR classes to use the properly aligned 12021 // classes if required. Ideally the register class constraints would differ 12022 // per-subtarget, but there's no easy way to achieve that right now. This is 12023 // not a problem for VGPRs because the correctly aligned VGPR class is implied 12024 // from using them as the register class for legal types. 12025 if (ST.needsAlignedVGPRs()) { 12026 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) { 12027 const Register Reg = Register::index2VirtReg(I); 12028 const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg); 12029 if (!RC) 12030 continue; 12031 int NewClassID = getAlignedAGPRClassID(RC->getID()); 12032 if (NewClassID != -1) 12033 MRI.setRegClass(Reg, TRI->getRegClass(NewClassID)); 12034 } 12035 } 12036 12037 TargetLoweringBase::finalizeLowering(MF); 12038 } 12039 12040 void SITargetLowering::computeKnownBitsForFrameIndex( 12041 const int FI, KnownBits &Known, const MachineFunction &MF) const { 12042 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 12043 12044 // Set the high bits to zero based on the maximum allowed scratch size per 12045 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 12046 // calculation won't overflow, so assume the sign bit is never set. 12047 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 12048 } 12049 12050 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 12051 KnownBits &Known, unsigned Dim) { 12052 unsigned MaxValue = 12053 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 12054 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 12055 } 12056 12057 void SITargetLowering::computeKnownBitsForTargetInstr( 12058 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 12059 const MachineRegisterInfo &MRI, unsigned Depth) const { 12060 const MachineInstr *MI = MRI.getVRegDef(R); 12061 switch (MI->getOpcode()) { 12062 case AMDGPU::G_INTRINSIC: { 12063 switch (MI->getIntrinsicID()) { 12064 case Intrinsic::amdgcn_workitem_id_x: 12065 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 12066 break; 12067 case Intrinsic::amdgcn_workitem_id_y: 12068 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 12069 break; 12070 case Intrinsic::amdgcn_workitem_id_z: 12071 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 12072 break; 12073 case Intrinsic::amdgcn_mbcnt_lo: 12074 case Intrinsic::amdgcn_mbcnt_hi: { 12075 // These return at most the wavefront size - 1. 12076 unsigned Size = MRI.getType(R).getSizeInBits(); 12077 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 12078 break; 12079 } 12080 case Intrinsic::amdgcn_groupstaticsize: { 12081 // We can report everything over the maximum size as 0. We can't report 12082 // based on the actual size because we don't know if it's accurate or not 12083 // at any given point. 12084 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 12085 break; 12086 } 12087 } 12088 break; 12089 } 12090 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE: 12091 Known.Zero.setHighBits(24); 12092 break; 12093 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT: 12094 Known.Zero.setHighBits(16); 12095 break; 12096 } 12097 } 12098 12099 Align SITargetLowering::computeKnownAlignForTargetInstr( 12100 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 12101 unsigned Depth) const { 12102 const MachineInstr *MI = MRI.getVRegDef(R); 12103 switch (MI->getOpcode()) { 12104 case AMDGPU::G_INTRINSIC: 12105 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 12106 // FIXME: Can this move to generic code? What about the case where the call 12107 // site specifies a lower alignment? 12108 Intrinsic::ID IID = MI->getIntrinsicID(); 12109 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 12110 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 12111 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 12112 return *RetAlign; 12113 return Align(1); 12114 } 12115 default: 12116 return Align(1); 12117 } 12118 } 12119 12120 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 12121 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 12122 const Align CacheLineAlign = Align(64); 12123 12124 // Pre-GFX10 target did not benefit from loop alignment 12125 if (!ML || DisableLoopAlignment || 12126 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 12127 getSubtarget()->hasInstFwdPrefetchBug()) 12128 return PrefAlign; 12129 12130 // On GFX10 I$ is 4 x 64 bytes cache lines. 12131 // By default prefetcher keeps one cache line behind and reads two ahead. 12132 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 12133 // behind and one ahead. 12134 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 12135 // If loop fits 64 bytes it always spans no more than two cache lines and 12136 // does not need an alignment. 12137 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 12138 // Else if loop is less or equal 192 bytes we need two lines behind. 12139 12140 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 12141 const MachineBasicBlock *Header = ML->getHeader(); 12142 if (Header->getAlignment() != PrefAlign) 12143 return Header->getAlignment(); // Already processed. 12144 12145 unsigned LoopSize = 0; 12146 for (const MachineBasicBlock *MBB : ML->blocks()) { 12147 // If inner loop block is aligned assume in average half of the alignment 12148 // size to be added as nops. 12149 if (MBB != Header) 12150 LoopSize += MBB->getAlignment().value() / 2; 12151 12152 for (const MachineInstr &MI : *MBB) { 12153 LoopSize += TII->getInstSizeInBytes(MI); 12154 if (LoopSize > 192) 12155 return PrefAlign; 12156 } 12157 } 12158 12159 if (LoopSize <= 64) 12160 return PrefAlign; 12161 12162 if (LoopSize <= 128) 12163 return CacheLineAlign; 12164 12165 // If any of parent loops is surrounded by prefetch instructions do not 12166 // insert new for inner loop, which would reset parent's settings. 12167 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 12168 if (MachineBasicBlock *Exit = P->getExitBlock()) { 12169 auto I = Exit->getFirstNonDebugInstr(); 12170 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 12171 return CacheLineAlign; 12172 } 12173 } 12174 12175 MachineBasicBlock *Pre = ML->getLoopPreheader(); 12176 MachineBasicBlock *Exit = ML->getExitBlock(); 12177 12178 if (Pre && Exit) { 12179 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 12180 TII->get(AMDGPU::S_INST_PREFETCH)) 12181 .addImm(1); // prefetch 2 lines behind PC 12182 12183 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 12184 TII->get(AMDGPU::S_INST_PREFETCH)) 12185 .addImm(2); // prefetch 1 line behind PC 12186 } 12187 12188 return CacheLineAlign; 12189 } 12190 12191 LLVM_ATTRIBUTE_UNUSED 12192 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 12193 assert(N->getOpcode() == ISD::CopyFromReg); 12194 do { 12195 // Follow the chain until we find an INLINEASM node. 12196 N = N->getOperand(0).getNode(); 12197 if (N->getOpcode() == ISD::INLINEASM || 12198 N->getOpcode() == ISD::INLINEASM_BR) 12199 return true; 12200 } while (N->getOpcode() == ISD::CopyFromReg); 12201 return false; 12202 } 12203 12204 bool SITargetLowering::isSDNodeSourceOfDivergence( 12205 const SDNode *N, FunctionLoweringInfo *FLI, 12206 LegacyDivergenceAnalysis *KDA) const { 12207 switch (N->getOpcode()) { 12208 case ISD::CopyFromReg: { 12209 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 12210 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 12211 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12212 Register Reg = R->getReg(); 12213 12214 // FIXME: Why does this need to consider isLiveIn? 12215 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 12216 return !TRI->isSGPRReg(MRI, Reg); 12217 12218 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 12219 return KDA->isDivergent(V); 12220 12221 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 12222 return !TRI->isSGPRReg(MRI, Reg); 12223 } 12224 case ISD::LOAD: { 12225 const LoadSDNode *L = cast<LoadSDNode>(N); 12226 unsigned AS = L->getAddressSpace(); 12227 // A flat load may access private memory. 12228 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 12229 } 12230 case ISD::CALLSEQ_END: 12231 return true; 12232 case ISD::INTRINSIC_WO_CHAIN: 12233 return AMDGPU::isIntrinsicSourceOfDivergence( 12234 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 12235 case ISD::INTRINSIC_W_CHAIN: 12236 return AMDGPU::isIntrinsicSourceOfDivergence( 12237 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 12238 case AMDGPUISD::ATOMIC_CMP_SWAP: 12239 case AMDGPUISD::ATOMIC_INC: 12240 case AMDGPUISD::ATOMIC_DEC: 12241 case AMDGPUISD::ATOMIC_LOAD_FMIN: 12242 case AMDGPUISD::ATOMIC_LOAD_FMAX: 12243 case AMDGPUISD::BUFFER_ATOMIC_SWAP: 12244 case AMDGPUISD::BUFFER_ATOMIC_ADD: 12245 case AMDGPUISD::BUFFER_ATOMIC_SUB: 12246 case AMDGPUISD::BUFFER_ATOMIC_SMIN: 12247 case AMDGPUISD::BUFFER_ATOMIC_UMIN: 12248 case AMDGPUISD::BUFFER_ATOMIC_SMAX: 12249 case AMDGPUISD::BUFFER_ATOMIC_UMAX: 12250 case AMDGPUISD::BUFFER_ATOMIC_AND: 12251 case AMDGPUISD::BUFFER_ATOMIC_OR: 12252 case AMDGPUISD::BUFFER_ATOMIC_XOR: 12253 case AMDGPUISD::BUFFER_ATOMIC_INC: 12254 case AMDGPUISD::BUFFER_ATOMIC_DEC: 12255 case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP: 12256 case AMDGPUISD::BUFFER_ATOMIC_CSUB: 12257 case AMDGPUISD::BUFFER_ATOMIC_FADD: 12258 case AMDGPUISD::BUFFER_ATOMIC_FMIN: 12259 case AMDGPUISD::BUFFER_ATOMIC_FMAX: 12260 // Target-specific read-modify-write atomics are sources of divergence. 12261 return true; 12262 default: 12263 if (auto *A = dyn_cast<AtomicSDNode>(N)) { 12264 // Generic read-modify-write atomics are sources of divergence. 12265 return A->readMem() && A->writeMem(); 12266 } 12267 return false; 12268 } 12269 } 12270 12271 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 12272 EVT VT) const { 12273 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 12274 case MVT::f32: 12275 return hasFP32Denormals(DAG.getMachineFunction()); 12276 case MVT::f64: 12277 case MVT::f16: 12278 return hasFP64FP16Denormals(DAG.getMachineFunction()); 12279 default: 12280 return false; 12281 } 12282 } 12283 12284 bool SITargetLowering::denormalsEnabledForType(LLT Ty, 12285 MachineFunction &MF) const { 12286 switch (Ty.getScalarSizeInBits()) { 12287 case 32: 12288 return hasFP32Denormals(MF); 12289 case 64: 12290 case 16: 12291 return hasFP64FP16Denormals(MF); 12292 default: 12293 return false; 12294 } 12295 } 12296 12297 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 12298 const SelectionDAG &DAG, 12299 bool SNaN, 12300 unsigned Depth) const { 12301 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 12302 const MachineFunction &MF = DAG.getMachineFunction(); 12303 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 12304 12305 if (Info->getMode().DX10Clamp) 12306 return true; // Clamped to 0. 12307 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 12308 } 12309 12310 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 12311 SNaN, Depth); 12312 } 12313 12314 // Global FP atomic instructions have a hardcoded FP mode and do not support 12315 // FP32 denormals, and only support v2f16 denormals. 12316 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) { 12317 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics(); 12318 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt); 12319 if (&Flt == &APFloat::IEEEsingle()) 12320 return DenormMode == DenormalMode::getPreserveSign(); 12321 return DenormMode == DenormalMode::getIEEE(); 12322 } 12323 12324 TargetLowering::AtomicExpansionKind 12325 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 12326 12327 auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) { 12328 OptimizationRemarkEmitter ORE(RMW->getFunction()); 12329 LLVMContext &Ctx = RMW->getFunction()->getContext(); 12330 SmallVector<StringRef> SSNs; 12331 Ctx.getSyncScopeNames(SSNs); 12332 auto MemScope = SSNs[RMW->getSyncScopeID()].empty() 12333 ? "system" 12334 : SSNs[RMW->getSyncScopeID()]; 12335 ORE.emit([&]() { 12336 return OptimizationRemark(DEBUG_TYPE, "Passed", RMW) 12337 << "Hardware instruction generated for atomic " 12338 << RMW->getOperationName(RMW->getOperation()) 12339 << " operation at memory scope " << MemScope 12340 << " due to an unsafe request."; 12341 }); 12342 return Kind; 12343 }; 12344 12345 switch (RMW->getOperation()) { 12346 case AtomicRMWInst::FAdd: { 12347 Type *Ty = RMW->getType(); 12348 12349 // We don't have a way to support 16-bit atomics now, so just leave them 12350 // as-is. 12351 if (Ty->isHalfTy()) 12352 return AtomicExpansionKind::None; 12353 12354 if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy())) 12355 return AtomicExpansionKind::CmpXChg; 12356 12357 unsigned AS = RMW->getPointerAddressSpace(); 12358 12359 if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) && 12360 Subtarget->hasAtomicFaddInsts()) { 12361 // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe 12362 // floating point atomic instructions. May generate more efficient code, 12363 // but may not respect rounding and denormal modes, and may give incorrect 12364 // results for certain memory destinations. 12365 if (RMW->getFunction() 12366 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12367 .getValueAsString() != "true") 12368 return AtomicExpansionKind::CmpXChg; 12369 12370 if (Subtarget->hasGFX90AInsts()) { 12371 if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS) 12372 return AtomicExpansionKind::CmpXChg; 12373 12374 auto SSID = RMW->getSyncScopeID(); 12375 if (SSID == SyncScope::System || 12376 SSID == RMW->getContext().getOrInsertSyncScopeID("one-as")) 12377 return AtomicExpansionKind::CmpXChg; 12378 12379 return ReportUnsafeHWInst(AtomicExpansionKind::None); 12380 } 12381 12382 if (AS == AMDGPUAS::FLAT_ADDRESS) 12383 return AtomicExpansionKind::CmpXChg; 12384 12385 return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None) 12386 : AtomicExpansionKind::CmpXChg; 12387 } 12388 12389 // DS FP atomics do repect the denormal mode, but the rounding mode is fixed 12390 // to round-to-nearest-even. 12391 // The only exception is DS_ADD_F64 which never flushes regardless of mode. 12392 if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) { 12393 if (!Ty->isDoubleTy()) 12394 return AtomicExpansionKind::None; 12395 12396 if (fpModeMatchesGlobalFPAtomicMode(RMW)) 12397 return AtomicExpansionKind::None; 12398 12399 return RMW->getFunction() 12400 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12401 .getValueAsString() == "true" 12402 ? ReportUnsafeHWInst(AtomicExpansionKind::None) 12403 : AtomicExpansionKind::CmpXChg; 12404 } 12405 12406 return AtomicExpansionKind::CmpXChg; 12407 } 12408 default: 12409 break; 12410 } 12411 12412 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 12413 } 12414 12415 const TargetRegisterClass * 12416 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 12417 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 12418 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12419 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 12420 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 12421 : &AMDGPU::SReg_32RegClass; 12422 if (!TRI->isSGPRClass(RC) && !isDivergent) 12423 return TRI->getEquivalentSGPRClass(RC); 12424 else if (TRI->isSGPRClass(RC) && isDivergent) 12425 return TRI->getEquivalentVGPRClass(RC); 12426 12427 return RC; 12428 } 12429 12430 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 12431 // uniform values (as produced by the mask results of control flow intrinsics) 12432 // used outside of divergent blocks. The phi users need to also be treated as 12433 // always uniform. 12434 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 12435 unsigned WaveSize) { 12436 // FIXME: We asssume we never cast the mask results of a control flow 12437 // intrinsic. 12438 // Early exit if the type won't be consistent as a compile time hack. 12439 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 12440 if (!IT || IT->getBitWidth() != WaveSize) 12441 return false; 12442 12443 if (!isa<Instruction>(V)) 12444 return false; 12445 if (!Visited.insert(V).second) 12446 return false; 12447 bool Result = false; 12448 for (auto U : V->users()) { 12449 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 12450 if (V == U->getOperand(1)) { 12451 switch (Intrinsic->getIntrinsicID()) { 12452 default: 12453 Result = false; 12454 break; 12455 case Intrinsic::amdgcn_if_break: 12456 case Intrinsic::amdgcn_if: 12457 case Intrinsic::amdgcn_else: 12458 Result = true; 12459 break; 12460 } 12461 } 12462 if (V == U->getOperand(0)) { 12463 switch (Intrinsic->getIntrinsicID()) { 12464 default: 12465 Result = false; 12466 break; 12467 case Intrinsic::amdgcn_end_cf: 12468 case Intrinsic::amdgcn_loop: 12469 Result = true; 12470 break; 12471 } 12472 } 12473 } else { 12474 Result = hasCFUser(U, Visited, WaveSize); 12475 } 12476 if (Result) 12477 break; 12478 } 12479 return Result; 12480 } 12481 12482 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 12483 const Value *V) const { 12484 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 12485 if (CI->isInlineAsm()) { 12486 // FIXME: This cannot give a correct answer. This should only trigger in 12487 // the case where inline asm returns mixed SGPR and VGPR results, used 12488 // outside the defining block. We don't have a specific result to 12489 // consider, so this assumes if any value is SGPR, the overall register 12490 // also needs to be SGPR. 12491 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 12492 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 12493 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 12494 for (auto &TC : TargetConstraints) { 12495 if (TC.Type == InlineAsm::isOutput) { 12496 ComputeConstraintToUse(TC, SDValue()); 12497 const TargetRegisterClass *RC = getRegForInlineAsmConstraint( 12498 SIRI, TC.ConstraintCode, TC.ConstraintVT).second; 12499 if (RC && SIRI->isSGPRClass(RC)) 12500 return true; 12501 } 12502 } 12503 } 12504 } 12505 SmallPtrSet<const Value *, 16> Visited; 12506 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 12507 } 12508 12509 std::pair<InstructionCost, MVT> 12510 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 12511 Type *Ty) const { 12512 std::pair<InstructionCost, MVT> Cost = 12513 TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 12514 auto Size = DL.getTypeSizeInBits(Ty); 12515 // Maximum load or store can handle 8 dwords for scalar and 4 for 12516 // vector ALU. Let's assume anything above 8 dwords is expensive 12517 // even if legal. 12518 if (Size <= 256) 12519 return Cost; 12520 12521 Cost.first += (Size + 255) / 256; 12522 return Cost; 12523 } 12524