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