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