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