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