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