1 //===- llvm/Analysis/TargetTransformInfo.cpp ------------------------------===// 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 #include "llvm/Analysis/TargetTransformInfo.h" 10 #include "llvm/Analysis/CFG.h" 11 #include "llvm/Analysis/LoopIterator.h" 12 #include "llvm/Analysis/TargetTransformInfoImpl.h" 13 #include "llvm/IR/CFG.h" 14 #include "llvm/IR/DataLayout.h" 15 #include "llvm/IR/Instruction.h" 16 #include "llvm/IR/Instructions.h" 17 #include "llvm/IR/IntrinsicInst.h" 18 #include "llvm/IR/Module.h" 19 #include "llvm/IR/Operator.h" 20 #include "llvm/IR/PatternMatch.h" 21 #include "llvm/InitializePasses.h" 22 #include "llvm/Support/CommandLine.h" 23 #include "llvm/Support/ErrorHandling.h" 24 #include <utility> 25 26 using namespace llvm; 27 using namespace PatternMatch; 28 29 #define DEBUG_TYPE "tti" 30 31 static cl::opt<bool> EnableReduxCost("costmodel-reduxcost", cl::init(false), 32 cl::Hidden, 33 cl::desc("Recognize reduction patterns.")); 34 35 namespace { 36 /// No-op implementation of the TTI interface using the utility base 37 /// classes. 38 /// 39 /// This is used when no target specific information is available. 40 struct NoTTIImpl : TargetTransformInfoImplCRTPBase<NoTTIImpl> { 41 explicit NoTTIImpl(const DataLayout &DL) 42 : TargetTransformInfoImplCRTPBase<NoTTIImpl>(DL) {} 43 }; 44 } // namespace 45 46 bool HardwareLoopInfo::canAnalyze(LoopInfo &LI) { 47 // If the loop has irreducible control flow, it can not be converted to 48 // Hardware loop. 49 LoopBlocksRPO RPOT(L); 50 RPOT.perform(&LI); 51 if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI)) 52 return false; 53 return true; 54 } 55 56 bool HardwareLoopInfo::isHardwareLoopCandidate(ScalarEvolution &SE, 57 LoopInfo &LI, DominatorTree &DT, 58 bool ForceNestedLoop, 59 bool ForceHardwareLoopPHI) { 60 SmallVector<BasicBlock *, 4> ExitingBlocks; 61 L->getExitingBlocks(ExitingBlocks); 62 63 for (BasicBlock *BB : ExitingBlocks) { 64 // If we pass the updated counter back through a phi, we need to know 65 // which latch the updated value will be coming from. 66 if (!L->isLoopLatch(BB)) { 67 if (ForceHardwareLoopPHI || CounterInReg) 68 continue; 69 } 70 71 const SCEV *EC = SE.getExitCount(L, BB); 72 if (isa<SCEVCouldNotCompute>(EC)) 73 continue; 74 if (const SCEVConstant *ConstEC = dyn_cast<SCEVConstant>(EC)) { 75 if (ConstEC->getValue()->isZero()) 76 continue; 77 } else if (!SE.isLoopInvariant(EC, L)) 78 continue; 79 80 if (SE.getTypeSizeInBits(EC->getType()) > CountType->getBitWidth()) 81 continue; 82 83 // If this exiting block is contained in a nested loop, it is not eligible 84 // for insertion of the branch-and-decrement since the inner loop would 85 // end up messing up the value in the CTR. 86 if (!IsNestingLegal && LI.getLoopFor(BB) != L && !ForceNestedLoop) 87 continue; 88 89 // We now have a loop-invariant count of loop iterations (which is not the 90 // constant zero) for which we know that this loop will not exit via this 91 // existing block. 92 93 // We need to make sure that this block will run on every loop iteration. 94 // For this to be true, we must dominate all blocks with backedges. Such 95 // blocks are in-loop predecessors to the header block. 96 bool NotAlways = false; 97 for (BasicBlock *Pred : predecessors(L->getHeader())) { 98 if (!L->contains(Pred)) 99 continue; 100 101 if (!DT.dominates(BB, Pred)) { 102 NotAlways = true; 103 break; 104 } 105 } 106 107 if (NotAlways) 108 continue; 109 110 // Make sure this blocks ends with a conditional branch. 111 Instruction *TI = BB->getTerminator(); 112 if (!TI) 113 continue; 114 115 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 116 if (!BI->isConditional()) 117 continue; 118 119 ExitBranch = BI; 120 } else 121 continue; 122 123 // Note that this block may not be the loop latch block, even if the loop 124 // has a latch block. 125 ExitBlock = BB; 126 ExitCount = EC; 127 break; 128 } 129 130 if (!ExitBlock) 131 return false; 132 return true; 133 } 134 135 TargetTransformInfo::TargetTransformInfo(const DataLayout &DL) 136 : TTIImpl(new Model<NoTTIImpl>(NoTTIImpl(DL))) {} 137 138 TargetTransformInfo::~TargetTransformInfo() {} 139 140 TargetTransformInfo::TargetTransformInfo(TargetTransformInfo &&Arg) 141 : TTIImpl(std::move(Arg.TTIImpl)) {} 142 143 TargetTransformInfo &TargetTransformInfo::operator=(TargetTransformInfo &&RHS) { 144 TTIImpl = std::move(RHS.TTIImpl); 145 return *this; 146 } 147 148 unsigned TargetTransformInfo::getInliningThresholdMultiplier() const { 149 return TTIImpl->getInliningThresholdMultiplier(); 150 } 151 152 int TargetTransformInfo::getInlinerVectorBonusPercent() const { 153 return TTIImpl->getInlinerVectorBonusPercent(); 154 } 155 156 int TargetTransformInfo::getGEPCost(Type *PointeeType, const Value *Ptr, 157 ArrayRef<const Value *> Operands) const { 158 return TTIImpl->getGEPCost(PointeeType, Ptr, Operands); 159 } 160 161 int TargetTransformInfo::getExtCost(const Instruction *I, 162 const Value *Src) const { 163 return TTIImpl->getExtCost(I, Src); 164 } 165 166 int TargetTransformInfo::getIntrinsicCost(Intrinsic::ID IID, Type *RetTy, 167 ArrayRef<const Value *> Arguments, 168 const User *U) const { 169 int Cost = TTIImpl->getIntrinsicCost(IID, RetTy, Arguments, U); 170 assert(Cost >= 0 && "TTI should not produce negative costs!"); 171 return Cost; 172 } 173 174 unsigned TargetTransformInfo::getEstimatedNumberOfCaseClusters( 175 const SwitchInst &SI, unsigned &JTSize, ProfileSummaryInfo *PSI, 176 BlockFrequencyInfo *BFI) const { 177 return TTIImpl->getEstimatedNumberOfCaseClusters(SI, JTSize, PSI, BFI); 178 } 179 180 int TargetTransformInfo::getUserCost(const User *U, 181 ArrayRef<const Value *> Operands) const { 182 int Cost = TTIImpl->getUserCost(U, Operands); 183 assert(Cost >= 0 && "TTI should not produce negative costs!"); 184 return Cost; 185 } 186 187 bool TargetTransformInfo::hasBranchDivergence() const { 188 return TTIImpl->hasBranchDivergence(); 189 } 190 191 bool TargetTransformInfo::useGPUDivergenceAnalysis() const { 192 return TTIImpl->useGPUDivergenceAnalysis(); 193 } 194 195 bool TargetTransformInfo::isSourceOfDivergence(const Value *V) const { 196 return TTIImpl->isSourceOfDivergence(V); 197 } 198 199 bool llvm::TargetTransformInfo::isAlwaysUniform(const Value *V) const { 200 return TTIImpl->isAlwaysUniform(V); 201 } 202 203 unsigned TargetTransformInfo::getFlatAddressSpace() const { 204 return TTIImpl->getFlatAddressSpace(); 205 } 206 207 bool TargetTransformInfo::collectFlatAddressOperands( 208 SmallVectorImpl<int> &OpIndexes, Intrinsic::ID IID) const { 209 return TTIImpl->collectFlatAddressOperands(OpIndexes, IID); 210 } 211 212 bool TargetTransformInfo::rewriteIntrinsicWithAddressSpace(IntrinsicInst *II, 213 Value *OldV, 214 Value *NewV) const { 215 return TTIImpl->rewriteIntrinsicWithAddressSpace(II, OldV, NewV); 216 } 217 218 bool TargetTransformInfo::isLoweredToCall(const Function *F) const { 219 return TTIImpl->isLoweredToCall(F); 220 } 221 222 bool TargetTransformInfo::isHardwareLoopProfitable( 223 Loop *L, ScalarEvolution &SE, AssumptionCache &AC, 224 TargetLibraryInfo *LibInfo, HardwareLoopInfo &HWLoopInfo) const { 225 return TTIImpl->isHardwareLoopProfitable(L, SE, AC, LibInfo, HWLoopInfo); 226 } 227 228 bool TargetTransformInfo::preferPredicateOverEpilogue( 229 Loop *L, LoopInfo *LI, ScalarEvolution &SE, AssumptionCache &AC, 230 TargetLibraryInfo *TLI, DominatorTree *DT, 231 const LoopAccessInfo *LAI) const { 232 return TTIImpl->preferPredicateOverEpilogue(L, LI, SE, AC, TLI, DT, LAI); 233 } 234 235 void TargetTransformInfo::getUnrollingPreferences( 236 Loop *L, ScalarEvolution &SE, UnrollingPreferences &UP) const { 237 return TTIImpl->getUnrollingPreferences(L, SE, UP); 238 } 239 240 bool TargetTransformInfo::isLegalAddImmediate(int64_t Imm) const { 241 return TTIImpl->isLegalAddImmediate(Imm); 242 } 243 244 bool TargetTransformInfo::isLegalICmpImmediate(int64_t Imm) const { 245 return TTIImpl->isLegalICmpImmediate(Imm); 246 } 247 248 bool TargetTransformInfo::isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, 249 int64_t BaseOffset, 250 bool HasBaseReg, int64_t Scale, 251 unsigned AddrSpace, 252 Instruction *I) const { 253 return TTIImpl->isLegalAddressingMode(Ty, BaseGV, BaseOffset, HasBaseReg, 254 Scale, AddrSpace, I); 255 } 256 257 bool TargetTransformInfo::isLSRCostLess(LSRCost &C1, LSRCost &C2) const { 258 return TTIImpl->isLSRCostLess(C1, C2); 259 } 260 261 bool TargetTransformInfo::canMacroFuseCmp() const { 262 return TTIImpl->canMacroFuseCmp(); 263 } 264 265 bool TargetTransformInfo::canSaveCmp(Loop *L, BranchInst **BI, 266 ScalarEvolution *SE, LoopInfo *LI, 267 DominatorTree *DT, AssumptionCache *AC, 268 TargetLibraryInfo *LibInfo) const { 269 return TTIImpl->canSaveCmp(L, BI, SE, LI, DT, AC, LibInfo); 270 } 271 272 bool TargetTransformInfo::shouldFavorPostInc() const { 273 return TTIImpl->shouldFavorPostInc(); 274 } 275 276 bool TargetTransformInfo::shouldFavorBackedgeIndex(const Loop *L) const { 277 return TTIImpl->shouldFavorBackedgeIndex(L); 278 } 279 280 bool TargetTransformInfo::isLegalMaskedStore(Type *DataType, 281 MaybeAlign Alignment) const { 282 return TTIImpl->isLegalMaskedStore(DataType, Alignment); 283 } 284 285 bool TargetTransformInfo::isLegalMaskedLoad(Type *DataType, 286 MaybeAlign Alignment) const { 287 return TTIImpl->isLegalMaskedLoad(DataType, Alignment); 288 } 289 290 bool TargetTransformInfo::isLegalNTStore(Type *DataType, 291 Align Alignment) const { 292 return TTIImpl->isLegalNTStore(DataType, Alignment); 293 } 294 295 bool TargetTransformInfo::isLegalNTLoad(Type *DataType, Align Alignment) const { 296 return TTIImpl->isLegalNTLoad(DataType, Alignment); 297 } 298 299 bool TargetTransformInfo::isLegalMaskedGather(Type *DataType, 300 MaybeAlign Alignment) const { 301 return TTIImpl->isLegalMaskedGather(DataType, Alignment); 302 } 303 304 bool TargetTransformInfo::isLegalMaskedScatter(Type *DataType, 305 MaybeAlign Alignment) const { 306 return TTIImpl->isLegalMaskedScatter(DataType, Alignment); 307 } 308 309 bool TargetTransformInfo::isLegalMaskedCompressStore(Type *DataType) const { 310 return TTIImpl->isLegalMaskedCompressStore(DataType); 311 } 312 313 bool TargetTransformInfo::isLegalMaskedExpandLoad(Type *DataType) const { 314 return TTIImpl->isLegalMaskedExpandLoad(DataType); 315 } 316 317 bool TargetTransformInfo::hasDivRemOp(Type *DataType, bool IsSigned) const { 318 return TTIImpl->hasDivRemOp(DataType, IsSigned); 319 } 320 321 bool TargetTransformInfo::hasVolatileVariant(Instruction *I, 322 unsigned AddrSpace) const { 323 return TTIImpl->hasVolatileVariant(I, AddrSpace); 324 } 325 326 bool TargetTransformInfo::prefersVectorizedAddressing() const { 327 return TTIImpl->prefersVectorizedAddressing(); 328 } 329 330 int TargetTransformInfo::getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, 331 int64_t BaseOffset, 332 bool HasBaseReg, int64_t Scale, 333 unsigned AddrSpace) const { 334 int Cost = TTIImpl->getScalingFactorCost(Ty, BaseGV, BaseOffset, HasBaseReg, 335 Scale, AddrSpace); 336 assert(Cost >= 0 && "TTI should not produce negative costs!"); 337 return Cost; 338 } 339 340 bool TargetTransformInfo::LSRWithInstrQueries() const { 341 return TTIImpl->LSRWithInstrQueries(); 342 } 343 344 bool TargetTransformInfo::isTruncateFree(Type *Ty1, Type *Ty2) const { 345 return TTIImpl->isTruncateFree(Ty1, Ty2); 346 } 347 348 bool TargetTransformInfo::isProfitableToHoist(Instruction *I) const { 349 return TTIImpl->isProfitableToHoist(I); 350 } 351 352 bool TargetTransformInfo::useAA() const { return TTIImpl->useAA(); } 353 354 bool TargetTransformInfo::isTypeLegal(Type *Ty) const { 355 return TTIImpl->isTypeLegal(Ty); 356 } 357 358 bool TargetTransformInfo::shouldBuildLookupTables() const { 359 return TTIImpl->shouldBuildLookupTables(); 360 } 361 bool TargetTransformInfo::shouldBuildLookupTablesForConstant( 362 Constant *C) const { 363 return TTIImpl->shouldBuildLookupTablesForConstant(C); 364 } 365 366 bool TargetTransformInfo::useColdCCForColdCall(Function &F) const { 367 return TTIImpl->useColdCCForColdCall(F); 368 } 369 370 unsigned TargetTransformInfo::getScalarizationOverhead(Type *Ty, bool Insert, 371 bool Extract) const { 372 return TTIImpl->getScalarizationOverhead(Ty, Insert, Extract); 373 } 374 375 unsigned TargetTransformInfo::getOperandsScalarizationOverhead( 376 ArrayRef<const Value *> Args, unsigned VF) const { 377 return TTIImpl->getOperandsScalarizationOverhead(Args, VF); 378 } 379 380 bool TargetTransformInfo::supportsEfficientVectorElementLoadStore() const { 381 return TTIImpl->supportsEfficientVectorElementLoadStore(); 382 } 383 384 bool TargetTransformInfo::enableAggressiveInterleaving( 385 bool LoopHasReductions) const { 386 return TTIImpl->enableAggressiveInterleaving(LoopHasReductions); 387 } 388 389 TargetTransformInfo::MemCmpExpansionOptions 390 TargetTransformInfo::enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const { 391 return TTIImpl->enableMemCmpExpansion(OptSize, IsZeroCmp); 392 } 393 394 bool TargetTransformInfo::enableInterleavedAccessVectorization() const { 395 return TTIImpl->enableInterleavedAccessVectorization(); 396 } 397 398 bool TargetTransformInfo::enableMaskedInterleavedAccessVectorization() const { 399 return TTIImpl->enableMaskedInterleavedAccessVectorization(); 400 } 401 402 bool TargetTransformInfo::isFPVectorizationPotentiallyUnsafe() const { 403 return TTIImpl->isFPVectorizationPotentiallyUnsafe(); 404 } 405 406 bool TargetTransformInfo::allowsMisalignedMemoryAccesses(LLVMContext &Context, 407 unsigned BitWidth, 408 unsigned AddressSpace, 409 unsigned Alignment, 410 bool *Fast) const { 411 return TTIImpl->allowsMisalignedMemoryAccesses(Context, BitWidth, 412 AddressSpace, Alignment, Fast); 413 } 414 415 TargetTransformInfo::PopcntSupportKind 416 TargetTransformInfo::getPopcntSupport(unsigned IntTyWidthInBit) const { 417 return TTIImpl->getPopcntSupport(IntTyWidthInBit); 418 } 419 420 bool TargetTransformInfo::haveFastSqrt(Type *Ty) const { 421 return TTIImpl->haveFastSqrt(Ty); 422 } 423 424 bool TargetTransformInfo::isFCmpOrdCheaperThanFCmpZero(Type *Ty) const { 425 return TTIImpl->isFCmpOrdCheaperThanFCmpZero(Ty); 426 } 427 428 int TargetTransformInfo::getFPOpCost(Type *Ty) const { 429 int Cost = TTIImpl->getFPOpCost(Ty); 430 assert(Cost >= 0 && "TTI should not produce negative costs!"); 431 return Cost; 432 } 433 434 int TargetTransformInfo::getIntImmCodeSizeCost(unsigned Opcode, unsigned Idx, 435 const APInt &Imm, 436 Type *Ty) const { 437 int Cost = TTIImpl->getIntImmCodeSizeCost(Opcode, Idx, Imm, Ty); 438 assert(Cost >= 0 && "TTI should not produce negative costs!"); 439 return Cost; 440 } 441 442 int TargetTransformInfo::getIntImmCost(const APInt &Imm, Type *Ty) const { 443 int Cost = TTIImpl->getIntImmCost(Imm, Ty); 444 assert(Cost >= 0 && "TTI should not produce negative costs!"); 445 return Cost; 446 } 447 448 int TargetTransformInfo::getIntImmCostInst(unsigned Opcode, unsigned Idx, 449 const APInt &Imm, Type *Ty) const { 450 int Cost = TTIImpl->getIntImmCostInst(Opcode, Idx, Imm, Ty); 451 assert(Cost >= 0 && "TTI should not produce negative costs!"); 452 return Cost; 453 } 454 455 int TargetTransformInfo::getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx, 456 const APInt &Imm, Type *Ty) const { 457 int Cost = TTIImpl->getIntImmCostIntrin(IID, Idx, Imm, Ty); 458 assert(Cost >= 0 && "TTI should not produce negative costs!"); 459 return Cost; 460 } 461 462 unsigned TargetTransformInfo::getNumberOfRegisters(unsigned ClassID) const { 463 return TTIImpl->getNumberOfRegisters(ClassID); 464 } 465 466 unsigned TargetTransformInfo::getRegisterClassForType(bool Vector, 467 Type *Ty) const { 468 return TTIImpl->getRegisterClassForType(Vector, Ty); 469 } 470 471 const char *TargetTransformInfo::getRegisterClassName(unsigned ClassID) const { 472 return TTIImpl->getRegisterClassName(ClassID); 473 } 474 475 unsigned TargetTransformInfo::getRegisterBitWidth(bool Vector) const { 476 return TTIImpl->getRegisterBitWidth(Vector); 477 } 478 479 unsigned TargetTransformInfo::getMinVectorRegisterBitWidth() const { 480 return TTIImpl->getMinVectorRegisterBitWidth(); 481 } 482 483 bool TargetTransformInfo::shouldMaximizeVectorBandwidth(bool OptSize) const { 484 return TTIImpl->shouldMaximizeVectorBandwidth(OptSize); 485 } 486 487 unsigned TargetTransformInfo::getMinimumVF(unsigned ElemWidth) const { 488 return TTIImpl->getMinimumVF(ElemWidth); 489 } 490 491 bool TargetTransformInfo::shouldConsiderAddressTypePromotion( 492 const Instruction &I, bool &AllowPromotionWithoutCommonHeader) const { 493 return TTIImpl->shouldConsiderAddressTypePromotion( 494 I, AllowPromotionWithoutCommonHeader); 495 } 496 497 unsigned TargetTransformInfo::getCacheLineSize() const { 498 return TTIImpl->getCacheLineSize(); 499 } 500 501 llvm::Optional<unsigned> 502 TargetTransformInfo::getCacheSize(CacheLevel Level) const { 503 return TTIImpl->getCacheSize(Level); 504 } 505 506 llvm::Optional<unsigned> 507 TargetTransformInfo::getCacheAssociativity(CacheLevel Level) const { 508 return TTIImpl->getCacheAssociativity(Level); 509 } 510 511 unsigned TargetTransformInfo::getPrefetchDistance() const { 512 return TTIImpl->getPrefetchDistance(); 513 } 514 515 unsigned TargetTransformInfo::getMinPrefetchStride( 516 unsigned NumMemAccesses, unsigned NumStridedMemAccesses, 517 unsigned NumPrefetches, bool HasCall) const { 518 return TTIImpl->getMinPrefetchStride(NumMemAccesses, NumStridedMemAccesses, 519 NumPrefetches, HasCall); 520 } 521 522 unsigned TargetTransformInfo::getMaxPrefetchIterationsAhead() const { 523 return TTIImpl->getMaxPrefetchIterationsAhead(); 524 } 525 526 bool TargetTransformInfo::enableWritePrefetching() const { 527 return TTIImpl->enableWritePrefetching(); 528 } 529 530 unsigned TargetTransformInfo::getMaxInterleaveFactor(unsigned VF) const { 531 return TTIImpl->getMaxInterleaveFactor(VF); 532 } 533 534 TargetTransformInfo::OperandValueKind 535 TargetTransformInfo::getOperandInfo(Value *V, OperandValueProperties &OpProps) { 536 OperandValueKind OpInfo = OK_AnyValue; 537 OpProps = OP_None; 538 539 if (auto *CI = dyn_cast<ConstantInt>(V)) { 540 if (CI->getValue().isPowerOf2()) 541 OpProps = OP_PowerOf2; 542 return OK_UniformConstantValue; 543 } 544 545 // A broadcast shuffle creates a uniform value. 546 // TODO: Add support for non-zero index broadcasts. 547 // TODO: Add support for different source vector width. 548 if (auto *ShuffleInst = dyn_cast<ShuffleVectorInst>(V)) 549 if (ShuffleInst->isZeroEltSplat()) 550 OpInfo = OK_UniformValue; 551 552 const Value *Splat = getSplatValue(V); 553 554 // Check for a splat of a constant or for a non uniform vector of constants 555 // and check if the constant(s) are all powers of two. 556 if (isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) { 557 OpInfo = OK_NonUniformConstantValue; 558 if (Splat) { 559 OpInfo = OK_UniformConstantValue; 560 if (auto *CI = dyn_cast<ConstantInt>(Splat)) 561 if (CI->getValue().isPowerOf2()) 562 OpProps = OP_PowerOf2; 563 } else if (auto *CDS = dyn_cast<ConstantDataSequential>(V)) { 564 OpProps = OP_PowerOf2; 565 for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I) { 566 if (auto *CI = dyn_cast<ConstantInt>(CDS->getElementAsConstant(I))) 567 if (CI->getValue().isPowerOf2()) 568 continue; 569 OpProps = OP_None; 570 break; 571 } 572 } 573 } 574 575 // Check for a splat of a uniform value. This is not loop aware, so return 576 // true only for the obviously uniform cases (argument, globalvalue) 577 if (Splat && (isa<Argument>(Splat) || isa<GlobalValue>(Splat))) 578 OpInfo = OK_UniformValue; 579 580 return OpInfo; 581 } 582 583 int TargetTransformInfo::getArithmeticInstrCost( 584 unsigned Opcode, Type *Ty, OperandValueKind Opd1Info, 585 OperandValueKind Opd2Info, OperandValueProperties Opd1PropInfo, 586 OperandValueProperties Opd2PropInfo, ArrayRef<const Value *> Args, 587 const Instruction *CxtI) const { 588 int Cost = TTIImpl->getArithmeticInstrCost( 589 Opcode, Ty, Opd1Info, Opd2Info, Opd1PropInfo, Opd2PropInfo, Args, CxtI); 590 assert(Cost >= 0 && "TTI should not produce negative costs!"); 591 return Cost; 592 } 593 594 int TargetTransformInfo::getShuffleCost(ShuffleKind Kind, VectorType *Ty, 595 int Index, VectorType *SubTp) const { 596 int Cost = TTIImpl->getShuffleCost(Kind, Ty, Index, SubTp); 597 assert(Cost >= 0 && "TTI should not produce negative costs!"); 598 return Cost; 599 } 600 601 int TargetTransformInfo::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, 602 const Instruction *I) const { 603 assert((I == nullptr || I->getOpcode() == Opcode) && 604 "Opcode should reflect passed instruction."); 605 int Cost = TTIImpl->getCastInstrCost(Opcode, Dst, Src, I); 606 assert(Cost >= 0 && "TTI should not produce negative costs!"); 607 return Cost; 608 } 609 610 int TargetTransformInfo::getExtractWithExtendCost(unsigned Opcode, Type *Dst, 611 VectorType *VecTy, 612 unsigned Index) const { 613 int Cost = TTIImpl->getExtractWithExtendCost(Opcode, Dst, VecTy, Index); 614 assert(Cost >= 0 && "TTI should not produce negative costs!"); 615 return Cost; 616 } 617 618 int TargetTransformInfo::getCFInstrCost(unsigned Opcode) const { 619 int Cost = TTIImpl->getCFInstrCost(Opcode); 620 assert(Cost >= 0 && "TTI should not produce negative costs!"); 621 return Cost; 622 } 623 624 int TargetTransformInfo::getCmpSelInstrCost(unsigned Opcode, Type *ValTy, 625 Type *CondTy, 626 const Instruction *I) const { 627 assert((I == nullptr || I->getOpcode() == Opcode) && 628 "Opcode should reflect passed instruction."); 629 int Cost = TTIImpl->getCmpSelInstrCost(Opcode, ValTy, CondTy, I); 630 assert(Cost >= 0 && "TTI should not produce negative costs!"); 631 return Cost; 632 } 633 634 int TargetTransformInfo::getVectorInstrCost(unsigned Opcode, Type *Val, 635 unsigned Index) const { 636 int Cost = TTIImpl->getVectorInstrCost(Opcode, Val, Index); 637 assert(Cost >= 0 && "TTI should not produce negative costs!"); 638 return Cost; 639 } 640 641 int TargetTransformInfo::getMemoryOpCost(unsigned Opcode, Type *Src, 642 MaybeAlign Alignment, 643 unsigned AddressSpace, 644 const Instruction *I) const { 645 assert((I == nullptr || I->getOpcode() == Opcode) && 646 "Opcode should reflect passed instruction."); 647 int Cost = TTIImpl->getMemoryOpCost(Opcode, Src, Alignment, AddressSpace, I); 648 assert(Cost >= 0 && "TTI should not produce negative costs!"); 649 return Cost; 650 } 651 652 int TargetTransformInfo::getMaskedMemoryOpCost(unsigned Opcode, Type *Src, 653 unsigned Alignment, 654 unsigned AddressSpace) const { 655 int Cost = 656 TTIImpl->getMaskedMemoryOpCost(Opcode, Src, Alignment, AddressSpace); 657 assert(Cost >= 0 && "TTI should not produce negative costs!"); 658 return Cost; 659 } 660 661 int TargetTransformInfo::getGatherScatterOpCost(unsigned Opcode, Type *DataTy, 662 Value *Ptr, bool VariableMask, 663 unsigned Alignment, 664 const Instruction *I) const { 665 int Cost = TTIImpl->getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask, 666 Alignment, I); 667 assert(Cost >= 0 && "TTI should not produce negative costs!"); 668 return Cost; 669 } 670 671 int TargetTransformInfo::getInterleavedMemoryOpCost( 672 unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices, 673 unsigned Alignment, unsigned AddressSpace, bool UseMaskForCond, 674 bool UseMaskForGaps) const { 675 int Cost = TTIImpl->getInterleavedMemoryOpCost( 676 Opcode, VecTy, Factor, Indices, Alignment, AddressSpace, UseMaskForCond, 677 UseMaskForGaps); 678 assert(Cost >= 0 && "TTI should not produce negative costs!"); 679 return Cost; 680 } 681 682 int TargetTransformInfo::getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy, 683 ArrayRef<Type *> Tys, 684 FastMathFlags FMF, 685 unsigned ScalarizationCostPassed, 686 const Instruction *I) const { 687 int Cost = TTIImpl->getIntrinsicInstrCost(ID, RetTy, Tys, FMF, 688 ScalarizationCostPassed, I); 689 assert(Cost >= 0 && "TTI should not produce negative costs!"); 690 return Cost; 691 } 692 693 int TargetTransformInfo::getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy, 694 ArrayRef<Value *> Args, 695 FastMathFlags FMF, unsigned VF, 696 const Instruction *I) const { 697 int Cost = TTIImpl->getIntrinsicInstrCost(ID, RetTy, Args, FMF, VF, I); 698 assert(Cost >= 0 && "TTI should not produce negative costs!"); 699 return Cost; 700 } 701 702 int TargetTransformInfo::getCallInstrCost(Function *F, Type *RetTy, 703 ArrayRef<Type *> Tys) const { 704 int Cost = TTIImpl->getCallInstrCost(F, RetTy, Tys); 705 assert(Cost >= 0 && "TTI should not produce negative costs!"); 706 return Cost; 707 } 708 709 unsigned TargetTransformInfo::getNumberOfParts(Type *Tp) const { 710 return TTIImpl->getNumberOfParts(Tp); 711 } 712 713 int TargetTransformInfo::getAddressComputationCost(Type *Tp, 714 ScalarEvolution *SE, 715 const SCEV *Ptr) const { 716 int Cost = TTIImpl->getAddressComputationCost(Tp, SE, Ptr); 717 assert(Cost >= 0 && "TTI should not produce negative costs!"); 718 return Cost; 719 } 720 721 int TargetTransformInfo::getMemcpyCost(const Instruction *I) const { 722 int Cost = TTIImpl->getMemcpyCost(I); 723 assert(Cost >= 0 && "TTI should not produce negative costs!"); 724 return Cost; 725 } 726 727 int TargetTransformInfo::getArithmeticReductionCost(unsigned Opcode, 728 VectorType *Ty, 729 bool IsPairwiseForm) const { 730 int Cost = TTIImpl->getArithmeticReductionCost(Opcode, Ty, IsPairwiseForm); 731 assert(Cost >= 0 && "TTI should not produce negative costs!"); 732 return Cost; 733 } 734 735 int TargetTransformInfo::getMinMaxReductionCost(VectorType *Ty, 736 VectorType *CondTy, 737 bool IsPairwiseForm, 738 bool IsUnsigned) const { 739 int Cost = 740 TTIImpl->getMinMaxReductionCost(Ty, CondTy, IsPairwiseForm, IsUnsigned); 741 assert(Cost >= 0 && "TTI should not produce negative costs!"); 742 return Cost; 743 } 744 745 unsigned 746 TargetTransformInfo::getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) const { 747 return TTIImpl->getCostOfKeepingLiveOverCall(Tys); 748 } 749 750 bool TargetTransformInfo::getTgtMemIntrinsic(IntrinsicInst *Inst, 751 MemIntrinsicInfo &Info) const { 752 return TTIImpl->getTgtMemIntrinsic(Inst, Info); 753 } 754 755 unsigned TargetTransformInfo::getAtomicMemIntrinsicMaxElementSize() const { 756 return TTIImpl->getAtomicMemIntrinsicMaxElementSize(); 757 } 758 759 Value *TargetTransformInfo::getOrCreateResultFromMemIntrinsic( 760 IntrinsicInst *Inst, Type *ExpectedType) const { 761 return TTIImpl->getOrCreateResultFromMemIntrinsic(Inst, ExpectedType); 762 } 763 764 Type *TargetTransformInfo::getMemcpyLoopLoweringType( 765 LLVMContext &Context, Value *Length, unsigned SrcAddrSpace, 766 unsigned DestAddrSpace, unsigned SrcAlign, unsigned DestAlign) const { 767 return TTIImpl->getMemcpyLoopLoweringType(Context, Length, SrcAddrSpace, 768 DestAddrSpace, SrcAlign, DestAlign); 769 } 770 771 void TargetTransformInfo::getMemcpyLoopResidualLoweringType( 772 SmallVectorImpl<Type *> &OpsOut, LLVMContext &Context, 773 unsigned RemainingBytes, unsigned SrcAddrSpace, unsigned DestAddrSpace, 774 unsigned SrcAlign, unsigned DestAlign) const { 775 TTIImpl->getMemcpyLoopResidualLoweringType(OpsOut, Context, RemainingBytes, 776 SrcAddrSpace, DestAddrSpace, 777 SrcAlign, DestAlign); 778 } 779 780 bool TargetTransformInfo::areInlineCompatible(const Function *Caller, 781 const Function *Callee) const { 782 return TTIImpl->areInlineCompatible(Caller, Callee); 783 } 784 785 bool TargetTransformInfo::areFunctionArgsABICompatible( 786 const Function *Caller, const Function *Callee, 787 SmallPtrSetImpl<Argument *> &Args) const { 788 return TTIImpl->areFunctionArgsABICompatible(Caller, Callee, Args); 789 } 790 791 bool TargetTransformInfo::isIndexedLoadLegal(MemIndexedMode Mode, 792 Type *Ty) const { 793 return TTIImpl->isIndexedLoadLegal(Mode, Ty); 794 } 795 796 bool TargetTransformInfo::isIndexedStoreLegal(MemIndexedMode Mode, 797 Type *Ty) const { 798 return TTIImpl->isIndexedStoreLegal(Mode, Ty); 799 } 800 801 unsigned TargetTransformInfo::getLoadStoreVecRegBitWidth(unsigned AS) const { 802 return TTIImpl->getLoadStoreVecRegBitWidth(AS); 803 } 804 805 bool TargetTransformInfo::isLegalToVectorizeLoad(LoadInst *LI) const { 806 return TTIImpl->isLegalToVectorizeLoad(LI); 807 } 808 809 bool TargetTransformInfo::isLegalToVectorizeStore(StoreInst *SI) const { 810 return TTIImpl->isLegalToVectorizeStore(SI); 811 } 812 813 bool TargetTransformInfo::isLegalToVectorizeLoadChain( 814 unsigned ChainSizeInBytes, unsigned Alignment, unsigned AddrSpace) const { 815 return TTIImpl->isLegalToVectorizeLoadChain(ChainSizeInBytes, Alignment, 816 AddrSpace); 817 } 818 819 bool TargetTransformInfo::isLegalToVectorizeStoreChain( 820 unsigned ChainSizeInBytes, unsigned Alignment, unsigned AddrSpace) const { 821 return TTIImpl->isLegalToVectorizeStoreChain(ChainSizeInBytes, Alignment, 822 AddrSpace); 823 } 824 825 unsigned TargetTransformInfo::getLoadVectorFactor(unsigned VF, 826 unsigned LoadSize, 827 unsigned ChainSizeInBytes, 828 VectorType *VecTy) const { 829 return TTIImpl->getLoadVectorFactor(VF, LoadSize, ChainSizeInBytes, VecTy); 830 } 831 832 unsigned TargetTransformInfo::getStoreVectorFactor(unsigned VF, 833 unsigned StoreSize, 834 unsigned ChainSizeInBytes, 835 VectorType *VecTy) const { 836 return TTIImpl->getStoreVectorFactor(VF, StoreSize, ChainSizeInBytes, VecTy); 837 } 838 839 bool TargetTransformInfo::useReductionIntrinsic(unsigned Opcode, Type *Ty, 840 ReductionFlags Flags) const { 841 return TTIImpl->useReductionIntrinsic(Opcode, Ty, Flags); 842 } 843 844 bool TargetTransformInfo::shouldExpandReduction(const IntrinsicInst *II) const { 845 return TTIImpl->shouldExpandReduction(II); 846 } 847 848 unsigned TargetTransformInfo::getGISelRematGlobalCost() const { 849 return TTIImpl->getGISelRematGlobalCost(); 850 } 851 852 int TargetTransformInfo::getInstructionLatency(const Instruction *I) const { 853 return TTIImpl->getInstructionLatency(I); 854 } 855 856 static bool matchPairwiseShuffleMask(ShuffleVectorInst *SI, bool IsLeft, 857 unsigned Level) { 858 // We don't need a shuffle if we just want to have element 0 in position 0 of 859 // the vector. 860 if (!SI && Level == 0 && IsLeft) 861 return true; 862 else if (!SI) 863 return false; 864 865 SmallVector<int, 32> Mask(SI->getType()->getNumElements(), -1); 866 867 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right) depending on whether 868 // we look at the left or right side. 869 for (unsigned i = 0, e = (1 << Level), val = !IsLeft; i != e; ++i, val += 2) 870 Mask[i] = val; 871 872 ArrayRef<int> ActualMask = SI->getShuffleMask(); 873 return Mask == ActualMask; 874 } 875 876 namespace { 877 /// Kind of the reduction data. 878 enum ReductionKind { 879 RK_None, /// Not a reduction. 880 RK_Arithmetic, /// Binary reduction data. 881 RK_MinMax, /// Min/max reduction data. 882 RK_UnsignedMinMax, /// Unsigned min/max reduction data. 883 }; 884 /// Contains opcode + LHS/RHS parts of the reduction operations. 885 struct ReductionData { 886 ReductionData() = delete; 887 ReductionData(ReductionKind Kind, unsigned Opcode, Value *LHS, Value *RHS) 888 : Opcode(Opcode), LHS(LHS), RHS(RHS), Kind(Kind) { 889 assert(Kind != RK_None && "expected binary or min/max reduction only."); 890 } 891 unsigned Opcode = 0; 892 Value *LHS = nullptr; 893 Value *RHS = nullptr; 894 ReductionKind Kind = RK_None; 895 bool hasSameData(ReductionData &RD) const { 896 return Kind == RD.Kind && Opcode == RD.Opcode; 897 } 898 }; 899 } // namespace 900 901 static Optional<ReductionData> getReductionData(Instruction *I) { 902 Value *L, *R; 903 if (m_BinOp(m_Value(L), m_Value(R)).match(I)) 904 return ReductionData(RK_Arithmetic, I->getOpcode(), L, R); 905 if (auto *SI = dyn_cast<SelectInst>(I)) { 906 if (m_SMin(m_Value(L), m_Value(R)).match(SI) || 907 m_SMax(m_Value(L), m_Value(R)).match(SI) || 908 m_OrdFMin(m_Value(L), m_Value(R)).match(SI) || 909 m_OrdFMax(m_Value(L), m_Value(R)).match(SI) || 910 m_UnordFMin(m_Value(L), m_Value(R)).match(SI) || 911 m_UnordFMax(m_Value(L), m_Value(R)).match(SI)) { 912 auto *CI = cast<CmpInst>(SI->getCondition()); 913 return ReductionData(RK_MinMax, CI->getOpcode(), L, R); 914 } 915 if (m_UMin(m_Value(L), m_Value(R)).match(SI) || 916 m_UMax(m_Value(L), m_Value(R)).match(SI)) { 917 auto *CI = cast<CmpInst>(SI->getCondition()); 918 return ReductionData(RK_UnsignedMinMax, CI->getOpcode(), L, R); 919 } 920 } 921 return llvm::None; 922 } 923 924 static ReductionKind matchPairwiseReductionAtLevel(Instruction *I, 925 unsigned Level, 926 unsigned NumLevels) { 927 // Match one level of pairwise operations. 928 // %rdx.shuf.0.0 = shufflevector <4 x float> %rdx, <4 x float> undef, 929 // <4 x i32> <i32 0, i32 2 , i32 undef, i32 undef> 930 // %rdx.shuf.0.1 = shufflevector <4 x float> %rdx, <4 x float> undef, 931 // <4 x i32> <i32 1, i32 3, i32 undef, i32 undef> 932 // %bin.rdx.0 = fadd <4 x float> %rdx.shuf.0.0, %rdx.shuf.0.1 933 if (!I) 934 return RK_None; 935 936 assert(I->getType()->isVectorTy() && "Expecting a vector type"); 937 938 Optional<ReductionData> RD = getReductionData(I); 939 if (!RD) 940 return RK_None; 941 942 ShuffleVectorInst *LS = dyn_cast<ShuffleVectorInst>(RD->LHS); 943 if (!LS && Level) 944 return RK_None; 945 ShuffleVectorInst *RS = dyn_cast<ShuffleVectorInst>(RD->RHS); 946 if (!RS && Level) 947 return RK_None; 948 949 // On level 0 we can omit one shufflevector instruction. 950 if (!Level && !RS && !LS) 951 return RK_None; 952 953 // Shuffle inputs must match. 954 Value *NextLevelOpL = LS ? LS->getOperand(0) : nullptr; 955 Value *NextLevelOpR = RS ? RS->getOperand(0) : nullptr; 956 Value *NextLevelOp = nullptr; 957 if (NextLevelOpR && NextLevelOpL) { 958 // If we have two shuffles their operands must match. 959 if (NextLevelOpL != NextLevelOpR) 960 return RK_None; 961 962 NextLevelOp = NextLevelOpL; 963 } else if (Level == 0 && (NextLevelOpR || NextLevelOpL)) { 964 // On the first level we can omit the shufflevector <0, undef,...>. So the 965 // input to the other shufflevector <1, undef> must match with one of the 966 // inputs to the current binary operation. 967 // Example: 968 // %NextLevelOpL = shufflevector %R, <1, undef ...> 969 // %BinOp = fadd %NextLevelOpL, %R 970 if (NextLevelOpL && NextLevelOpL != RD->RHS) 971 return RK_None; 972 else if (NextLevelOpR && NextLevelOpR != RD->LHS) 973 return RK_None; 974 975 NextLevelOp = NextLevelOpL ? RD->RHS : RD->LHS; 976 } else 977 return RK_None; 978 979 // Check that the next levels binary operation exists and matches with the 980 // current one. 981 if (Level + 1 != NumLevels) { 982 Optional<ReductionData> NextLevelRD = 983 getReductionData(cast<Instruction>(NextLevelOp)); 984 if (!NextLevelRD || !RD->hasSameData(*NextLevelRD)) 985 return RK_None; 986 } 987 988 // Shuffle mask for pairwise operation must match. 989 if (matchPairwiseShuffleMask(LS, /*IsLeft=*/true, Level)) { 990 if (!matchPairwiseShuffleMask(RS, /*IsLeft=*/false, Level)) 991 return RK_None; 992 } else if (matchPairwiseShuffleMask(RS, /*IsLeft=*/true, Level)) { 993 if (!matchPairwiseShuffleMask(LS, /*IsLeft=*/false, Level)) 994 return RK_None; 995 } else { 996 return RK_None; 997 } 998 999 if (++Level == NumLevels) 1000 return RD->Kind; 1001 1002 // Match next level. 1003 return matchPairwiseReductionAtLevel(cast<Instruction>(NextLevelOp), Level, 1004 NumLevels); 1005 } 1006 1007 static ReductionKind matchPairwiseReduction(const ExtractElementInst *ReduxRoot, 1008 unsigned &Opcode, 1009 VectorType *&Ty) { 1010 if (!EnableReduxCost) 1011 return RK_None; 1012 1013 // Need to extract the first element. 1014 ConstantInt *CI = dyn_cast<ConstantInt>(ReduxRoot->getOperand(1)); 1015 unsigned Idx = ~0u; 1016 if (CI) 1017 Idx = CI->getZExtValue(); 1018 if (Idx != 0) 1019 return RK_None; 1020 1021 auto *RdxStart = dyn_cast<Instruction>(ReduxRoot->getOperand(0)); 1022 if (!RdxStart) 1023 return RK_None; 1024 Optional<ReductionData> RD = getReductionData(RdxStart); 1025 if (!RD) 1026 return RK_None; 1027 1028 auto *VecTy = cast<VectorType>(RdxStart->getType()); 1029 unsigned NumVecElems = VecTy->getNumElements(); 1030 if (!isPowerOf2_32(NumVecElems)) 1031 return RK_None; 1032 1033 // We look for a sequence of shuffle,shuffle,add triples like the following 1034 // that builds a pairwise reduction tree. 1035 // 1036 // (X0, X1, X2, X3) 1037 // (X0 + X1, X2 + X3, undef, undef) 1038 // ((X0 + X1) + (X2 + X3), undef, undef, undef) 1039 // 1040 // %rdx.shuf.0.0 = shufflevector <4 x float> %rdx, <4 x float> undef, 1041 // <4 x i32> <i32 0, i32 2 , i32 undef, i32 undef> 1042 // %rdx.shuf.0.1 = shufflevector <4 x float> %rdx, <4 x float> undef, 1043 // <4 x i32> <i32 1, i32 3, i32 undef, i32 undef> 1044 // %bin.rdx.0 = fadd <4 x float> %rdx.shuf.0.0, %rdx.shuf.0.1 1045 // %rdx.shuf.1.0 = shufflevector <4 x float> %bin.rdx.0, <4 x float> undef, 1046 // <4 x i32> <i32 0, i32 undef, i32 undef, i32 undef> 1047 // %rdx.shuf.1.1 = shufflevector <4 x float> %bin.rdx.0, <4 x float> undef, 1048 // <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef> 1049 // %bin.rdx8 = fadd <4 x float> %rdx.shuf.1.0, %rdx.shuf.1.1 1050 // %r = extractelement <4 x float> %bin.rdx8, i32 0 1051 if (matchPairwiseReductionAtLevel(RdxStart, 0, Log2_32(NumVecElems)) == 1052 RK_None) 1053 return RK_None; 1054 1055 Opcode = RD->Opcode; 1056 Ty = VecTy; 1057 1058 return RD->Kind; 1059 } 1060 1061 static std::pair<Value *, ShuffleVectorInst *> 1062 getShuffleAndOtherOprd(Value *L, Value *R) { 1063 ShuffleVectorInst *S = nullptr; 1064 1065 if ((S = dyn_cast<ShuffleVectorInst>(L))) 1066 return std::make_pair(R, S); 1067 1068 S = dyn_cast<ShuffleVectorInst>(R); 1069 return std::make_pair(L, S); 1070 } 1071 1072 static ReductionKind 1073 matchVectorSplittingReduction(const ExtractElementInst *ReduxRoot, 1074 unsigned &Opcode, VectorType *&Ty) { 1075 if (!EnableReduxCost) 1076 return RK_None; 1077 1078 // Need to extract the first element. 1079 ConstantInt *CI = dyn_cast<ConstantInt>(ReduxRoot->getOperand(1)); 1080 unsigned Idx = ~0u; 1081 if (CI) 1082 Idx = CI->getZExtValue(); 1083 if (Idx != 0) 1084 return RK_None; 1085 1086 auto *RdxStart = dyn_cast<Instruction>(ReduxRoot->getOperand(0)); 1087 if (!RdxStart) 1088 return RK_None; 1089 Optional<ReductionData> RD = getReductionData(RdxStart); 1090 if (!RD) 1091 return RK_None; 1092 1093 auto *VecTy = cast<VectorType>(ReduxRoot->getOperand(0)->getType()); 1094 unsigned NumVecElems = VecTy->getNumElements(); 1095 if (!isPowerOf2_32(NumVecElems)) 1096 return RK_None; 1097 1098 // We look for a sequence of shuffles and adds like the following matching one 1099 // fadd, shuffle vector pair at a time. 1100 // 1101 // %rdx.shuf = shufflevector <4 x float> %rdx, <4 x float> undef, 1102 // <4 x i32> <i32 2, i32 3, i32 undef, i32 undef> 1103 // %bin.rdx = fadd <4 x float> %rdx, %rdx.shuf 1104 // %rdx.shuf7 = shufflevector <4 x float> %bin.rdx, <4 x float> undef, 1105 // <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef> 1106 // %bin.rdx8 = fadd <4 x float> %bin.rdx, %rdx.shuf7 1107 // %r = extractelement <4 x float> %bin.rdx8, i32 0 1108 1109 unsigned MaskStart = 1; 1110 Instruction *RdxOp = RdxStart; 1111 SmallVector<int, 32> ShuffleMask(NumVecElems, 0); 1112 unsigned NumVecElemsRemain = NumVecElems; 1113 while (NumVecElemsRemain - 1) { 1114 // Check for the right reduction operation. 1115 if (!RdxOp) 1116 return RK_None; 1117 Optional<ReductionData> RDLevel = getReductionData(RdxOp); 1118 if (!RDLevel || !RDLevel->hasSameData(*RD)) 1119 return RK_None; 1120 1121 Value *NextRdxOp; 1122 ShuffleVectorInst *Shuffle; 1123 std::tie(NextRdxOp, Shuffle) = 1124 getShuffleAndOtherOprd(RDLevel->LHS, RDLevel->RHS); 1125 1126 // Check the current reduction operation and the shuffle use the same value. 1127 if (Shuffle == nullptr) 1128 return RK_None; 1129 if (Shuffle->getOperand(0) != NextRdxOp) 1130 return RK_None; 1131 1132 // Check that shuffle masks matches. 1133 for (unsigned j = 0; j != MaskStart; ++j) 1134 ShuffleMask[j] = MaskStart + j; 1135 // Fill the rest of the mask with -1 for undef. 1136 std::fill(&ShuffleMask[MaskStart], ShuffleMask.end(), -1); 1137 1138 ArrayRef<int> Mask = Shuffle->getShuffleMask(); 1139 if (ShuffleMask != Mask) 1140 return RK_None; 1141 1142 RdxOp = dyn_cast<Instruction>(NextRdxOp); 1143 NumVecElemsRemain /= 2; 1144 MaskStart *= 2; 1145 } 1146 1147 Opcode = RD->Opcode; 1148 Ty = VecTy; 1149 return RD->Kind; 1150 } 1151 1152 int TargetTransformInfo::getInstructionThroughput(const Instruction *I) const { 1153 switch (I->getOpcode()) { 1154 case Instruction::GetElementPtr: 1155 return getUserCost(I); 1156 1157 case Instruction::Ret: 1158 case Instruction::PHI: 1159 case Instruction::Br: { 1160 return getCFInstrCost(I->getOpcode()); 1161 } 1162 case Instruction::Add: 1163 case Instruction::FAdd: 1164 case Instruction::Sub: 1165 case Instruction::FSub: 1166 case Instruction::Mul: 1167 case Instruction::FMul: 1168 case Instruction::UDiv: 1169 case Instruction::SDiv: 1170 case Instruction::FDiv: 1171 case Instruction::URem: 1172 case Instruction::SRem: 1173 case Instruction::FRem: 1174 case Instruction::Shl: 1175 case Instruction::LShr: 1176 case Instruction::AShr: 1177 case Instruction::And: 1178 case Instruction::Or: 1179 case Instruction::Xor: { 1180 TargetTransformInfo::OperandValueKind Op1VK, Op2VK; 1181 TargetTransformInfo::OperandValueProperties Op1VP, Op2VP; 1182 Op1VK = getOperandInfo(I->getOperand(0), Op1VP); 1183 Op2VK = getOperandInfo(I->getOperand(1), Op2VP); 1184 SmallVector<const Value *, 2> Operands(I->operand_values()); 1185 return getArithmeticInstrCost(I->getOpcode(), I->getType(), Op1VK, Op2VK, 1186 Op1VP, Op2VP, Operands, I); 1187 } 1188 case Instruction::FNeg: { 1189 TargetTransformInfo::OperandValueKind Op1VK, Op2VK; 1190 TargetTransformInfo::OperandValueProperties Op1VP, Op2VP; 1191 Op1VK = getOperandInfo(I->getOperand(0), Op1VP); 1192 Op2VK = OK_AnyValue; 1193 Op2VP = OP_None; 1194 SmallVector<const Value *, 2> Operands(I->operand_values()); 1195 return getArithmeticInstrCost(I->getOpcode(), I->getType(), Op1VK, Op2VK, 1196 Op1VP, Op2VP, Operands, I); 1197 } 1198 case Instruction::Select: { 1199 const SelectInst *SI = cast<SelectInst>(I); 1200 Type *CondTy = SI->getCondition()->getType(); 1201 return getCmpSelInstrCost(I->getOpcode(), I->getType(), CondTy, I); 1202 } 1203 case Instruction::ICmp: 1204 case Instruction::FCmp: { 1205 Type *ValTy = I->getOperand(0)->getType(); 1206 return getCmpSelInstrCost(I->getOpcode(), ValTy, I->getType(), I); 1207 } 1208 case Instruction::Store: { 1209 const StoreInst *SI = cast<StoreInst>(I); 1210 Type *ValTy = SI->getValueOperand()->getType(); 1211 return getMemoryOpCost(I->getOpcode(), ValTy, 1212 MaybeAlign(SI->getAlignment()), 1213 SI->getPointerAddressSpace(), I); 1214 } 1215 case Instruction::Load: { 1216 const LoadInst *LI = cast<LoadInst>(I); 1217 return getMemoryOpCost(I->getOpcode(), I->getType(), 1218 MaybeAlign(LI->getAlignment()), 1219 LI->getPointerAddressSpace(), I); 1220 } 1221 case Instruction::ZExt: 1222 case Instruction::SExt: 1223 case Instruction::FPToUI: 1224 case Instruction::FPToSI: 1225 case Instruction::FPExt: 1226 case Instruction::PtrToInt: 1227 case Instruction::IntToPtr: 1228 case Instruction::SIToFP: 1229 case Instruction::UIToFP: 1230 case Instruction::Trunc: 1231 case Instruction::FPTrunc: 1232 case Instruction::BitCast: 1233 case Instruction::AddrSpaceCast: { 1234 Type *SrcTy = I->getOperand(0)->getType(); 1235 return getCastInstrCost(I->getOpcode(), I->getType(), SrcTy, I); 1236 } 1237 case Instruction::ExtractElement: { 1238 const ExtractElementInst *EEI = cast<ExtractElementInst>(I); 1239 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1)); 1240 unsigned Idx = -1; 1241 if (CI) 1242 Idx = CI->getZExtValue(); 1243 1244 // Try to match a reduction sequence (series of shufflevector and vector 1245 // adds followed by a extractelement). 1246 unsigned ReduxOpCode; 1247 VectorType *ReduxType; 1248 1249 switch (matchVectorSplittingReduction(EEI, ReduxOpCode, ReduxType)) { 1250 case RK_Arithmetic: 1251 return getArithmeticReductionCost(ReduxOpCode, ReduxType, 1252 /*IsPairwiseForm=*/false); 1253 case RK_MinMax: 1254 return getMinMaxReductionCost( 1255 ReduxType, cast<VectorType>(CmpInst::makeCmpResultType(ReduxType)), 1256 /*IsPairwiseForm=*/false, /*IsUnsigned=*/false); 1257 case RK_UnsignedMinMax: 1258 return getMinMaxReductionCost( 1259 ReduxType, cast<VectorType>(CmpInst::makeCmpResultType(ReduxType)), 1260 /*IsPairwiseForm=*/false, /*IsUnsigned=*/true); 1261 case RK_None: 1262 break; 1263 } 1264 1265 switch (matchPairwiseReduction(EEI, ReduxOpCode, ReduxType)) { 1266 case RK_Arithmetic: 1267 return getArithmeticReductionCost(ReduxOpCode, ReduxType, 1268 /*IsPairwiseForm=*/true); 1269 case RK_MinMax: 1270 return getMinMaxReductionCost( 1271 ReduxType, cast<VectorType>(CmpInst::makeCmpResultType(ReduxType)), 1272 /*IsPairwiseForm=*/true, /*IsUnsigned=*/false); 1273 case RK_UnsignedMinMax: 1274 return getMinMaxReductionCost( 1275 ReduxType, cast<VectorType>(CmpInst::makeCmpResultType(ReduxType)), 1276 /*IsPairwiseForm=*/true, /*IsUnsigned=*/true); 1277 case RK_None: 1278 break; 1279 } 1280 1281 return getVectorInstrCost(I->getOpcode(), EEI->getOperand(0)->getType(), 1282 Idx); 1283 } 1284 case Instruction::InsertElement: { 1285 const InsertElementInst *IE = cast<InsertElementInst>(I); 1286 ConstantInt *CI = dyn_cast<ConstantInt>(IE->getOperand(2)); 1287 unsigned Idx = -1; 1288 if (CI) 1289 Idx = CI->getZExtValue(); 1290 return getVectorInstrCost(I->getOpcode(), IE->getType(), Idx); 1291 } 1292 case Instruction::ExtractValue: 1293 return 0; // Model all ExtractValue nodes as free. 1294 case Instruction::ShuffleVector: { 1295 const ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I); 1296 auto *Ty = cast<VectorType>(Shuffle->getType()); 1297 auto *SrcTy = cast<VectorType>(Shuffle->getOperand(0)->getType()); 1298 1299 // TODO: Identify and add costs for insert subvector, etc. 1300 int SubIndex; 1301 if (Shuffle->isExtractSubvectorMask(SubIndex)) 1302 return TTIImpl->getShuffleCost(SK_ExtractSubvector, SrcTy, SubIndex, Ty); 1303 1304 if (Shuffle->changesLength()) 1305 return -1; 1306 1307 if (Shuffle->isIdentity()) 1308 return 0; 1309 1310 if (Shuffle->isReverse()) 1311 return TTIImpl->getShuffleCost(SK_Reverse, Ty, 0, nullptr); 1312 1313 if (Shuffle->isSelect()) 1314 return TTIImpl->getShuffleCost(SK_Select, Ty, 0, nullptr); 1315 1316 if (Shuffle->isTranspose()) 1317 return TTIImpl->getShuffleCost(SK_Transpose, Ty, 0, nullptr); 1318 1319 if (Shuffle->isZeroEltSplat()) 1320 return TTIImpl->getShuffleCost(SK_Broadcast, Ty, 0, nullptr); 1321 1322 if (Shuffle->isSingleSource()) 1323 return TTIImpl->getShuffleCost(SK_PermuteSingleSrc, Ty, 0, nullptr); 1324 1325 return TTIImpl->getShuffleCost(SK_PermuteTwoSrc, Ty, 0, nullptr); 1326 } 1327 case Instruction::Call: 1328 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 1329 SmallVector<Value *, 4> Args(II->arg_operands()); 1330 1331 FastMathFlags FMF; 1332 if (auto *FPMO = dyn_cast<FPMathOperator>(II)) 1333 FMF = FPMO->getFastMathFlags(); 1334 1335 return getIntrinsicInstrCost(II->getIntrinsicID(), II->getType(), Args, 1336 FMF, 1, II); 1337 } 1338 return -1; 1339 default: 1340 // We don't have any information on this instruction. 1341 return -1; 1342 } 1343 } 1344 1345 TargetTransformInfo::Concept::~Concept() {} 1346 1347 TargetIRAnalysis::TargetIRAnalysis() : TTICallback(&getDefaultTTI) {} 1348 1349 TargetIRAnalysis::TargetIRAnalysis( 1350 std::function<Result(const Function &)> TTICallback) 1351 : TTICallback(std::move(TTICallback)) {} 1352 1353 TargetIRAnalysis::Result TargetIRAnalysis::run(const Function &F, 1354 FunctionAnalysisManager &) { 1355 return TTICallback(F); 1356 } 1357 1358 AnalysisKey TargetIRAnalysis::Key; 1359 1360 TargetIRAnalysis::Result TargetIRAnalysis::getDefaultTTI(const Function &F) { 1361 return Result(F.getParent()->getDataLayout()); 1362 } 1363 1364 // Register the basic pass. 1365 INITIALIZE_PASS(TargetTransformInfoWrapperPass, "tti", 1366 "Target Transform Information", false, true) 1367 char TargetTransformInfoWrapperPass::ID = 0; 1368 1369 void TargetTransformInfoWrapperPass::anchor() {} 1370 1371 TargetTransformInfoWrapperPass::TargetTransformInfoWrapperPass() 1372 : ImmutablePass(ID) { 1373 initializeTargetTransformInfoWrapperPassPass( 1374 *PassRegistry::getPassRegistry()); 1375 } 1376 1377 TargetTransformInfoWrapperPass::TargetTransformInfoWrapperPass( 1378 TargetIRAnalysis TIRA) 1379 : ImmutablePass(ID), TIRA(std::move(TIRA)) { 1380 initializeTargetTransformInfoWrapperPassPass( 1381 *PassRegistry::getPassRegistry()); 1382 } 1383 1384 TargetTransformInfo &TargetTransformInfoWrapperPass::getTTI(const Function &F) { 1385 FunctionAnalysisManager DummyFAM; 1386 TTI = TIRA.run(F, DummyFAM); 1387 return *TTI; 1388 } 1389 1390 ImmutablePass * 1391 llvm::createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA) { 1392 return new TargetTransformInfoWrapperPass(std::move(TIRA)); 1393 } 1394