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