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