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