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