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