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