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