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 unsigned 947 TargetTransformInfo::getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) const { 948 return TTIImpl->getCostOfKeepingLiveOverCall(Tys); 949 } 950 951 bool TargetTransformInfo::getTgtMemIntrinsic(IntrinsicInst *Inst, 952 MemIntrinsicInfo &Info) const { 953 return TTIImpl->getTgtMemIntrinsic(Inst, Info); 954 } 955 956 unsigned TargetTransformInfo::getAtomicMemIntrinsicMaxElementSize() const { 957 return TTIImpl->getAtomicMemIntrinsicMaxElementSize(); 958 } 959 960 Value *TargetTransformInfo::getOrCreateResultFromMemIntrinsic( 961 IntrinsicInst *Inst, Type *ExpectedType) const { 962 return TTIImpl->getOrCreateResultFromMemIntrinsic(Inst, ExpectedType); 963 } 964 965 Type *TargetTransformInfo::getMemcpyLoopLoweringType( 966 LLVMContext &Context, Value *Length, unsigned SrcAddrSpace, 967 unsigned DestAddrSpace, unsigned SrcAlign, unsigned DestAlign) const { 968 return TTIImpl->getMemcpyLoopLoweringType(Context, Length, SrcAddrSpace, 969 DestAddrSpace, SrcAlign, DestAlign); 970 } 971 972 void TargetTransformInfo::getMemcpyLoopResidualLoweringType( 973 SmallVectorImpl<Type *> &OpsOut, LLVMContext &Context, 974 unsigned RemainingBytes, unsigned SrcAddrSpace, unsigned DestAddrSpace, 975 unsigned SrcAlign, unsigned DestAlign) const { 976 TTIImpl->getMemcpyLoopResidualLoweringType(OpsOut, Context, RemainingBytes, 977 SrcAddrSpace, DestAddrSpace, 978 SrcAlign, DestAlign); 979 } 980 981 bool TargetTransformInfo::areInlineCompatible(const Function *Caller, 982 const Function *Callee) const { 983 return TTIImpl->areInlineCompatible(Caller, Callee); 984 } 985 986 bool TargetTransformInfo::areFunctionArgsABICompatible( 987 const Function *Caller, const Function *Callee, 988 SmallPtrSetImpl<Argument *> &Args) const { 989 return TTIImpl->areFunctionArgsABICompatible(Caller, Callee, Args); 990 } 991 992 bool TargetTransformInfo::isIndexedLoadLegal(MemIndexedMode Mode, 993 Type *Ty) const { 994 return TTIImpl->isIndexedLoadLegal(Mode, Ty); 995 } 996 997 bool TargetTransformInfo::isIndexedStoreLegal(MemIndexedMode Mode, 998 Type *Ty) const { 999 return TTIImpl->isIndexedStoreLegal(Mode, Ty); 1000 } 1001 1002 unsigned TargetTransformInfo::getLoadStoreVecRegBitWidth(unsigned AS) const { 1003 return TTIImpl->getLoadStoreVecRegBitWidth(AS); 1004 } 1005 1006 bool TargetTransformInfo::isLegalToVectorizeLoad(LoadInst *LI) const { 1007 return TTIImpl->isLegalToVectorizeLoad(LI); 1008 } 1009 1010 bool TargetTransformInfo::isLegalToVectorizeStore(StoreInst *SI) const { 1011 return TTIImpl->isLegalToVectorizeStore(SI); 1012 } 1013 1014 bool TargetTransformInfo::isLegalToVectorizeLoadChain( 1015 unsigned ChainSizeInBytes, Align Alignment, unsigned AddrSpace) const { 1016 return TTIImpl->isLegalToVectorizeLoadChain(ChainSizeInBytes, Alignment, 1017 AddrSpace); 1018 } 1019 1020 bool TargetTransformInfo::isLegalToVectorizeStoreChain( 1021 unsigned ChainSizeInBytes, Align Alignment, unsigned AddrSpace) const { 1022 return TTIImpl->isLegalToVectorizeStoreChain(ChainSizeInBytes, Alignment, 1023 AddrSpace); 1024 } 1025 1026 unsigned TargetTransformInfo::getLoadVectorFactor(unsigned VF, 1027 unsigned LoadSize, 1028 unsigned ChainSizeInBytes, 1029 VectorType *VecTy) const { 1030 return TTIImpl->getLoadVectorFactor(VF, LoadSize, ChainSizeInBytes, VecTy); 1031 } 1032 1033 unsigned TargetTransformInfo::getStoreVectorFactor(unsigned VF, 1034 unsigned StoreSize, 1035 unsigned ChainSizeInBytes, 1036 VectorType *VecTy) const { 1037 return TTIImpl->getStoreVectorFactor(VF, StoreSize, ChainSizeInBytes, VecTy); 1038 } 1039 1040 bool TargetTransformInfo::useReductionIntrinsic(unsigned Opcode, Type *Ty, 1041 ReductionFlags Flags) const { 1042 return TTIImpl->useReductionIntrinsic(Opcode, Ty, Flags); 1043 } 1044 1045 bool TargetTransformInfo::preferInLoopReduction(unsigned Opcode, Type *Ty, 1046 ReductionFlags Flags) const { 1047 return TTIImpl->preferInLoopReduction(Opcode, Ty, Flags); 1048 } 1049 1050 bool TargetTransformInfo::preferPredicatedReductionSelect( 1051 unsigned Opcode, Type *Ty, ReductionFlags Flags) const { 1052 return TTIImpl->preferPredicatedReductionSelect(Opcode, Ty, Flags); 1053 } 1054 1055 bool TargetTransformInfo::shouldExpandReduction(const IntrinsicInst *II) const { 1056 return TTIImpl->shouldExpandReduction(II); 1057 } 1058 1059 unsigned TargetTransformInfo::getGISelRematGlobalCost() const { 1060 return TTIImpl->getGISelRematGlobalCost(); 1061 } 1062 1063 bool TargetTransformInfo::supportsScalableVectors() const { 1064 return TTIImpl->supportsScalableVectors(); 1065 } 1066 1067 int TargetTransformInfo::getInstructionLatency(const Instruction *I) const { 1068 return TTIImpl->getInstructionLatency(I); 1069 } 1070 1071 static bool matchPairwiseShuffleMask(ShuffleVectorInst *SI, bool IsLeft, 1072 unsigned Level) { 1073 // We don't need a shuffle if we just want to have element 0 in position 0 of 1074 // the vector. 1075 if (!SI && Level == 0 && IsLeft) 1076 return true; 1077 else if (!SI) 1078 return false; 1079 1080 SmallVector<int, 32> Mask( 1081 cast<FixedVectorType>(SI->getType())->getNumElements(), -1); 1082 1083 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right) depending on whether 1084 // we look at the left or right side. 1085 for (unsigned i = 0, e = (1 << Level), val = !IsLeft; i != e; ++i, val += 2) 1086 Mask[i] = val; 1087 1088 ArrayRef<int> ActualMask = SI->getShuffleMask(); 1089 return Mask == ActualMask; 1090 } 1091 1092 static Optional<TTI::ReductionData> getReductionData(Instruction *I) { 1093 Value *L, *R; 1094 if (m_BinOp(m_Value(L), m_Value(R)).match(I)) 1095 return TTI::ReductionData(TTI::RK_Arithmetic, I->getOpcode(), L, R); 1096 if (auto *SI = dyn_cast<SelectInst>(I)) { 1097 if (m_SMin(m_Value(L), m_Value(R)).match(SI) || 1098 m_SMax(m_Value(L), m_Value(R)).match(SI) || 1099 m_OrdFMin(m_Value(L), m_Value(R)).match(SI) || 1100 m_OrdFMax(m_Value(L), m_Value(R)).match(SI) || 1101 m_UnordFMin(m_Value(L), m_Value(R)).match(SI) || 1102 m_UnordFMax(m_Value(L), m_Value(R)).match(SI)) { 1103 auto *CI = cast<CmpInst>(SI->getCondition()); 1104 return TTI::ReductionData(TTI::RK_MinMax, CI->getOpcode(), L, R); 1105 } 1106 if (m_UMin(m_Value(L), m_Value(R)).match(SI) || 1107 m_UMax(m_Value(L), m_Value(R)).match(SI)) { 1108 auto *CI = cast<CmpInst>(SI->getCondition()); 1109 return TTI::ReductionData(TTI::RK_UnsignedMinMax, CI->getOpcode(), L, R); 1110 } 1111 } 1112 return llvm::None; 1113 } 1114 1115 static TTI::ReductionKind matchPairwiseReductionAtLevel(Instruction *I, 1116 unsigned Level, 1117 unsigned NumLevels) { 1118 // Match one level of pairwise operations. 1119 // %rdx.shuf.0.0 = shufflevector <4 x float> %rdx, <4 x float> undef, 1120 // <4 x i32> <i32 0, i32 2 , i32 undef, i32 undef> 1121 // %rdx.shuf.0.1 = shufflevector <4 x float> %rdx, <4 x float> undef, 1122 // <4 x i32> <i32 1, i32 3, i32 undef, i32 undef> 1123 // %bin.rdx.0 = fadd <4 x float> %rdx.shuf.0.0, %rdx.shuf.0.1 1124 if (!I) 1125 return TTI::RK_None; 1126 1127 assert(I->getType()->isVectorTy() && "Expecting a vector type"); 1128 1129 Optional<TTI::ReductionData> RD = getReductionData(I); 1130 if (!RD) 1131 return TTI::RK_None; 1132 1133 ShuffleVectorInst *LS = dyn_cast<ShuffleVectorInst>(RD->LHS); 1134 if (!LS && Level) 1135 return TTI::RK_None; 1136 ShuffleVectorInst *RS = dyn_cast<ShuffleVectorInst>(RD->RHS); 1137 if (!RS && Level) 1138 return TTI::RK_None; 1139 1140 // On level 0 we can omit one shufflevector instruction. 1141 if (!Level && !RS && !LS) 1142 return TTI::RK_None; 1143 1144 // Shuffle inputs must match. 1145 Value *NextLevelOpL = LS ? LS->getOperand(0) : nullptr; 1146 Value *NextLevelOpR = RS ? RS->getOperand(0) : nullptr; 1147 Value *NextLevelOp = nullptr; 1148 if (NextLevelOpR && NextLevelOpL) { 1149 // If we have two shuffles their operands must match. 1150 if (NextLevelOpL != NextLevelOpR) 1151 return TTI::RK_None; 1152 1153 NextLevelOp = NextLevelOpL; 1154 } else if (Level == 0 && (NextLevelOpR || NextLevelOpL)) { 1155 // On the first level we can omit the shufflevector <0, undef,...>. So the 1156 // input to the other shufflevector <1, undef> must match with one of the 1157 // inputs to the current binary operation. 1158 // Example: 1159 // %NextLevelOpL = shufflevector %R, <1, undef ...> 1160 // %BinOp = fadd %NextLevelOpL, %R 1161 if (NextLevelOpL && NextLevelOpL != RD->RHS) 1162 return TTI::RK_None; 1163 else if (NextLevelOpR && NextLevelOpR != RD->LHS) 1164 return TTI::RK_None; 1165 1166 NextLevelOp = NextLevelOpL ? RD->RHS : RD->LHS; 1167 } else 1168 return TTI::RK_None; 1169 1170 // Check that the next levels binary operation exists and matches with the 1171 // current one. 1172 if (Level + 1 != NumLevels) { 1173 if (!isa<Instruction>(NextLevelOp)) 1174 return TTI::RK_None; 1175 Optional<TTI::ReductionData> NextLevelRD = 1176 getReductionData(cast<Instruction>(NextLevelOp)); 1177 if (!NextLevelRD || !RD->hasSameData(*NextLevelRD)) 1178 return TTI::RK_None; 1179 } 1180 1181 // Shuffle mask for pairwise operation must match. 1182 if (matchPairwiseShuffleMask(LS, /*IsLeft=*/true, Level)) { 1183 if (!matchPairwiseShuffleMask(RS, /*IsLeft=*/false, Level)) 1184 return TTI::RK_None; 1185 } else if (matchPairwiseShuffleMask(RS, /*IsLeft=*/true, Level)) { 1186 if (!matchPairwiseShuffleMask(LS, /*IsLeft=*/false, Level)) 1187 return TTI::RK_None; 1188 } else { 1189 return TTI::RK_None; 1190 } 1191 1192 if (++Level == NumLevels) 1193 return RD->Kind; 1194 1195 // Match next level. 1196 return matchPairwiseReductionAtLevel(dyn_cast<Instruction>(NextLevelOp), Level, 1197 NumLevels); 1198 } 1199 1200 TTI::ReductionKind TTI::matchPairwiseReduction( 1201 const ExtractElementInst *ReduxRoot, unsigned &Opcode, VectorType *&Ty) { 1202 if (!EnableReduxCost) 1203 return TTI::RK_None; 1204 1205 // Need to extract the first element. 1206 ConstantInt *CI = dyn_cast<ConstantInt>(ReduxRoot->getOperand(1)); 1207 unsigned Idx = ~0u; 1208 if (CI) 1209 Idx = CI->getZExtValue(); 1210 if (Idx != 0) 1211 return TTI::RK_None; 1212 1213 auto *RdxStart = dyn_cast<Instruction>(ReduxRoot->getOperand(0)); 1214 if (!RdxStart) 1215 return TTI::RK_None; 1216 Optional<TTI::ReductionData> RD = getReductionData(RdxStart); 1217 if (!RD) 1218 return TTI::RK_None; 1219 1220 auto *VecTy = cast<FixedVectorType>(RdxStart->getType()); 1221 unsigned NumVecElems = VecTy->getNumElements(); 1222 if (!isPowerOf2_32(NumVecElems)) 1223 return TTI::RK_None; 1224 1225 // We look for a sequence of shuffle,shuffle,add triples like the following 1226 // that builds a pairwise reduction tree. 1227 // 1228 // (X0, X1, X2, X3) 1229 // (X0 + X1, X2 + X3, undef, undef) 1230 // ((X0 + X1) + (X2 + X3), undef, undef, undef) 1231 // 1232 // %rdx.shuf.0.0 = shufflevector <4 x float> %rdx, <4 x float> undef, 1233 // <4 x i32> <i32 0, i32 2 , i32 undef, i32 undef> 1234 // %rdx.shuf.0.1 = shufflevector <4 x float> %rdx, <4 x float> undef, 1235 // <4 x i32> <i32 1, i32 3, i32 undef, i32 undef> 1236 // %bin.rdx.0 = fadd <4 x float> %rdx.shuf.0.0, %rdx.shuf.0.1 1237 // %rdx.shuf.1.0 = shufflevector <4 x float> %bin.rdx.0, <4 x float> undef, 1238 // <4 x i32> <i32 0, i32 undef, i32 undef, i32 undef> 1239 // %rdx.shuf.1.1 = shufflevector <4 x float> %bin.rdx.0, <4 x float> undef, 1240 // <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef> 1241 // %bin.rdx8 = fadd <4 x float> %rdx.shuf.1.0, %rdx.shuf.1.1 1242 // %r = extractelement <4 x float> %bin.rdx8, i32 0 1243 if (matchPairwiseReductionAtLevel(RdxStart, 0, Log2_32(NumVecElems)) == 1244 TTI::RK_None) 1245 return TTI::RK_None; 1246 1247 Opcode = RD->Opcode; 1248 Ty = VecTy; 1249 1250 return RD->Kind; 1251 } 1252 1253 static std::pair<Value *, ShuffleVectorInst *> 1254 getShuffleAndOtherOprd(Value *L, Value *R) { 1255 ShuffleVectorInst *S = nullptr; 1256 1257 if ((S = dyn_cast<ShuffleVectorInst>(L))) 1258 return std::make_pair(R, S); 1259 1260 S = dyn_cast<ShuffleVectorInst>(R); 1261 return std::make_pair(L, S); 1262 } 1263 1264 TTI::ReductionKind TTI::matchVectorSplittingReduction( 1265 const ExtractElementInst *ReduxRoot, unsigned &Opcode, VectorType *&Ty) { 1266 1267 if (!EnableReduxCost) 1268 return TTI::RK_None; 1269 1270 // Need to extract the first element. 1271 ConstantInt *CI = dyn_cast<ConstantInt>(ReduxRoot->getOperand(1)); 1272 unsigned Idx = ~0u; 1273 if (CI) 1274 Idx = CI->getZExtValue(); 1275 if (Idx != 0) 1276 return TTI::RK_None; 1277 1278 auto *RdxStart = dyn_cast<Instruction>(ReduxRoot->getOperand(0)); 1279 if (!RdxStart) 1280 return TTI::RK_None; 1281 Optional<TTI::ReductionData> RD = getReductionData(RdxStart); 1282 if (!RD) 1283 return TTI::RK_None; 1284 1285 auto *VecTy = cast<FixedVectorType>(ReduxRoot->getOperand(0)->getType()); 1286 unsigned NumVecElems = VecTy->getNumElements(); 1287 if (!isPowerOf2_32(NumVecElems)) 1288 return TTI::RK_None; 1289 1290 // We look for a sequence of shuffles and adds like the following matching one 1291 // fadd, shuffle vector pair at a time. 1292 // 1293 // %rdx.shuf = shufflevector <4 x float> %rdx, <4 x float> undef, 1294 // <4 x i32> <i32 2, i32 3, i32 undef, i32 undef> 1295 // %bin.rdx = fadd <4 x float> %rdx, %rdx.shuf 1296 // %rdx.shuf7 = shufflevector <4 x float> %bin.rdx, <4 x float> undef, 1297 // <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef> 1298 // %bin.rdx8 = fadd <4 x float> %bin.rdx, %rdx.shuf7 1299 // %r = extractelement <4 x float> %bin.rdx8, i32 0 1300 1301 unsigned MaskStart = 1; 1302 Instruction *RdxOp = RdxStart; 1303 SmallVector<int, 32> ShuffleMask(NumVecElems, 0); 1304 unsigned NumVecElemsRemain = NumVecElems; 1305 while (NumVecElemsRemain - 1) { 1306 // Check for the right reduction operation. 1307 if (!RdxOp) 1308 return TTI::RK_None; 1309 Optional<TTI::ReductionData> RDLevel = getReductionData(RdxOp); 1310 if (!RDLevel || !RDLevel->hasSameData(*RD)) 1311 return TTI::RK_None; 1312 1313 Value *NextRdxOp; 1314 ShuffleVectorInst *Shuffle; 1315 std::tie(NextRdxOp, Shuffle) = 1316 getShuffleAndOtherOprd(RDLevel->LHS, RDLevel->RHS); 1317 1318 // Check the current reduction operation and the shuffle use the same value. 1319 if (Shuffle == nullptr) 1320 return TTI::RK_None; 1321 if (Shuffle->getOperand(0) != NextRdxOp) 1322 return TTI::RK_None; 1323 1324 // Check that shuffle masks matches. 1325 for (unsigned j = 0; j != MaskStart; ++j) 1326 ShuffleMask[j] = MaskStart + j; 1327 // Fill the rest of the mask with -1 for undef. 1328 std::fill(&ShuffleMask[MaskStart], ShuffleMask.end(), -1); 1329 1330 ArrayRef<int> Mask = Shuffle->getShuffleMask(); 1331 if (ShuffleMask != Mask) 1332 return TTI::RK_None; 1333 1334 RdxOp = dyn_cast<Instruction>(NextRdxOp); 1335 NumVecElemsRemain /= 2; 1336 MaskStart *= 2; 1337 } 1338 1339 Opcode = RD->Opcode; 1340 Ty = VecTy; 1341 return RD->Kind; 1342 } 1343 1344 TTI::ReductionKind 1345 TTI::matchVectorReduction(const ExtractElementInst *Root, unsigned &Opcode, 1346 VectorType *&Ty, bool &IsPairwise) { 1347 TTI::ReductionKind RdxKind = matchVectorSplittingReduction(Root, Opcode, Ty); 1348 if (RdxKind != TTI::ReductionKind::RK_None) { 1349 IsPairwise = false; 1350 return RdxKind; 1351 } 1352 IsPairwise = true; 1353 return matchPairwiseReduction(Root, Opcode, Ty); 1354 } 1355 1356 int TargetTransformInfo::getInstructionThroughput(const Instruction *I) const { 1357 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput; 1358 1359 switch (I->getOpcode()) { 1360 case Instruction::GetElementPtr: 1361 case Instruction::Ret: 1362 case Instruction::PHI: 1363 case Instruction::Br: 1364 case Instruction::Add: 1365 case Instruction::FAdd: 1366 case Instruction::Sub: 1367 case Instruction::FSub: 1368 case Instruction::Mul: 1369 case Instruction::FMul: 1370 case Instruction::UDiv: 1371 case Instruction::SDiv: 1372 case Instruction::FDiv: 1373 case Instruction::URem: 1374 case Instruction::SRem: 1375 case Instruction::FRem: 1376 case Instruction::Shl: 1377 case Instruction::LShr: 1378 case Instruction::AShr: 1379 case Instruction::And: 1380 case Instruction::Or: 1381 case Instruction::Xor: 1382 case Instruction::FNeg: 1383 case Instruction::Select: 1384 case Instruction::ICmp: 1385 case Instruction::FCmp: 1386 case Instruction::Store: 1387 case Instruction::Load: 1388 case Instruction::ZExt: 1389 case Instruction::SExt: 1390 case Instruction::FPToUI: 1391 case Instruction::FPToSI: 1392 case Instruction::FPExt: 1393 case Instruction::PtrToInt: 1394 case Instruction::IntToPtr: 1395 case Instruction::SIToFP: 1396 case Instruction::UIToFP: 1397 case Instruction::Trunc: 1398 case Instruction::FPTrunc: 1399 case Instruction::BitCast: 1400 case Instruction::AddrSpaceCast: 1401 case Instruction::ExtractElement: 1402 case Instruction::InsertElement: 1403 case Instruction::ExtractValue: 1404 case Instruction::ShuffleVector: 1405 case Instruction::Call: 1406 return getUserCost(I, CostKind); 1407 default: 1408 // We don't have any information on this instruction. 1409 return -1; 1410 } 1411 } 1412 1413 TargetTransformInfo::Concept::~Concept() {} 1414 1415 TargetIRAnalysis::TargetIRAnalysis() : TTICallback(&getDefaultTTI) {} 1416 1417 TargetIRAnalysis::TargetIRAnalysis( 1418 std::function<Result(const Function &)> TTICallback) 1419 : TTICallback(std::move(TTICallback)) {} 1420 1421 TargetIRAnalysis::Result TargetIRAnalysis::run(const Function &F, 1422 FunctionAnalysisManager &) { 1423 return TTICallback(F); 1424 } 1425 1426 AnalysisKey TargetIRAnalysis::Key; 1427 1428 TargetIRAnalysis::Result TargetIRAnalysis::getDefaultTTI(const Function &F) { 1429 return Result(F.getParent()->getDataLayout()); 1430 } 1431 1432 // Register the basic pass. 1433 INITIALIZE_PASS(TargetTransformInfoWrapperPass, "tti", 1434 "Target Transform Information", false, true) 1435 char TargetTransformInfoWrapperPass::ID = 0; 1436 1437 void TargetTransformInfoWrapperPass::anchor() {} 1438 1439 TargetTransformInfoWrapperPass::TargetTransformInfoWrapperPass() 1440 : ImmutablePass(ID) { 1441 initializeTargetTransformInfoWrapperPassPass( 1442 *PassRegistry::getPassRegistry()); 1443 } 1444 1445 TargetTransformInfoWrapperPass::TargetTransformInfoWrapperPass( 1446 TargetIRAnalysis TIRA) 1447 : ImmutablePass(ID), TIRA(std::move(TIRA)) { 1448 initializeTargetTransformInfoWrapperPassPass( 1449 *PassRegistry::getPassRegistry()); 1450 } 1451 1452 TargetTransformInfo &TargetTransformInfoWrapperPass::getTTI(const Function &F) { 1453 FunctionAnalysisManager DummyFAM; 1454 TTI = TIRA.run(F, DummyFAM); 1455 return *TTI; 1456 } 1457 1458 ImmutablePass * 1459 llvm::createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA) { 1460 return new TargetTransformInfoWrapperPass(std::move(TIRA)); 1461 } 1462