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