1 //===-- SystemZTargetTransformInfo.cpp - SystemZ-specific TTI -------------===// 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 // This file implements a TargetTransformInfo analysis pass specific to the 10 // SystemZ target machine. It uses the target's detailed information to provide 11 // more precise answers to certain TTI queries, while letting the target 12 // independent and default TTI implementations handle the rest. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "SystemZTargetTransformInfo.h" 17 #include "llvm/Analysis/TargetTransformInfo.h" 18 #include "llvm/CodeGen/BasicTTIImpl.h" 19 #include "llvm/CodeGen/CostTable.h" 20 #include "llvm/CodeGen/TargetLowering.h" 21 #include "llvm/IR/IntrinsicInst.h" 22 #include "llvm/Support/Debug.h" 23 using namespace llvm; 24 25 #define DEBUG_TYPE "systemztti" 26 27 //===----------------------------------------------------------------------===// 28 // 29 // SystemZ cost model. 30 // 31 //===----------------------------------------------------------------------===// 32 33 int SystemZTTIImpl::getIntImmCost(const APInt &Imm, Type *Ty, 34 TTI::TargetCostKind CostKind) { 35 assert(Ty->isIntegerTy()); 36 37 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 38 // There is no cost model for constants with a bit size of 0. Return TCC_Free 39 // here, so that constant hoisting will ignore this constant. 40 if (BitSize == 0) 41 return TTI::TCC_Free; 42 // No cost model for operations on integers larger than 64 bit implemented yet. 43 if (BitSize > 64) 44 return TTI::TCC_Free; 45 46 if (Imm == 0) 47 return TTI::TCC_Free; 48 49 if (Imm.getBitWidth() <= 64) { 50 // Constants loaded via lgfi. 51 if (isInt<32>(Imm.getSExtValue())) 52 return TTI::TCC_Basic; 53 // Constants loaded via llilf. 54 if (isUInt<32>(Imm.getZExtValue())) 55 return TTI::TCC_Basic; 56 // Constants loaded via llihf: 57 if ((Imm.getZExtValue() & 0xffffffff) == 0) 58 return TTI::TCC_Basic; 59 60 return 2 * TTI::TCC_Basic; 61 } 62 63 return 4 * TTI::TCC_Basic; 64 } 65 66 int SystemZTTIImpl::getIntImmCostInst(unsigned Opcode, unsigned Idx, 67 const APInt &Imm, Type *Ty, 68 TTI::TargetCostKind CostKind, 69 Instruction *Inst) { 70 assert(Ty->isIntegerTy()); 71 72 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 73 // There is no cost model for constants with a bit size of 0. Return TCC_Free 74 // here, so that constant hoisting will ignore this constant. 75 if (BitSize == 0) 76 return TTI::TCC_Free; 77 // No cost model for operations on integers larger than 64 bit implemented yet. 78 if (BitSize > 64) 79 return TTI::TCC_Free; 80 81 switch (Opcode) { 82 default: 83 return TTI::TCC_Free; 84 case Instruction::GetElementPtr: 85 // Always hoist the base address of a GetElementPtr. This prevents the 86 // creation of new constants for every base constant that gets constant 87 // folded with the offset. 88 if (Idx == 0) 89 return 2 * TTI::TCC_Basic; 90 return TTI::TCC_Free; 91 case Instruction::Store: 92 if (Idx == 0 && Imm.getBitWidth() <= 64) { 93 // Any 8-bit immediate store can by implemented via mvi. 94 if (BitSize == 8) 95 return TTI::TCC_Free; 96 // 16-bit immediate values can be stored via mvhhi/mvhi/mvghi. 97 if (isInt<16>(Imm.getSExtValue())) 98 return TTI::TCC_Free; 99 } 100 break; 101 case Instruction::ICmp: 102 if (Idx == 1 && Imm.getBitWidth() <= 64) { 103 // Comparisons against signed 32-bit immediates implemented via cgfi. 104 if (isInt<32>(Imm.getSExtValue())) 105 return TTI::TCC_Free; 106 // Comparisons against unsigned 32-bit immediates implemented via clgfi. 107 if (isUInt<32>(Imm.getZExtValue())) 108 return TTI::TCC_Free; 109 } 110 break; 111 case Instruction::Add: 112 case Instruction::Sub: 113 if (Idx == 1 && Imm.getBitWidth() <= 64) { 114 // We use algfi/slgfi to add/subtract 32-bit unsigned immediates. 115 if (isUInt<32>(Imm.getZExtValue())) 116 return TTI::TCC_Free; 117 // Or their negation, by swapping addition vs. subtraction. 118 if (isUInt<32>(-Imm.getSExtValue())) 119 return TTI::TCC_Free; 120 } 121 break; 122 case Instruction::Mul: 123 if (Idx == 1 && Imm.getBitWidth() <= 64) { 124 // We use msgfi to multiply by 32-bit signed immediates. 125 if (isInt<32>(Imm.getSExtValue())) 126 return TTI::TCC_Free; 127 } 128 break; 129 case Instruction::Or: 130 case Instruction::Xor: 131 if (Idx == 1 && Imm.getBitWidth() <= 64) { 132 // Masks supported by oilf/xilf. 133 if (isUInt<32>(Imm.getZExtValue())) 134 return TTI::TCC_Free; 135 // Masks supported by oihf/xihf. 136 if ((Imm.getZExtValue() & 0xffffffff) == 0) 137 return TTI::TCC_Free; 138 } 139 break; 140 case Instruction::And: 141 if (Idx == 1 && Imm.getBitWidth() <= 64) { 142 // Any 32-bit AND operation can by implemented via nilf. 143 if (BitSize <= 32) 144 return TTI::TCC_Free; 145 // 64-bit masks supported by nilf. 146 if (isUInt<32>(~Imm.getZExtValue())) 147 return TTI::TCC_Free; 148 // 64-bit masks supported by nilh. 149 if ((Imm.getZExtValue() & 0xffffffff) == 0xffffffff) 150 return TTI::TCC_Free; 151 // Some 64-bit AND operations can be implemented via risbg. 152 const SystemZInstrInfo *TII = ST->getInstrInfo(); 153 unsigned Start, End; 154 if (TII->isRxSBGMask(Imm.getZExtValue(), BitSize, Start, End)) 155 return TTI::TCC_Free; 156 } 157 break; 158 case Instruction::Shl: 159 case Instruction::LShr: 160 case Instruction::AShr: 161 // Always return TCC_Free for the shift value of a shift instruction. 162 if (Idx == 1) 163 return TTI::TCC_Free; 164 break; 165 case Instruction::UDiv: 166 case Instruction::SDiv: 167 case Instruction::URem: 168 case Instruction::SRem: 169 case Instruction::Trunc: 170 case Instruction::ZExt: 171 case Instruction::SExt: 172 case Instruction::IntToPtr: 173 case Instruction::PtrToInt: 174 case Instruction::BitCast: 175 case Instruction::PHI: 176 case Instruction::Call: 177 case Instruction::Select: 178 case Instruction::Ret: 179 case Instruction::Load: 180 break; 181 } 182 183 return SystemZTTIImpl::getIntImmCost(Imm, Ty, CostKind); 184 } 185 186 int SystemZTTIImpl::getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx, 187 const APInt &Imm, Type *Ty, 188 TTI::TargetCostKind CostKind) { 189 assert(Ty->isIntegerTy()); 190 191 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 192 // There is no cost model for constants with a bit size of 0. Return TCC_Free 193 // here, so that constant hoisting will ignore this constant. 194 if (BitSize == 0) 195 return TTI::TCC_Free; 196 // No cost model for operations on integers larger than 64 bit implemented yet. 197 if (BitSize > 64) 198 return TTI::TCC_Free; 199 200 switch (IID) { 201 default: 202 return TTI::TCC_Free; 203 case Intrinsic::sadd_with_overflow: 204 case Intrinsic::uadd_with_overflow: 205 case Intrinsic::ssub_with_overflow: 206 case Intrinsic::usub_with_overflow: 207 // These get expanded to include a normal addition/subtraction. 208 if (Idx == 1 && Imm.getBitWidth() <= 64) { 209 if (isUInt<32>(Imm.getZExtValue())) 210 return TTI::TCC_Free; 211 if (isUInt<32>(-Imm.getSExtValue())) 212 return TTI::TCC_Free; 213 } 214 break; 215 case Intrinsic::smul_with_overflow: 216 case Intrinsic::umul_with_overflow: 217 // These get expanded to include a normal multiplication. 218 if (Idx == 1 && Imm.getBitWidth() <= 64) { 219 if (isInt<32>(Imm.getSExtValue())) 220 return TTI::TCC_Free; 221 } 222 break; 223 case Intrinsic::experimental_stackmap: 224 if ((Idx < 2) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue()))) 225 return TTI::TCC_Free; 226 break; 227 case Intrinsic::experimental_patchpoint_void: 228 case Intrinsic::experimental_patchpoint_i64: 229 if ((Idx < 4) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue()))) 230 return TTI::TCC_Free; 231 break; 232 } 233 return SystemZTTIImpl::getIntImmCost(Imm, Ty, CostKind); 234 } 235 236 TargetTransformInfo::PopcntSupportKind 237 SystemZTTIImpl::getPopcntSupport(unsigned TyWidth) { 238 assert(isPowerOf2_32(TyWidth) && "Type width must be power of 2"); 239 if (ST->hasPopulationCount() && TyWidth <= 64) 240 return TTI::PSK_FastHardware; 241 return TTI::PSK_Software; 242 } 243 244 void SystemZTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE, 245 TTI::UnrollingPreferences &UP) { 246 // Find out if L contains a call, what the machine instruction count 247 // estimate is, and how many stores there are. 248 bool HasCall = false; 249 unsigned NumStores = 0; 250 for (auto &BB : L->blocks()) 251 for (auto &I : *BB) { 252 if (isa<CallInst>(&I) || isa<InvokeInst>(&I)) { 253 if (const Function *F = cast<CallBase>(I).getCalledFunction()) { 254 if (isLoweredToCall(F)) 255 HasCall = true; 256 if (F->getIntrinsicID() == Intrinsic::memcpy || 257 F->getIntrinsicID() == Intrinsic::memset) 258 NumStores++; 259 } else { // indirect call. 260 HasCall = true; 261 } 262 } 263 if (isa<StoreInst>(&I)) { 264 Type *MemAccessTy = I.getOperand(0)->getType(); 265 NumStores += getMemoryOpCost(Instruction::Store, MemAccessTy, None, 0, 266 TTI::TCK_RecipThroughput); 267 } 268 } 269 270 // The z13 processor will run out of store tags if too many stores 271 // are fed into it too quickly. Therefore make sure there are not 272 // too many stores in the resulting unrolled loop. 273 unsigned const Max = (NumStores ? (12 / NumStores) : UINT_MAX); 274 275 if (HasCall) { 276 // Only allow full unrolling if loop has any calls. 277 UP.FullUnrollMaxCount = Max; 278 UP.MaxCount = 1; 279 return; 280 } 281 282 UP.MaxCount = Max; 283 if (UP.MaxCount <= 1) 284 return; 285 286 // Allow partial and runtime trip count unrolling. 287 UP.Partial = UP.Runtime = true; 288 289 UP.PartialThreshold = 75; 290 UP.DefaultUnrollRuntimeCount = 4; 291 292 // Allow expensive instructions in the pre-header of the loop. 293 UP.AllowExpensiveTripCount = true; 294 295 UP.Force = true; 296 } 297 298 void SystemZTTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE, 299 TTI::PeelingPreferences &PP) { 300 BaseT::getPeelingPreferences(L, SE, PP); 301 } 302 303 bool SystemZTTIImpl::isLSRCostLess(TargetTransformInfo::LSRCost &C1, 304 TargetTransformInfo::LSRCost &C2) { 305 // SystemZ specific: check instruction count (first), and don't care about 306 // ImmCost, since offsets are checked explicitly. 307 return std::tie(C1.Insns, C1.NumRegs, C1.AddRecCost, 308 C1.NumIVMuls, C1.NumBaseAdds, 309 C1.ScaleCost, C1.SetupCost) < 310 std::tie(C2.Insns, C2.NumRegs, C2.AddRecCost, 311 C2.NumIVMuls, C2.NumBaseAdds, 312 C2.ScaleCost, C2.SetupCost); 313 } 314 315 unsigned SystemZTTIImpl::getNumberOfRegisters(unsigned ClassID) const { 316 bool Vector = (ClassID == 1); 317 if (!Vector) 318 // Discount the stack pointer. Also leave out %r0, since it can't 319 // be used in an address. 320 return 14; 321 if (ST->hasVector()) 322 return 32; 323 return 0; 324 } 325 326 unsigned SystemZTTIImpl::getRegisterBitWidth(bool Vector) const { 327 if (!Vector) 328 return 64; 329 if (ST->hasVector()) 330 return 128; 331 return 0; 332 } 333 334 unsigned SystemZTTIImpl::getMinPrefetchStride(unsigned NumMemAccesses, 335 unsigned NumStridedMemAccesses, 336 unsigned NumPrefetches, 337 bool HasCall) const { 338 // Don't prefetch a loop with many far apart accesses. 339 if (NumPrefetches > 16) 340 return UINT_MAX; 341 342 // Emit prefetch instructions for smaller strides in cases where we think 343 // the hardware prefetcher might not be able to keep up. 344 if (NumStridedMemAccesses > 32 && !HasCall && 345 (NumMemAccesses - NumStridedMemAccesses) * 32 <= NumStridedMemAccesses) 346 return 1; 347 348 return ST->hasMiscellaneousExtensions3() ? 8192 : 2048; 349 } 350 351 bool SystemZTTIImpl::hasDivRemOp(Type *DataType, bool IsSigned) { 352 EVT VT = TLI->getValueType(DL, DataType); 353 return (VT.isScalarInteger() && TLI->isTypeLegal(VT)); 354 } 355 356 // Return the bit size for the scalar type or vector element 357 // type. getScalarSizeInBits() returns 0 for a pointer type. 358 static unsigned getScalarSizeInBits(Type *Ty) { 359 unsigned Size = 360 (Ty->isPtrOrPtrVectorTy() ? 64U : Ty->getScalarSizeInBits()); 361 assert(Size > 0 && "Element must have non-zero size."); 362 return Size; 363 } 364 365 // getNumberOfParts() calls getTypeLegalizationCost() which splits the vector 366 // type until it is legal. This would e.g. return 4 for <6 x i64>, instead of 367 // 3. 368 static unsigned getNumVectorRegs(Type *Ty) { 369 auto *VTy = cast<FixedVectorType>(Ty); 370 unsigned WideBits = getScalarSizeInBits(Ty) * VTy->getNumElements(); 371 assert(WideBits > 0 && "Could not compute size of vector"); 372 return ((WideBits % 128U) ? ((WideBits / 128U) + 1) : (WideBits / 128U)); 373 } 374 375 int SystemZTTIImpl::getArithmeticInstrCost( 376 unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind, 377 TTI::OperandValueKind Op1Info, 378 TTI::OperandValueKind Op2Info, TTI::OperandValueProperties Opd1PropInfo, 379 TTI::OperandValueProperties Opd2PropInfo, ArrayRef<const Value *> Args, 380 const Instruction *CxtI) { 381 382 // TODO: Handle more cost kinds. 383 if (CostKind != TTI::TCK_RecipThroughput) 384 return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info, 385 Op2Info, Opd1PropInfo, 386 Opd2PropInfo, Args, CxtI); 387 388 // TODO: return a good value for BB-VECTORIZER that includes the 389 // immediate loads, which we do not want to count for the loop 390 // vectorizer, since they are hopefully hoisted out of the loop. This 391 // would require a new parameter 'InLoop', but not sure if constant 392 // args are common enough to motivate this. 393 394 unsigned ScalarBits = Ty->getScalarSizeInBits(); 395 396 // There are thre cases of division and remainder: Dividing with a register 397 // needs a divide instruction. A divisor which is a power of two constant 398 // can be implemented with a sequence of shifts. Any other constant needs a 399 // multiply and shifts. 400 const unsigned DivInstrCost = 20; 401 const unsigned DivMulSeqCost = 10; 402 const unsigned SDivPow2Cost = 4; 403 404 bool SignedDivRem = 405 Opcode == Instruction::SDiv || Opcode == Instruction::SRem; 406 bool UnsignedDivRem = 407 Opcode == Instruction::UDiv || Opcode == Instruction::URem; 408 409 // Check for a constant divisor. 410 bool DivRemConst = false; 411 bool DivRemConstPow2 = false; 412 if ((SignedDivRem || UnsignedDivRem) && Args.size() == 2) { 413 if (const Constant *C = dyn_cast<Constant>(Args[1])) { 414 const ConstantInt *CVal = 415 (C->getType()->isVectorTy() 416 ? dyn_cast_or_null<const ConstantInt>(C->getSplatValue()) 417 : dyn_cast<const ConstantInt>(C)); 418 if (CVal != nullptr && 419 (CVal->getValue().isPowerOf2() || (-CVal->getValue()).isPowerOf2())) 420 DivRemConstPow2 = true; 421 else 422 DivRemConst = true; 423 } 424 } 425 426 if (!Ty->isVectorTy()) { 427 // These FP operations are supported with a dedicated instruction for 428 // float, double and fp128 (base implementation assumes float generally 429 // costs 2). 430 if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub || 431 Opcode == Instruction::FMul || Opcode == Instruction::FDiv) 432 return 1; 433 434 // There is no native support for FRem. 435 if (Opcode == Instruction::FRem) 436 return LIBCALL_COST; 437 438 // Give discount for some combined logical operations if supported. 439 if (Args.size() == 2 && ST->hasMiscellaneousExtensions3()) { 440 if (Opcode == Instruction::Xor) { 441 for (const Value *A : Args) { 442 if (const Instruction *I = dyn_cast<Instruction>(A)) 443 if (I->hasOneUse() && 444 (I->getOpcode() == Instruction::And || 445 I->getOpcode() == Instruction::Or || 446 I->getOpcode() == Instruction::Xor)) 447 return 0; 448 } 449 } 450 else if (Opcode == Instruction::Or || Opcode == Instruction::And) { 451 for (const Value *A : Args) { 452 if (const Instruction *I = dyn_cast<Instruction>(A)) 453 if (I->hasOneUse() && I->getOpcode() == Instruction::Xor) 454 return 0; 455 } 456 } 457 } 458 459 // Or requires one instruction, although it has custom handling for i64. 460 if (Opcode == Instruction::Or) 461 return 1; 462 463 if (Opcode == Instruction::Xor && ScalarBits == 1) { 464 if (ST->hasLoadStoreOnCond2()) 465 return 5; // 2 * (li 0; loc 1); xor 466 return 7; // 2 * ipm sequences ; xor ; shift ; compare 467 } 468 469 if (DivRemConstPow2) 470 return (SignedDivRem ? SDivPow2Cost : 1); 471 if (DivRemConst) 472 return DivMulSeqCost; 473 if (SignedDivRem || UnsignedDivRem) 474 return DivInstrCost; 475 } 476 else if (ST->hasVector()) { 477 auto *VTy = cast<FixedVectorType>(Ty); 478 unsigned VF = VTy->getNumElements(); 479 unsigned NumVectors = getNumVectorRegs(Ty); 480 481 // These vector operations are custom handled, but are still supported 482 // with one instruction per vector, regardless of element size. 483 if (Opcode == Instruction::Shl || Opcode == Instruction::LShr || 484 Opcode == Instruction::AShr) { 485 return NumVectors; 486 } 487 488 if (DivRemConstPow2) 489 return (NumVectors * (SignedDivRem ? SDivPow2Cost : 1)); 490 if (DivRemConst) { 491 SmallVector<Type *> Tys(Args.size(), Ty); 492 return VF * DivMulSeqCost + getScalarizationOverhead(VTy, Args, Tys); 493 } 494 if ((SignedDivRem || UnsignedDivRem) && VF > 4) 495 // Temporary hack: disable high vectorization factors with integer 496 // division/remainder, which will get scalarized and handled with 497 // GR128 registers. The mischeduler is not clever enough to avoid 498 // spilling yet. 499 return 1000; 500 501 // These FP operations are supported with a single vector instruction for 502 // double (base implementation assumes float generally costs 2). For 503 // FP128, the scalar cost is 1, and there is no overhead since the values 504 // are already in scalar registers. 505 if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub || 506 Opcode == Instruction::FMul || Opcode == Instruction::FDiv) { 507 switch (ScalarBits) { 508 case 32: { 509 // The vector enhancements facility 1 provides v4f32 instructions. 510 if (ST->hasVectorEnhancements1()) 511 return NumVectors; 512 // Return the cost of multiple scalar invocation plus the cost of 513 // inserting and extracting the values. 514 unsigned ScalarCost = 515 getArithmeticInstrCost(Opcode, Ty->getScalarType(), CostKind); 516 SmallVector<Type *> Tys(Args.size(), Ty); 517 unsigned Cost = 518 (VF * ScalarCost) + getScalarizationOverhead(VTy, Args, Tys); 519 // FIXME: VF 2 for these FP operations are currently just as 520 // expensive as for VF 4. 521 if (VF == 2) 522 Cost *= 2; 523 return Cost; 524 } 525 case 64: 526 case 128: 527 return NumVectors; 528 default: 529 break; 530 } 531 } 532 533 // There is no native support for FRem. 534 if (Opcode == Instruction::FRem) { 535 SmallVector<Type *> Tys(Args.size(), Ty); 536 unsigned Cost = 537 (VF * LIBCALL_COST) + getScalarizationOverhead(VTy, Args, Tys); 538 // FIXME: VF 2 for float is currently just as expensive as for VF 4. 539 if (VF == 2 && ScalarBits == 32) 540 Cost *= 2; 541 return Cost; 542 } 543 } 544 545 // Fallback to the default implementation. 546 return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info, Op2Info, 547 Opd1PropInfo, Opd2PropInfo, Args, CxtI); 548 } 549 550 int SystemZTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, VectorType *Tp, 551 int Index, VectorType *SubTp) { 552 if (ST->hasVector()) { 553 unsigned NumVectors = getNumVectorRegs(Tp); 554 555 // TODO: Since fp32 is expanded, the shuffle cost should always be 0. 556 557 // FP128 values are always in scalar registers, so there is no work 558 // involved with a shuffle, except for broadcast. In that case register 559 // moves are done with a single instruction per element. 560 if (Tp->getScalarType()->isFP128Ty()) 561 return (Kind == TargetTransformInfo::SK_Broadcast ? NumVectors - 1 : 0); 562 563 switch (Kind) { 564 case TargetTransformInfo::SK_ExtractSubvector: 565 // ExtractSubvector Index indicates start offset. 566 567 // Extracting a subvector from first index is a noop. 568 return (Index == 0 ? 0 : NumVectors); 569 570 case TargetTransformInfo::SK_Broadcast: 571 // Loop vectorizer calls here to figure out the extra cost of 572 // broadcasting a loaded value to all elements of a vector. Since vlrep 573 // loads and replicates with a single instruction, adjust the returned 574 // value. 575 return NumVectors - 1; 576 577 default: 578 579 // SystemZ supports single instruction permutation / replication. 580 return NumVectors; 581 } 582 } 583 584 return BaseT::getShuffleCost(Kind, Tp, Index, SubTp); 585 } 586 587 // Return the log2 difference of the element sizes of the two vector types. 588 static unsigned getElSizeLog2Diff(Type *Ty0, Type *Ty1) { 589 unsigned Bits0 = Ty0->getScalarSizeInBits(); 590 unsigned Bits1 = Ty1->getScalarSizeInBits(); 591 592 if (Bits1 > Bits0) 593 return (Log2_32(Bits1) - Log2_32(Bits0)); 594 595 return (Log2_32(Bits0) - Log2_32(Bits1)); 596 } 597 598 // Return the number of instructions needed to truncate SrcTy to DstTy. 599 unsigned SystemZTTIImpl:: 600 getVectorTruncCost(Type *SrcTy, Type *DstTy) { 601 assert (SrcTy->isVectorTy() && DstTy->isVectorTy()); 602 assert(SrcTy->getPrimitiveSizeInBits().getFixedSize() > 603 DstTy->getPrimitiveSizeInBits().getFixedSize() && 604 "Packing must reduce size of vector type."); 605 assert(cast<FixedVectorType>(SrcTy)->getNumElements() == 606 cast<FixedVectorType>(DstTy)->getNumElements() && 607 "Packing should not change number of elements."); 608 609 // TODO: Since fp32 is expanded, the extract cost should always be 0. 610 611 unsigned NumParts = getNumVectorRegs(SrcTy); 612 if (NumParts <= 2) 613 // Up to 2 vector registers can be truncated efficiently with pack or 614 // permute. The latter requires an immediate mask to be loaded, which 615 // typically gets hoisted out of a loop. TODO: return a good value for 616 // BB-VECTORIZER that includes the immediate loads, which we do not want 617 // to count for the loop vectorizer. 618 return 1; 619 620 unsigned Cost = 0; 621 unsigned Log2Diff = getElSizeLog2Diff(SrcTy, DstTy); 622 unsigned VF = cast<FixedVectorType>(SrcTy)->getNumElements(); 623 for (unsigned P = 0; P < Log2Diff; ++P) { 624 if (NumParts > 1) 625 NumParts /= 2; 626 Cost += NumParts; 627 } 628 629 // Currently, a general mix of permutes and pack instructions is output by 630 // isel, which follow the cost computation above except for this case which 631 // is one instruction less: 632 if (VF == 8 && SrcTy->getScalarSizeInBits() == 64 && 633 DstTy->getScalarSizeInBits() == 8) 634 Cost--; 635 636 return Cost; 637 } 638 639 // Return the cost of converting a vector bitmask produced by a compare 640 // (SrcTy), to the type of the select or extend instruction (DstTy). 641 unsigned SystemZTTIImpl:: 642 getVectorBitmaskConversionCost(Type *SrcTy, Type *DstTy) { 643 assert (SrcTy->isVectorTy() && DstTy->isVectorTy() && 644 "Should only be called with vector types."); 645 646 unsigned PackCost = 0; 647 unsigned SrcScalarBits = SrcTy->getScalarSizeInBits(); 648 unsigned DstScalarBits = DstTy->getScalarSizeInBits(); 649 unsigned Log2Diff = getElSizeLog2Diff(SrcTy, DstTy); 650 if (SrcScalarBits > DstScalarBits) 651 // The bitmask will be truncated. 652 PackCost = getVectorTruncCost(SrcTy, DstTy); 653 else if (SrcScalarBits < DstScalarBits) { 654 unsigned DstNumParts = getNumVectorRegs(DstTy); 655 // Each vector select needs its part of the bitmask unpacked. 656 PackCost = Log2Diff * DstNumParts; 657 // Extra cost for moving part of mask before unpacking. 658 PackCost += DstNumParts - 1; 659 } 660 661 return PackCost; 662 } 663 664 // Return the type of the compared operands. This is needed to compute the 665 // cost for a Select / ZExt or SExt instruction. 666 static Type *getCmpOpsType(const Instruction *I, unsigned VF = 1) { 667 Type *OpTy = nullptr; 668 if (CmpInst *CI = dyn_cast<CmpInst>(I->getOperand(0))) 669 OpTy = CI->getOperand(0)->getType(); 670 else if (Instruction *LogicI = dyn_cast<Instruction>(I->getOperand(0))) 671 if (LogicI->getNumOperands() == 2) 672 if (CmpInst *CI0 = dyn_cast<CmpInst>(LogicI->getOperand(0))) 673 if (isa<CmpInst>(LogicI->getOperand(1))) 674 OpTy = CI0->getOperand(0)->getType(); 675 676 if (OpTy != nullptr) { 677 if (VF == 1) { 678 assert (!OpTy->isVectorTy() && "Expected scalar type"); 679 return OpTy; 680 } 681 // Return the potentially vectorized type based on 'I' and 'VF'. 'I' may 682 // be either scalar or already vectorized with a same or lesser VF. 683 Type *ElTy = OpTy->getScalarType(); 684 return FixedVectorType::get(ElTy, VF); 685 } 686 687 return nullptr; 688 } 689 690 // Get the cost of converting a boolean vector to a vector with same width 691 // and element size as Dst, plus the cost of zero extending if needed. 692 unsigned SystemZTTIImpl:: 693 getBoolVecToIntConversionCost(unsigned Opcode, Type *Dst, 694 const Instruction *I) { 695 auto *DstVTy = cast<FixedVectorType>(Dst); 696 unsigned VF = DstVTy->getNumElements(); 697 unsigned Cost = 0; 698 // If we know what the widths of the compared operands, get any cost of 699 // converting it to match Dst. Otherwise assume same widths. 700 Type *CmpOpTy = ((I != nullptr) ? getCmpOpsType(I, VF) : nullptr); 701 if (CmpOpTy != nullptr) 702 Cost = getVectorBitmaskConversionCost(CmpOpTy, Dst); 703 if (Opcode == Instruction::ZExt || Opcode == Instruction::UIToFP) 704 // One 'vn' per dst vector with an immediate mask. 705 Cost += getNumVectorRegs(Dst); 706 return Cost; 707 } 708 709 int SystemZTTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, 710 TTI::CastContextHint CCH, 711 TTI::TargetCostKind CostKind, 712 const Instruction *I) { 713 // FIXME: Can the logic below also be used for these cost kinds? 714 if (CostKind == TTI::TCK_CodeSize || CostKind == TTI::TCK_SizeAndLatency) { 715 int BaseCost = BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I); 716 return BaseCost == 0 ? BaseCost : 1; 717 } 718 719 unsigned DstScalarBits = Dst->getScalarSizeInBits(); 720 unsigned SrcScalarBits = Src->getScalarSizeInBits(); 721 722 if (!Src->isVectorTy()) { 723 assert (!Dst->isVectorTy()); 724 725 if (Opcode == Instruction::SIToFP || Opcode == Instruction::UIToFP) { 726 if (SrcScalarBits >= 32 || 727 (I != nullptr && isa<LoadInst>(I->getOperand(0)))) 728 return 1; 729 return SrcScalarBits > 1 ? 2 /*i8/i16 extend*/ : 5 /*branch seq.*/; 730 } 731 732 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) && 733 Src->isIntegerTy(1)) { 734 if (ST->hasLoadStoreOnCond2()) 735 return 2; // li 0; loc 1 736 737 // This should be extension of a compare i1 result, which is done with 738 // ipm and a varying sequence of instructions. 739 unsigned Cost = 0; 740 if (Opcode == Instruction::SExt) 741 Cost = (DstScalarBits < 64 ? 3 : 4); 742 if (Opcode == Instruction::ZExt) 743 Cost = 3; 744 Type *CmpOpTy = ((I != nullptr) ? getCmpOpsType(I) : nullptr); 745 if (CmpOpTy != nullptr && CmpOpTy->isFloatingPointTy()) 746 // If operands of an fp-type was compared, this costs +1. 747 Cost++; 748 return Cost; 749 } 750 } 751 else if (ST->hasVector()) { 752 auto *SrcVecTy = cast<FixedVectorType>(Src); 753 auto *DstVecTy = cast<FixedVectorType>(Dst); 754 unsigned VF = SrcVecTy->getNumElements(); 755 unsigned NumDstVectors = getNumVectorRegs(Dst); 756 unsigned NumSrcVectors = getNumVectorRegs(Src); 757 758 if (Opcode == Instruction::Trunc) { 759 if (Src->getScalarSizeInBits() == Dst->getScalarSizeInBits()) 760 return 0; // Check for NOOP conversions. 761 return getVectorTruncCost(Src, Dst); 762 } 763 764 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) { 765 if (SrcScalarBits >= 8) { 766 // ZExt/SExt will be handled with one unpack per doubling of width. 767 unsigned NumUnpacks = getElSizeLog2Diff(Src, Dst); 768 769 // For types that spans multiple vector registers, some additional 770 // instructions are used to setup the unpacking. 771 unsigned NumSrcVectorOps = 772 (NumUnpacks > 1 ? (NumDstVectors - NumSrcVectors) 773 : (NumDstVectors / 2)); 774 775 return (NumUnpacks * NumDstVectors) + NumSrcVectorOps; 776 } 777 else if (SrcScalarBits == 1) 778 return getBoolVecToIntConversionCost(Opcode, Dst, I); 779 } 780 781 if (Opcode == Instruction::SIToFP || Opcode == Instruction::UIToFP || 782 Opcode == Instruction::FPToSI || Opcode == Instruction::FPToUI) { 783 // TODO: Fix base implementation which could simplify things a bit here 784 // (seems to miss on differentiating on scalar/vector types). 785 786 // Only 64 bit vector conversions are natively supported before z15. 787 if (DstScalarBits == 64 || ST->hasVectorEnhancements2()) { 788 if (SrcScalarBits == DstScalarBits) 789 return NumDstVectors; 790 791 if (SrcScalarBits == 1) 792 return getBoolVecToIntConversionCost(Opcode, Dst, I) + NumDstVectors; 793 } 794 795 // Return the cost of multiple scalar invocation plus the cost of 796 // inserting and extracting the values. Base implementation does not 797 // realize float->int gets scalarized. 798 unsigned ScalarCost = getCastInstrCost( 799 Opcode, Dst->getScalarType(), Src->getScalarType(), CCH, CostKind); 800 unsigned TotCost = VF * ScalarCost; 801 bool NeedsInserts = true, NeedsExtracts = true; 802 // FP128 registers do not get inserted or extracted. 803 if (DstScalarBits == 128 && 804 (Opcode == Instruction::SIToFP || Opcode == Instruction::UIToFP)) 805 NeedsInserts = false; 806 if (SrcScalarBits == 128 && 807 (Opcode == Instruction::FPToSI || Opcode == Instruction::FPToUI)) 808 NeedsExtracts = false; 809 810 TotCost += getScalarizationOverhead(SrcVecTy, false, NeedsExtracts); 811 TotCost += getScalarizationOverhead(DstVecTy, NeedsInserts, false); 812 813 // FIXME: VF 2 for float<->i32 is currently just as expensive as for VF 4. 814 if (VF == 2 && SrcScalarBits == 32 && DstScalarBits == 32) 815 TotCost *= 2; 816 817 return TotCost; 818 } 819 820 if (Opcode == Instruction::FPTrunc) { 821 if (SrcScalarBits == 128) // fp128 -> double/float + inserts of elements. 822 return VF /*ldxbr/lexbr*/ + 823 getScalarizationOverhead(DstVecTy, true, false); 824 else // double -> float 825 return VF / 2 /*vledb*/ + std::max(1U, VF / 4 /*vperm*/); 826 } 827 828 if (Opcode == Instruction::FPExt) { 829 if (SrcScalarBits == 32 && DstScalarBits == 64) { 830 // float -> double is very rare and currently unoptimized. Instead of 831 // using vldeb, which can do two at a time, all conversions are 832 // scalarized. 833 return VF * 2; 834 } 835 // -> fp128. VF * lxdb/lxeb + extraction of elements. 836 return VF + getScalarizationOverhead(SrcVecTy, false, true); 837 } 838 } 839 840 return BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I); 841 } 842 843 // Scalar i8 / i16 operations will typically be made after first extending 844 // the operands to i32. 845 static unsigned getOperandsExtensionCost(const Instruction *I) { 846 unsigned ExtCost = 0; 847 for (Value *Op : I->operands()) 848 // A load of i8 or i16 sign/zero extends to i32. 849 if (!isa<LoadInst>(Op) && !isa<ConstantInt>(Op)) 850 ExtCost++; 851 852 return ExtCost; 853 } 854 855 int SystemZTTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy, 856 Type *CondTy, CmpInst::Predicate VecPred, 857 TTI::TargetCostKind CostKind, 858 const Instruction *I) { 859 if (CostKind != TTI::TCK_RecipThroughput) 860 return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind); 861 862 if (!ValTy->isVectorTy()) { 863 switch (Opcode) { 864 case Instruction::ICmp: { 865 // A loaded value compared with 0 with multiple users becomes Load and 866 // Test. The load is then not foldable, so return 0 cost for the ICmp. 867 unsigned ScalarBits = ValTy->getScalarSizeInBits(); 868 if (I != nullptr && ScalarBits >= 32) 869 if (LoadInst *Ld = dyn_cast<LoadInst>(I->getOperand(0))) 870 if (const ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1))) 871 if (!Ld->hasOneUse() && Ld->getParent() == I->getParent() && 872 C->isZero()) 873 return 0; 874 875 unsigned Cost = 1; 876 if (ValTy->isIntegerTy() && ValTy->getScalarSizeInBits() <= 16) 877 Cost += (I != nullptr ? getOperandsExtensionCost(I) : 2); 878 return Cost; 879 } 880 case Instruction::Select: 881 if (ValTy->isFloatingPointTy()) 882 return 4; // No load on condition for FP - costs a conditional jump. 883 return 1; // Load On Condition / Select Register. 884 } 885 } 886 else if (ST->hasVector()) { 887 unsigned VF = cast<FixedVectorType>(ValTy)->getNumElements(); 888 889 // Called with a compare instruction. 890 if (Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) { 891 unsigned PredicateExtraCost = 0; 892 if (I != nullptr) { 893 // Some predicates cost one or two extra instructions. 894 switch (cast<CmpInst>(I)->getPredicate()) { 895 case CmpInst::Predicate::ICMP_NE: 896 case CmpInst::Predicate::ICMP_UGE: 897 case CmpInst::Predicate::ICMP_ULE: 898 case CmpInst::Predicate::ICMP_SGE: 899 case CmpInst::Predicate::ICMP_SLE: 900 PredicateExtraCost = 1; 901 break; 902 case CmpInst::Predicate::FCMP_ONE: 903 case CmpInst::Predicate::FCMP_ORD: 904 case CmpInst::Predicate::FCMP_UEQ: 905 case CmpInst::Predicate::FCMP_UNO: 906 PredicateExtraCost = 2; 907 break; 908 default: 909 break; 910 } 911 } 912 913 // Float is handled with 2*vmr[lh]f + 2*vldeb + vfchdb for each pair of 914 // floats. FIXME: <2 x float> generates same code as <4 x float>. 915 unsigned CmpCostPerVector = (ValTy->getScalarType()->isFloatTy() ? 10 : 1); 916 unsigned NumVecs_cmp = getNumVectorRegs(ValTy); 917 918 unsigned Cost = (NumVecs_cmp * (CmpCostPerVector + PredicateExtraCost)); 919 return Cost; 920 } 921 else { // Called with a select instruction. 922 assert (Opcode == Instruction::Select); 923 924 // We can figure out the extra cost of packing / unpacking if the 925 // instruction was passed and the compare instruction is found. 926 unsigned PackCost = 0; 927 Type *CmpOpTy = ((I != nullptr) ? getCmpOpsType(I, VF) : nullptr); 928 if (CmpOpTy != nullptr) 929 PackCost = 930 getVectorBitmaskConversionCost(CmpOpTy, ValTy); 931 932 return getNumVectorRegs(ValTy) /*vsel*/ + PackCost; 933 } 934 } 935 936 return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind); 937 } 938 939 int SystemZTTIImpl:: 940 getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) { 941 // vlvgp will insert two grs into a vector register, so only count half the 942 // number of instructions. 943 if (Opcode == Instruction::InsertElement && Val->isIntOrIntVectorTy(64)) 944 return ((Index % 2 == 0) ? 1 : 0); 945 946 if (Opcode == Instruction::ExtractElement) { 947 int Cost = ((getScalarSizeInBits(Val) == 1) ? 2 /*+test-under-mask*/ : 1); 948 949 // Give a slight penalty for moving out of vector pipeline to FXU unit. 950 if (Index == 0 && Val->isIntOrIntVectorTy()) 951 Cost += 1; 952 953 return Cost; 954 } 955 956 return BaseT::getVectorInstrCost(Opcode, Val, Index); 957 } 958 959 // Check if a load may be folded as a memory operand in its user. 960 bool SystemZTTIImpl:: 961 isFoldableLoad(const LoadInst *Ld, const Instruction *&FoldedValue) { 962 if (!Ld->hasOneUse()) 963 return false; 964 FoldedValue = Ld; 965 const Instruction *UserI = cast<Instruction>(*Ld->user_begin()); 966 unsigned LoadedBits = getScalarSizeInBits(Ld->getType()); 967 unsigned TruncBits = 0; 968 unsigned SExtBits = 0; 969 unsigned ZExtBits = 0; 970 if (UserI->hasOneUse()) { 971 unsigned UserBits = UserI->getType()->getScalarSizeInBits(); 972 if (isa<TruncInst>(UserI)) 973 TruncBits = UserBits; 974 else if (isa<SExtInst>(UserI)) 975 SExtBits = UserBits; 976 else if (isa<ZExtInst>(UserI)) 977 ZExtBits = UserBits; 978 } 979 if (TruncBits || SExtBits || ZExtBits) { 980 FoldedValue = UserI; 981 UserI = cast<Instruction>(*UserI->user_begin()); 982 // Load (single use) -> trunc/extend (single use) -> UserI 983 } 984 if ((UserI->getOpcode() == Instruction::Sub || 985 UserI->getOpcode() == Instruction::SDiv || 986 UserI->getOpcode() == Instruction::UDiv) && 987 UserI->getOperand(1) != FoldedValue) 988 return false; // Not commutative, only RHS foldable. 989 // LoadOrTruncBits holds the number of effectively loaded bits, but 0 if an 990 // extension was made of the load. 991 unsigned LoadOrTruncBits = 992 ((SExtBits || ZExtBits) ? 0 : (TruncBits ? TruncBits : LoadedBits)); 993 switch (UserI->getOpcode()) { 994 case Instruction::Add: // SE: 16->32, 16/32->64, z14:16->64. ZE: 32->64 995 case Instruction::Sub: 996 case Instruction::ICmp: 997 if (LoadedBits == 32 && ZExtBits == 64) 998 return true; 999 LLVM_FALLTHROUGH; 1000 case Instruction::Mul: // SE: 16->32, 32->64, z14:16->64 1001 if (UserI->getOpcode() != Instruction::ICmp) { 1002 if (LoadedBits == 16 && 1003 (SExtBits == 32 || 1004 (SExtBits == 64 && ST->hasMiscellaneousExtensions2()))) 1005 return true; 1006 if (LoadOrTruncBits == 16) 1007 return true; 1008 } 1009 LLVM_FALLTHROUGH; 1010 case Instruction::SDiv:// SE: 32->64 1011 if (LoadedBits == 32 && SExtBits == 64) 1012 return true; 1013 LLVM_FALLTHROUGH; 1014 case Instruction::UDiv: 1015 case Instruction::And: 1016 case Instruction::Or: 1017 case Instruction::Xor: 1018 // This also makes sense for float operations, but disabled for now due 1019 // to regressions. 1020 // case Instruction::FCmp: 1021 // case Instruction::FAdd: 1022 // case Instruction::FSub: 1023 // case Instruction::FMul: 1024 // case Instruction::FDiv: 1025 1026 // All possible extensions of memory checked above. 1027 1028 // Comparison between memory and immediate. 1029 if (UserI->getOpcode() == Instruction::ICmp) 1030 if (ConstantInt *CI = dyn_cast<ConstantInt>(UserI->getOperand(1))) 1031 if (CI->getValue().isIntN(16)) 1032 return true; 1033 return (LoadOrTruncBits == 32 || LoadOrTruncBits == 64); 1034 break; 1035 } 1036 return false; 1037 } 1038 1039 static bool isBswapIntrinsicCall(const Value *V) { 1040 if (const Instruction *I = dyn_cast<Instruction>(V)) 1041 if (auto *CI = dyn_cast<CallInst>(I)) 1042 if (auto *F = CI->getCalledFunction()) 1043 if (F->getIntrinsicID() == Intrinsic::bswap) 1044 return true; 1045 return false; 1046 } 1047 1048 int SystemZTTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src, 1049 MaybeAlign Alignment, unsigned AddressSpace, 1050 TTI::TargetCostKind CostKind, 1051 const Instruction *I) { 1052 assert(!Src->isVoidTy() && "Invalid type"); 1053 1054 // TODO: Handle other cost kinds. 1055 if (CostKind != TTI::TCK_RecipThroughput) 1056 return 1; 1057 1058 if (!Src->isVectorTy() && Opcode == Instruction::Load && I != nullptr) { 1059 // Store the load or its truncated or extended value in FoldedValue. 1060 const Instruction *FoldedValue = nullptr; 1061 if (isFoldableLoad(cast<LoadInst>(I), FoldedValue)) { 1062 const Instruction *UserI = cast<Instruction>(*FoldedValue->user_begin()); 1063 assert (UserI->getNumOperands() == 2 && "Expected a binop."); 1064 1065 // UserI can't fold two loads, so in that case return 0 cost only 1066 // half of the time. 1067 for (unsigned i = 0; i < 2; ++i) { 1068 if (UserI->getOperand(i) == FoldedValue) 1069 continue; 1070 1071 if (Instruction *OtherOp = dyn_cast<Instruction>(UserI->getOperand(i))){ 1072 LoadInst *OtherLoad = dyn_cast<LoadInst>(OtherOp); 1073 if (!OtherLoad && 1074 (isa<TruncInst>(OtherOp) || isa<SExtInst>(OtherOp) || 1075 isa<ZExtInst>(OtherOp))) 1076 OtherLoad = dyn_cast<LoadInst>(OtherOp->getOperand(0)); 1077 if (OtherLoad && isFoldableLoad(OtherLoad, FoldedValue/*dummy*/)) 1078 return i == 0; // Both operands foldable. 1079 } 1080 } 1081 1082 return 0; // Only I is foldable in user. 1083 } 1084 } 1085 1086 unsigned NumOps = 1087 (Src->isVectorTy() ? getNumVectorRegs(Src) : getNumberOfParts(Src)); 1088 1089 // Store/Load reversed saves one instruction. 1090 if (((!Src->isVectorTy() && NumOps == 1) || ST->hasVectorEnhancements2()) && 1091 I != nullptr) { 1092 if (Opcode == Instruction::Load && I->hasOneUse()) { 1093 const Instruction *LdUser = cast<Instruction>(*I->user_begin()); 1094 // In case of load -> bswap -> store, return normal cost for the load. 1095 if (isBswapIntrinsicCall(LdUser) && 1096 (!LdUser->hasOneUse() || !isa<StoreInst>(*LdUser->user_begin()))) 1097 return 0; 1098 } 1099 else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) { 1100 const Value *StoredVal = SI->getValueOperand(); 1101 if (StoredVal->hasOneUse() && isBswapIntrinsicCall(StoredVal)) 1102 return 0; 1103 } 1104 } 1105 1106 if (Src->getScalarSizeInBits() == 128) 1107 // 128 bit scalars are held in a pair of two 64 bit registers. 1108 NumOps *= 2; 1109 1110 return NumOps; 1111 } 1112 1113 // The generic implementation of getInterleavedMemoryOpCost() is based on 1114 // adding costs of the memory operations plus all the extracts and inserts 1115 // needed for using / defining the vector operands. The SystemZ version does 1116 // roughly the same but bases the computations on vector permutations 1117 // instead. 1118 int SystemZTTIImpl::getInterleavedMemoryOpCost( 1119 unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices, 1120 Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, 1121 bool UseMaskForCond, bool UseMaskForGaps) { 1122 if (UseMaskForCond || UseMaskForGaps) 1123 return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices, 1124 Alignment, AddressSpace, CostKind, 1125 UseMaskForCond, UseMaskForGaps); 1126 assert(isa<VectorType>(VecTy) && 1127 "Expect a vector type for interleaved memory op"); 1128 1129 // Return the ceiling of dividing A by B. 1130 auto ceil = [](unsigned A, unsigned B) { return (A + B - 1) / B; }; 1131 1132 unsigned NumElts = cast<FixedVectorType>(VecTy)->getNumElements(); 1133 assert(Factor > 1 && NumElts % Factor == 0 && "Invalid interleave factor"); 1134 unsigned VF = NumElts / Factor; 1135 unsigned NumEltsPerVecReg = (128U / getScalarSizeInBits(VecTy)); 1136 unsigned NumVectorMemOps = getNumVectorRegs(VecTy); 1137 unsigned NumPermutes = 0; 1138 1139 if (Opcode == Instruction::Load) { 1140 // Loading interleave groups may have gaps, which may mean fewer 1141 // loads. Find out how many vectors will be loaded in total, and in how 1142 // many of them each value will be in. 1143 BitVector UsedInsts(NumVectorMemOps, false); 1144 std::vector<BitVector> ValueVecs(Factor, BitVector(NumVectorMemOps, false)); 1145 for (unsigned Index : Indices) 1146 for (unsigned Elt = 0; Elt < VF; ++Elt) { 1147 unsigned Vec = (Index + Elt * Factor) / NumEltsPerVecReg; 1148 UsedInsts.set(Vec); 1149 ValueVecs[Index].set(Vec); 1150 } 1151 NumVectorMemOps = UsedInsts.count(); 1152 1153 for (unsigned Index : Indices) { 1154 // Estimate that each loaded source vector containing this Index 1155 // requires one operation, except that vperm can handle two input 1156 // registers first time for each dst vector. 1157 unsigned NumSrcVecs = ValueVecs[Index].count(); 1158 unsigned NumDstVecs = ceil(VF * getScalarSizeInBits(VecTy), 128U); 1159 assert (NumSrcVecs >= NumDstVecs && "Expected at least as many sources"); 1160 NumPermutes += std::max(1U, NumSrcVecs - NumDstVecs); 1161 } 1162 } else { 1163 // Estimate the permutes for each stored vector as the smaller of the 1164 // number of elements and the number of source vectors. Subtract one per 1165 // dst vector for vperm (S.A.). 1166 unsigned NumSrcVecs = std::min(NumEltsPerVecReg, Factor); 1167 unsigned NumDstVecs = NumVectorMemOps; 1168 assert (NumSrcVecs > 1 && "Expected at least two source vectors."); 1169 NumPermutes += (NumDstVecs * NumSrcVecs) - NumDstVecs; 1170 } 1171 1172 // Cost of load/store operations and the permutations needed. 1173 return NumVectorMemOps + NumPermutes; 1174 } 1175 1176 static int getVectorIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy) { 1177 if (RetTy->isVectorTy() && ID == Intrinsic::bswap) 1178 return getNumVectorRegs(RetTy); // VPERM 1179 return -1; 1180 } 1181 1182 int SystemZTTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, 1183 TTI::TargetCostKind CostKind) { 1184 int Cost = getVectorIntrinsicInstrCost(ICA.getID(), ICA.getReturnType()); 1185 if (Cost != -1) 1186 return Cost; 1187 return BaseT::getIntrinsicInstrCost(ICA, CostKind); 1188 } 1189