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