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