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