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