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