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