[ARM] Generate 8.1-m CSINC, CSNEG and CSINV instructions.
[llvm-core.git] / lib / Analysis / TargetTransformInfo.cpp
blobc463d82fca0c0d3f03a4f584e2df68cb606d2007
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 //===----------------------------------------------------------------------===//
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>
25 using namespace llvm;
26 using namespace PatternMatch;
28 #define DEBUG_TYPE "tti"
30 static cl::opt<bool> EnableReduxCost("costmodel-reduxcost", cl::init(false),
31 cl::Hidden,
32 cl::desc("Recognize reduction patterns."));
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) {}
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;
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);
62 for (SmallVectorImpl<BasicBlock *>::iterator I = ExitingBlocks.begin(),
63 IE = ExitingBlocks.end();
64 I != IE; ++I) {
65 BasicBlock *BB = *I;
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;
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;
83 if (SE.getTypeSizeInBits(EC->getType()) > CountType->getBitWidth())
84 continue;
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;
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.
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;
106 if (!DT.dominates(*I, *PI)) {
107 NotAlways = true;
108 break;
112 if (NotAlways)
113 continue;
115 // Make sure this blocks ends with a conditional branch.
116 Instruction *TI = BB->getTerminator();
117 if (!TI)
118 continue;
120 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
121 if (!BI->isConditional())
122 continue;
124 ExitBranch = BI;
125 } else
126 continue;
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;
135 if (!ExitBlock)
136 return false;
137 return true;
140 TargetTransformInfo::TargetTransformInfo(const DataLayout &DL)
141 : TTIImpl(new Model<NoTTIImpl>(NoTTIImpl(DL))) {}
143 TargetTransformInfo::~TargetTransformInfo() {}
145 TargetTransformInfo::TargetTransformInfo(TargetTransformInfo &&Arg)
146 : TTIImpl(std::move(Arg.TTIImpl)) {}
148 TargetTransformInfo &TargetTransformInfo::operator=(TargetTransformInfo &&RHS) {
149 TTIImpl = std::move(RHS.TTIImpl);
150 return *this;
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;
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;
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;
175 unsigned TargetTransformInfo::getInliningThresholdMultiplier() const {
176 return TTIImpl->getInliningThresholdMultiplier();
179 int TargetTransformInfo::getInlinerVectorBonusPercent() const {
180 return TTIImpl->getInlinerVectorBonusPercent();
183 int TargetTransformInfo::getGEPCost(Type *PointeeType, const Value *Ptr,
184 ArrayRef<const Value *> Operands) const {
185 return TTIImpl->getGEPCost(PointeeType, Ptr, Operands);
188 int TargetTransformInfo::getExtCost(const Instruction *I,
189 const Value *Src) const {
190 return TTIImpl->getExtCost(I, Src);
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;
201 unsigned
202 TargetTransformInfo::getEstimatedNumberOfCaseClusters(const SwitchInst &SI,
203 unsigned &JTSize) const {
204 return TTIImpl->getEstimatedNumberOfCaseClusters(SI, JTSize);
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;
214 bool TargetTransformInfo::hasBranchDivergence() const {
215 return TTIImpl->hasBranchDivergence();
218 bool TargetTransformInfo::isSourceOfDivergence(const Value *V) const {
219 return TTIImpl->isSourceOfDivergence(V);
222 bool llvm::TargetTransformInfo::isAlwaysUniform(const Value *V) const {
223 return TTIImpl->isAlwaysUniform(V);
226 unsigned TargetTransformInfo::getFlatAddressSpace() const {
227 return TTIImpl->getFlatAddressSpace();
230 bool TargetTransformInfo::collectFlatAddressOperands(
231 SmallVectorImpl<int> &OpIndexes, Intrinsic::ID IID) const {
232 return TTIImpl->collectFlatAddressOperands(OpIndexes, IID);
235 bool TargetTransformInfo::rewriteIntrinsicWithAddressSpace(
236 IntrinsicInst *II, Value *OldV, Value *NewV) const {
237 return TTIImpl->rewriteIntrinsicWithAddressSpace(II, OldV, NewV);
240 bool TargetTransformInfo::isLoweredToCall(const Function *F) const {
241 return TTIImpl->isLoweredToCall(F);
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);
250 void TargetTransformInfo::getUnrollingPreferences(
251 Loop *L, ScalarEvolution &SE, UnrollingPreferences &UP) const {
252 return TTIImpl->getUnrollingPreferences(L, SE, UP);
255 bool TargetTransformInfo::isLegalAddImmediate(int64_t Imm) const {
256 return TTIImpl->isLegalAddImmediate(Imm);
259 bool TargetTransformInfo::isLegalICmpImmediate(int64_t Imm) const {
260 return TTIImpl->isLegalICmpImmediate(Imm);
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);
273 bool TargetTransformInfo::isLSRCostLess(LSRCost &C1, LSRCost &C2) const {
274 return TTIImpl->isLSRCostLess(C1, C2);
277 bool TargetTransformInfo::canMacroFuseCmp() const {
278 return TTIImpl->canMacroFuseCmp();
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);
288 bool TargetTransformInfo::shouldFavorPostInc() const {
289 return TTIImpl->shouldFavorPostInc();
292 bool TargetTransformInfo::shouldFavorBackedgeIndex(const Loop *L) const {
293 return TTIImpl->shouldFavorBackedgeIndex(L);
296 bool TargetTransformInfo::isLegalMaskedStore(Type *DataType) const {
297 return TTIImpl->isLegalMaskedStore(DataType);
300 bool TargetTransformInfo::isLegalMaskedLoad(Type *DataType) const {
301 return TTIImpl->isLegalMaskedLoad(DataType);
304 bool TargetTransformInfo::isLegalNTStore(Type *DataType,
305 unsigned Alignment) const {
306 return TTIImpl->isLegalNTStore(DataType, Alignment);
309 bool TargetTransformInfo::isLegalNTLoad(Type *DataType,
310 unsigned Alignment) const {
311 return TTIImpl->isLegalNTLoad(DataType, Alignment);
314 bool TargetTransformInfo::isLegalMaskedGather(Type *DataType) const {
315 return TTIImpl->isLegalMaskedGather(DataType);
318 bool TargetTransformInfo::isLegalMaskedScatter(Type *DataType) const {
319 return TTIImpl->isLegalMaskedScatter(DataType);
322 bool TargetTransformInfo::isLegalMaskedCompressStore(Type *DataType) const {
323 return TTIImpl->isLegalMaskedCompressStore(DataType);
326 bool TargetTransformInfo::isLegalMaskedExpandLoad(Type *DataType) const {
327 return TTIImpl->isLegalMaskedExpandLoad(DataType);
330 bool TargetTransformInfo::hasDivRemOp(Type *DataType, bool IsSigned) const {
331 return TTIImpl->hasDivRemOp(DataType, IsSigned);
334 bool TargetTransformInfo::hasVolatileVariant(Instruction *I,
335 unsigned AddrSpace) const {
336 return TTIImpl->hasVolatileVariant(I, AddrSpace);
339 bool TargetTransformInfo::prefersVectorizedAddressing() const {
340 return TTIImpl->prefersVectorizedAddressing();
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;
354 bool TargetTransformInfo::LSRWithInstrQueries() const {
355 return TTIImpl->LSRWithInstrQueries();
358 bool TargetTransformInfo::isTruncateFree(Type *Ty1, Type *Ty2) const {
359 return TTIImpl->isTruncateFree(Ty1, Ty2);
362 bool TargetTransformInfo::isProfitableToHoist(Instruction *I) const {
363 return TTIImpl->isProfitableToHoist(I);
366 bool TargetTransformInfo::useAA() const { return TTIImpl->useAA(); }
368 bool TargetTransformInfo::isTypeLegal(Type *Ty) const {
369 return TTIImpl->isTypeLegal(Ty);
372 unsigned TargetTransformInfo::getJumpBufAlignment() const {
373 return TTIImpl->getJumpBufAlignment();
376 unsigned TargetTransformInfo::getJumpBufSize() const {
377 return TTIImpl->getJumpBufSize();
380 bool TargetTransformInfo::shouldBuildLookupTables() const {
381 return TTIImpl->shouldBuildLookupTables();
383 bool TargetTransformInfo::shouldBuildLookupTablesForConstant(Constant *C) const {
384 return TTIImpl->shouldBuildLookupTablesForConstant(C);
387 bool TargetTransformInfo::useColdCCForColdCall(Function &F) const {
388 return TTIImpl->useColdCCForColdCall(F);
391 unsigned TargetTransformInfo::
392 getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) const {
393 return TTIImpl->getScalarizationOverhead(Ty, Insert, Extract);
396 unsigned TargetTransformInfo::
397 getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
398 unsigned VF) const {
399 return TTIImpl->getOperandsScalarizationOverhead(Args, VF);
402 bool TargetTransformInfo::supportsEfficientVectorElementLoadStore() const {
403 return TTIImpl->supportsEfficientVectorElementLoadStore();
406 bool TargetTransformInfo::enableAggressiveInterleaving(bool LoopHasReductions) const {
407 return TTIImpl->enableAggressiveInterleaving(LoopHasReductions);
410 TargetTransformInfo::MemCmpExpansionOptions
411 TargetTransformInfo::enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const {
412 return TTIImpl->enableMemCmpExpansion(OptSize, IsZeroCmp);
415 bool TargetTransformInfo::enableInterleavedAccessVectorization() const {
416 return TTIImpl->enableInterleavedAccessVectorization();
419 bool TargetTransformInfo::enableMaskedInterleavedAccessVectorization() const {
420 return TTIImpl->enableMaskedInterleavedAccessVectorization();
423 bool TargetTransformInfo::isFPVectorizationPotentiallyUnsafe() const {
424 return TTIImpl->isFPVectorizationPotentiallyUnsafe();
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);
436 TargetTransformInfo::PopcntSupportKind
437 TargetTransformInfo::getPopcntSupport(unsigned IntTyWidthInBit) const {
438 return TTIImpl->getPopcntSupport(IntTyWidthInBit);
441 bool TargetTransformInfo::haveFastSqrt(Type *Ty) const {
442 return TTIImpl->haveFastSqrt(Ty);
445 bool TargetTransformInfo::isFCmpOrdCheaperThanFCmpZero(Type *Ty) const {
446 return TTIImpl->isFCmpOrdCheaperThanFCmpZero(Ty);
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;
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;
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;
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;
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;
483 unsigned TargetTransformInfo::getNumberOfRegisters(bool Vector) const {
484 return TTIImpl->getNumberOfRegisters(Vector);
487 unsigned TargetTransformInfo::getRegisterBitWidth(bool Vector) const {
488 return TTIImpl->getRegisterBitWidth(Vector);
491 unsigned TargetTransformInfo::getMinVectorRegisterBitWidth() const {
492 return TTIImpl->getMinVectorRegisterBitWidth();
495 bool TargetTransformInfo::shouldMaximizeVectorBandwidth(bool OptSize) const {
496 return TTIImpl->shouldMaximizeVectorBandwidth(OptSize);
499 unsigned TargetTransformInfo::getMinimumVF(unsigned ElemWidth) const {
500 return TTIImpl->getMinimumVF(ElemWidth);
503 bool TargetTransformInfo::shouldConsiderAddressTypePromotion(
504 const Instruction &I, bool &AllowPromotionWithoutCommonHeader) const {
505 return TTIImpl->shouldConsiderAddressTypePromotion(
506 I, AllowPromotionWithoutCommonHeader);
509 unsigned TargetTransformInfo::getCacheLineSize() const {
510 return TTIImpl->getCacheLineSize();
513 llvm::Optional<unsigned> TargetTransformInfo::getCacheSize(CacheLevel Level)
514 const {
515 return TTIImpl->getCacheSize(Level);
518 llvm::Optional<unsigned> TargetTransformInfo::getCacheAssociativity(
519 CacheLevel Level) const {
520 return TTIImpl->getCacheAssociativity(Level);
523 unsigned TargetTransformInfo::getPrefetchDistance() const {
524 return TTIImpl->getPrefetchDistance();
527 unsigned TargetTransformInfo::getMinPrefetchStride() const {
528 return TTIImpl->getMinPrefetchStride();
531 unsigned TargetTransformInfo::getMaxPrefetchIterationsAhead() const {
532 return TTIImpl->getMaxPrefetchIterationsAhead();
535 unsigned TargetTransformInfo::getMaxInterleaveFactor(unsigned VF) const {
536 return TTIImpl->getMaxInterleaveFactor(VF);
539 TargetTransformInfo::OperandValueKind
540 TargetTransformInfo::getOperandInfo(Value *V, OperandValueProperties &OpProps) {
541 OperandValueKind OpInfo = OK_AnyValue;
542 OpProps = OP_None;
544 if (auto *CI = dyn_cast<ConstantInt>(V)) {
545 if (CI->getValue().isPowerOf2())
546 OpProps = OP_PowerOf2;
547 return OK_UniformConstantValue;
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;
557 const Value *Splat = getSplatValue(V);
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;
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;
585 return OpInfo;
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;
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;
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;
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;
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;
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;
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;
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;
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;
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;
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;
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;
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;
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;
709 unsigned TargetTransformInfo::getNumberOfParts(Type *Tp) const {
710 return TTIImpl->getNumberOfParts(Tp);
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;
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;
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;
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;
743 unsigned
744 TargetTransformInfo::getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) const {
745 return TTIImpl->getCostOfKeepingLiveOverCall(Tys);
748 bool TargetTransformInfo::getTgtMemIntrinsic(IntrinsicInst *Inst,
749 MemIntrinsicInfo &Info) const {
750 return TTIImpl->getTgtMemIntrinsic(Inst, Info);
753 unsigned TargetTransformInfo::getAtomicMemIntrinsicMaxElementSize() const {
754 return TTIImpl->getAtomicMemIntrinsicMaxElementSize();
757 Value *TargetTransformInfo::getOrCreateResultFromMemIntrinsic(
758 IntrinsicInst *Inst, Type *ExpectedType) const {
759 return TTIImpl->getOrCreateResultFromMemIntrinsic(Inst, ExpectedType);
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);
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);
777 bool TargetTransformInfo::areInlineCompatible(const Function *Caller,
778 const Function *Callee) const {
779 return TTIImpl->areInlineCompatible(Caller, Callee);
782 bool TargetTransformInfo::areFunctionArgsABICompatible(
783 const Function *Caller, const Function *Callee,
784 SmallPtrSetImpl<Argument *> &Args) const {
785 return TTIImpl->areFunctionArgsABICompatible(Caller, Callee, Args);
788 bool TargetTransformInfo::isIndexedLoadLegal(MemIndexedMode Mode,
789 Type *Ty) const {
790 return TTIImpl->isIndexedLoadLegal(Mode, Ty);
793 bool TargetTransformInfo::isIndexedStoreLegal(MemIndexedMode Mode,
794 Type *Ty) const {
795 return TTIImpl->isIndexedStoreLegal(Mode, Ty);
798 unsigned TargetTransformInfo::getLoadStoreVecRegBitWidth(unsigned AS) const {
799 return TTIImpl->getLoadStoreVecRegBitWidth(AS);
802 bool TargetTransformInfo::isLegalToVectorizeLoad(LoadInst *LI) const {
803 return TTIImpl->isLegalToVectorizeLoad(LI);
806 bool TargetTransformInfo::isLegalToVectorizeStore(StoreInst *SI) const {
807 return TTIImpl->isLegalToVectorizeStore(SI);
810 bool TargetTransformInfo::isLegalToVectorizeLoadChain(
811 unsigned ChainSizeInBytes, unsigned Alignment, unsigned AddrSpace) const {
812 return TTIImpl->isLegalToVectorizeLoadChain(ChainSizeInBytes, Alignment,
813 AddrSpace);
816 bool TargetTransformInfo::isLegalToVectorizeStoreChain(
817 unsigned ChainSizeInBytes, unsigned Alignment, unsigned AddrSpace) const {
818 return TTIImpl->isLegalToVectorizeStoreChain(ChainSizeInBytes, Alignment,
819 AddrSpace);
822 unsigned TargetTransformInfo::getLoadVectorFactor(unsigned VF,
823 unsigned LoadSize,
824 unsigned ChainSizeInBytes,
825 VectorType *VecTy) const {
826 return TTIImpl->getLoadVectorFactor(VF, LoadSize, ChainSizeInBytes, VecTy);
829 unsigned TargetTransformInfo::getStoreVectorFactor(unsigned VF,
830 unsigned StoreSize,
831 unsigned ChainSizeInBytes,
832 VectorType *VecTy) const {
833 return TTIImpl->getStoreVectorFactor(VF, StoreSize, ChainSizeInBytes, VecTy);
836 bool TargetTransformInfo::useReductionIntrinsic(unsigned Opcode,
837 Type *Ty, ReductionFlags Flags) const {
838 return TTIImpl->useReductionIntrinsic(Opcode, Ty, Flags);
841 bool TargetTransformInfo::shouldExpandReduction(const IntrinsicInst *II) const {
842 return TTIImpl->shouldExpandReduction(II);
845 unsigned TargetTransformInfo::getGISelRematGlobalCost() const {
846 return TTIImpl->getGISelRematGlobalCost();
849 int TargetTransformInfo::getInstructionLatency(const Instruction *I) const {
850 return TTIImpl->getInstructionLatency(I);
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;
862 SmallVector<int, 32> Mask(SI->getType()->getVectorNumElements(), -1);
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;
869 SmallVector<int, 16> ActualMask = SI->getShuffleMask();
870 return Mask == ActualMask;
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.
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.");
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;
896 } // namespace
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);
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);
918 return llvm::None;
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;
933 assert(I->getType()->isVectorTy() && "Expecting a vector type");
935 Optional<ReductionData> RD = getReductionData(I);
936 if (!RD)
937 return RK_None;
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;
946 // On level 0 we can omit one shufflevector instruction.
947 if (!Level && !RS && !LS)
948 return RK_None;
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;
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;
972 NextLevelOp = NextLevelOpL ? RD->RHS : RD->LHS;
973 } else
974 return RK_None;
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;
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;
996 if (++Level == NumLevels)
997 return RD->Kind;
999 // Match next level.
1000 return matchPairwiseReductionAtLevel(cast<Instruction>(NextLevelOp), Level,
1001 NumLevels);
1004 static ReductionKind matchPairwiseReduction(const ExtractElementInst *ReduxRoot,
1005 unsigned &Opcode, Type *&Ty) {
1006 if (!EnableReduxCost)
1007 return RK_None;
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;
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;
1024 Type *VecTy = RdxStart->getType();
1025 unsigned NumVecElems = VecTy->getVectorNumElements();
1026 if (!isPowerOf2_32(NumVecElems))
1027 return RK_None;
1029 // We look for a sequence of shuffle,shuffle,add triples like the following
1030 // that builds a pairwise reduction tree.
1032 // (X0, X1, X2, X3)
1033 // (X0 + X1, X2 + X3, undef, undef)
1034 // ((X0 + X1) + (X2 + X3), undef, undef, undef)
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;
1051 Opcode = RD->Opcode;
1052 Ty = VecTy;
1054 return RD->Kind;
1057 static std::pair<Value *, ShuffleVectorInst *>
1058 getShuffleAndOtherOprd(Value *L, Value *R) {
1059 ShuffleVectorInst *S = nullptr;
1061 if ((S = dyn_cast<ShuffleVectorInst>(L)))
1062 return std::make_pair(R, S);
1064 S = dyn_cast<ShuffleVectorInst>(R);
1065 return std::make_pair(L, S);
1068 static ReductionKind
1069 matchVectorSplittingReduction(const ExtractElementInst *ReduxRoot,
1070 unsigned &Opcode, Type *&Ty) {
1071 if (!EnableReduxCost)
1072 return RK_None;
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;
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;
1089 Type *VecTy = ReduxRoot->getOperand(0)->getType();
1090 unsigned NumVecElems = VecTy->getVectorNumElements();
1091 if (!isPowerOf2_32(NumVecElems))
1092 return RK_None;
1094 // We look for a sequence of shuffles and adds like the following matching one
1095 // fadd, shuffle vector pair at a time.
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
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;
1117 Value *NextRdxOp;
1118 ShuffleVectorInst *Shuffle;
1119 std::tie(NextRdxOp, Shuffle) =
1120 getShuffleAndOtherOprd(RDLevel->LHS, RDLevel->RHS);
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;
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);
1134 SmallVector<int, 16> Mask = Shuffle->getShuffleMask();
1135 if (ShuffleMask != Mask)
1136 return RK_None;
1138 RdxOp = dyn_cast<Instruction>(NextRdxOp);
1139 NumVecElemsRemain /= 2;
1140 MaskStart *= 2;
1143 Opcode = RD->Opcode;
1144 Ty = VecTy;
1145 return RD->Kind;
1148 int TargetTransformInfo::getInstructionThroughput(const Instruction *I) const {
1149 switch (I->getOpcode()) {
1150 case Instruction::GetElementPtr:
1151 return getUserCost(I);
1153 case Instruction::Ret:
1154 case Instruction::PHI:
1155 case Instruction::Br: {
1156 return getCFInstrCost(I->getOpcode());
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);
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);
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);
1199 case Instruction::ICmp:
1200 case Instruction::FCmp: {
1201 Type *ValTy = I->getOperand(0)->getType();
1202 return getCmpSelInstrCost(I->getOpcode(), ValTy, I->getType(), I);
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);
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);
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);
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();
1240 // Try to match a reduction sequence (series of shufflevector and vector
1241 // adds followed by a extractelement).
1242 unsigned ReduxOpCode;
1243 Type *ReduxType;
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;
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;
1277 return getVectorInstrCost(I->getOpcode(),
1278 EEI->getOperand(0)->getType(), Idx);
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);
1289 case Instruction::ExtractValue:
1290 return 0; // Model all ExtractValue nodes as free.
1291 case Instruction::ShuffleVector: {
1292 const ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1293 Type *Ty = Shuffle->getType();
1294 Type *SrcTy = Shuffle->getOperand(0)->getType();
1296 // TODO: Identify and add costs for insert subvector, etc.
1297 int SubIndex;
1298 if (Shuffle->isExtractSubvectorMask(SubIndex))
1299 return TTIImpl->getShuffleCost(SK_ExtractSubvector, SrcTy, SubIndex, Ty);
1301 if (Shuffle->changesLength())
1302 return -1;
1304 if (Shuffle->isIdentity())
1305 return 0;
1307 if (Shuffle->isReverse())
1308 return TTIImpl->getShuffleCost(SK_Reverse, Ty, 0, nullptr);
1310 if (Shuffle->isSelect())
1311 return TTIImpl->getShuffleCost(SK_Select, Ty, 0, nullptr);
1313 if (Shuffle->isTranspose())
1314 return TTIImpl->getShuffleCost(SK_Transpose, Ty, 0, nullptr);
1316 if (Shuffle->isZeroEltSplat())
1317 return TTIImpl->getShuffleCost(SK_Broadcast, Ty, 0, nullptr);
1319 if (Shuffle->isSingleSource())
1320 return TTIImpl->getShuffleCost(SK_PermuteSingleSrc, Ty, 0, nullptr);
1322 return TTIImpl->getShuffleCost(SK_PermuteTwoSrc, Ty, 0, nullptr);
1324 case Instruction::Call:
1325 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1326 SmallVector<Value *, 4> Args(II->arg_operands());
1328 FastMathFlags FMF;
1329 if (auto *FPMO = dyn_cast<FPMathOperator>(II))
1330 FMF = FPMO->getFastMathFlags();
1332 return getIntrinsicInstrCost(II->getIntrinsicID(), II->getType(),
1333 Args, FMF);
1335 return -1;
1336 default:
1337 // We don't have any information on this instruction.
1338 return -1;
1342 TargetTransformInfo::Concept::~Concept() {}
1344 TargetIRAnalysis::TargetIRAnalysis() : TTICallback(&getDefaultTTI) {}
1346 TargetIRAnalysis::TargetIRAnalysis(
1347 std::function<Result(const Function &)> TTICallback)
1348 : TTICallback(std::move(TTICallback)) {}
1350 TargetIRAnalysis::Result TargetIRAnalysis::run(const Function &F,
1351 FunctionAnalysisManager &) {
1352 return TTICallback(F);
1355 AnalysisKey TargetIRAnalysis::Key;
1357 TargetIRAnalysis::Result TargetIRAnalysis::getDefaultTTI(const Function &F) {
1358 return Result(F.getParent()->getDataLayout());
1361 // Register the basic pass.
1362 INITIALIZE_PASS(TargetTransformInfoWrapperPass, "tti",
1363 "Target Transform Information", false, true)
1364 char TargetTransformInfoWrapperPass::ID = 0;
1366 void TargetTransformInfoWrapperPass::anchor() {}
1368 TargetTransformInfoWrapperPass::TargetTransformInfoWrapperPass()
1369 : ImmutablePass(ID) {
1370 initializeTargetTransformInfoWrapperPassPass(
1371 *PassRegistry::getPassRegistry());
1374 TargetTransformInfoWrapperPass::TargetTransformInfoWrapperPass(
1375 TargetIRAnalysis TIRA)
1376 : ImmutablePass(ID), TIRA(std::move(TIRA)) {
1377 initializeTargetTransformInfoWrapperPassPass(
1378 *PassRegistry::getPassRegistry());
1381 TargetTransformInfo &TargetTransformInfoWrapperPass::getTTI(const Function &F) {
1382 FunctionAnalysisManager DummyFAM;
1383 TTI = TIRA.run(F, DummyFAM);
1384 return *TTI;
1387 ImmutablePass *
1388 llvm::createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA) {
1389 return new TargetTransformInfoWrapperPass(std::move(TIRA));