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