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(
993       cast<FixedVectorType>(SI->getType())->getNumElements(), -1);
994 
995   // Build a mask of 0, 2, ... (left) or 1, 3, ... (right) depending on whether
996   // we look at the left or right side.
997   for (unsigned i = 0, e = (1 << Level), val = !IsLeft; i != e; ++i, val += 2)
998     Mask[i] = val;
999 
1000   ArrayRef<int> ActualMask = SI->getShuffleMask();
1001   return Mask == ActualMask;
1002 }
1003 
1004 static Optional<TTI::ReductionData> getReductionData(Instruction *I) {
1005   Value *L, *R;
1006   if (m_BinOp(m_Value(L), m_Value(R)).match(I))
1007     return TTI::ReductionData(TTI::RK_Arithmetic, I->getOpcode(), L, R);
1008   if (auto *SI = dyn_cast<SelectInst>(I)) {
1009     if (m_SMin(m_Value(L), m_Value(R)).match(SI) ||
1010         m_SMax(m_Value(L), m_Value(R)).match(SI) ||
1011         m_OrdFMin(m_Value(L), m_Value(R)).match(SI) ||
1012         m_OrdFMax(m_Value(L), m_Value(R)).match(SI) ||
1013         m_UnordFMin(m_Value(L), m_Value(R)).match(SI) ||
1014         m_UnordFMax(m_Value(L), m_Value(R)).match(SI)) {
1015       auto *CI = cast<CmpInst>(SI->getCondition());
1016       return TTI::ReductionData(TTI::RK_MinMax, CI->getOpcode(), L, R);
1017     }
1018     if (m_UMin(m_Value(L), m_Value(R)).match(SI) ||
1019         m_UMax(m_Value(L), m_Value(R)).match(SI)) {
1020       auto *CI = cast<CmpInst>(SI->getCondition());
1021       return TTI::ReductionData(TTI::RK_UnsignedMinMax, CI->getOpcode(), L, R);
1022     }
1023   }
1024   return llvm::None;
1025 }
1026 
1027 static TTI::ReductionKind matchPairwiseReductionAtLevel(Instruction *I,
1028                                                         unsigned Level,
1029                                                         unsigned NumLevels) {
1030   // Match one level of pairwise operations.
1031   // %rdx.shuf.0.0 = shufflevector <4 x float> %rdx, <4 x float> undef,
1032   //       <4 x i32> <i32 0, i32 2 , i32 undef, i32 undef>
1033   // %rdx.shuf.0.1 = shufflevector <4 x float> %rdx, <4 x float> undef,
1034   //       <4 x i32> <i32 1, i32 3, i32 undef, i32 undef>
1035   // %bin.rdx.0 = fadd <4 x float> %rdx.shuf.0.0, %rdx.shuf.0.1
1036   if (!I)
1037     return TTI::RK_None;
1038 
1039   assert(I->getType()->isVectorTy() && "Expecting a vector type");
1040 
1041   Optional<TTI::ReductionData> RD = getReductionData(I);
1042   if (!RD)
1043     return TTI::RK_None;
1044 
1045   ShuffleVectorInst *LS = dyn_cast<ShuffleVectorInst>(RD->LHS);
1046   if (!LS && Level)
1047     return TTI::RK_None;
1048   ShuffleVectorInst *RS = dyn_cast<ShuffleVectorInst>(RD->RHS);
1049   if (!RS && Level)
1050     return TTI::RK_None;
1051 
1052   // On level 0 we can omit one shufflevector instruction.
1053   if (!Level && !RS && !LS)
1054     return TTI::RK_None;
1055 
1056   // Shuffle inputs must match.
1057   Value *NextLevelOpL = LS ? LS->getOperand(0) : nullptr;
1058   Value *NextLevelOpR = RS ? RS->getOperand(0) : nullptr;
1059   Value *NextLevelOp = nullptr;
1060   if (NextLevelOpR && NextLevelOpL) {
1061     // If we have two shuffles their operands must match.
1062     if (NextLevelOpL != NextLevelOpR)
1063       return TTI::RK_None;
1064 
1065     NextLevelOp = NextLevelOpL;
1066   } else if (Level == 0 && (NextLevelOpR || NextLevelOpL)) {
1067     // On the first level we can omit the shufflevector <0, undef,...>. So the
1068     // input to the other shufflevector <1, undef> must match with one of the
1069     // inputs to the current binary operation.
1070     // Example:
1071     //  %NextLevelOpL = shufflevector %R, <1, undef ...>
1072     //  %BinOp        = fadd          %NextLevelOpL, %R
1073     if (NextLevelOpL && NextLevelOpL != RD->RHS)
1074       return TTI::RK_None;
1075     else if (NextLevelOpR && NextLevelOpR != RD->LHS)
1076       return TTI::RK_None;
1077 
1078     NextLevelOp = NextLevelOpL ? RD->RHS : RD->LHS;
1079   } else
1080     return TTI::RK_None;
1081 
1082   // Check that the next levels binary operation exists and matches with the
1083   // current one.
1084   if (Level + 1 != NumLevels) {
1085     if (!isa<Instruction>(NextLevelOp))
1086       return TTI::RK_None;
1087     Optional<TTI::ReductionData> NextLevelRD =
1088         getReductionData(cast<Instruction>(NextLevelOp));
1089     if (!NextLevelRD || !RD->hasSameData(*NextLevelRD))
1090       return TTI::RK_None;
1091   }
1092 
1093   // Shuffle mask for pairwise operation must match.
1094   if (matchPairwiseShuffleMask(LS, /*IsLeft=*/true, Level)) {
1095     if (!matchPairwiseShuffleMask(RS, /*IsLeft=*/false, Level))
1096       return TTI::RK_None;
1097   } else if (matchPairwiseShuffleMask(RS, /*IsLeft=*/true, Level)) {
1098     if (!matchPairwiseShuffleMask(LS, /*IsLeft=*/false, Level))
1099       return TTI::RK_None;
1100   } else {
1101     return TTI::RK_None;
1102   }
1103 
1104   if (++Level == NumLevels)
1105     return RD->Kind;
1106 
1107   // Match next level.
1108   return matchPairwiseReductionAtLevel(dyn_cast<Instruction>(NextLevelOp), Level,
1109                                        NumLevels);
1110 }
1111 
1112 TTI::ReductionKind TTI::matchPairwiseReduction(
1113   const ExtractElementInst *ReduxRoot, unsigned &Opcode, VectorType *&Ty) {
1114   if (!EnableReduxCost)
1115     return TTI::RK_None;
1116 
1117   // Need to extract the first element.
1118   ConstantInt *CI = dyn_cast<ConstantInt>(ReduxRoot->getOperand(1));
1119   unsigned Idx = ~0u;
1120   if (CI)
1121     Idx = CI->getZExtValue();
1122   if (Idx != 0)
1123     return TTI::RK_None;
1124 
1125   auto *RdxStart = dyn_cast<Instruction>(ReduxRoot->getOperand(0));
1126   if (!RdxStart)
1127     return TTI::RK_None;
1128   Optional<TTI::ReductionData> RD = getReductionData(RdxStart);
1129   if (!RD)
1130     return TTI::RK_None;
1131 
1132   auto *VecTy = cast<FixedVectorType>(RdxStart->getType());
1133   unsigned NumVecElems = VecTy->getNumElements();
1134   if (!isPowerOf2_32(NumVecElems))
1135     return TTI::RK_None;
1136 
1137   // We look for a sequence of shuffle,shuffle,add triples like the following
1138   // that builds a pairwise reduction tree.
1139   //
1140   //  (X0, X1, X2, X3)
1141   //   (X0 + X1, X2 + X3, undef, undef)
1142   //    ((X0 + X1) + (X2 + X3), undef, undef, undef)
1143   //
1144   // %rdx.shuf.0.0 = shufflevector <4 x float> %rdx, <4 x float> undef,
1145   //       <4 x i32> <i32 0, i32 2 , i32 undef, i32 undef>
1146   // %rdx.shuf.0.1 = shufflevector <4 x float> %rdx, <4 x float> undef,
1147   //       <4 x i32> <i32 1, i32 3, i32 undef, i32 undef>
1148   // %bin.rdx.0 = fadd <4 x float> %rdx.shuf.0.0, %rdx.shuf.0.1
1149   // %rdx.shuf.1.0 = shufflevector <4 x float> %bin.rdx.0, <4 x float> undef,
1150   //       <4 x i32> <i32 0, i32 undef, i32 undef, i32 undef>
1151   // %rdx.shuf.1.1 = shufflevector <4 x float> %bin.rdx.0, <4 x float> undef,
1152   //       <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef>
1153   // %bin.rdx8 = fadd <4 x float> %rdx.shuf.1.0, %rdx.shuf.1.1
1154   // %r = extractelement <4 x float> %bin.rdx8, i32 0
1155   if (matchPairwiseReductionAtLevel(RdxStart, 0, Log2_32(NumVecElems)) ==
1156       TTI::RK_None)
1157     return TTI::RK_None;
1158 
1159   Opcode = RD->Opcode;
1160   Ty = VecTy;
1161 
1162   return RD->Kind;
1163 }
1164 
1165 static std::pair<Value *, ShuffleVectorInst *>
1166 getShuffleAndOtherOprd(Value *L, Value *R) {
1167   ShuffleVectorInst *S = nullptr;
1168 
1169   if ((S = dyn_cast<ShuffleVectorInst>(L)))
1170     return std::make_pair(R, S);
1171 
1172   S = dyn_cast<ShuffleVectorInst>(R);
1173   return std::make_pair(L, S);
1174 }
1175 
1176 TTI::ReductionKind TTI::matchVectorSplittingReduction(
1177   const ExtractElementInst *ReduxRoot, unsigned &Opcode, VectorType *&Ty) {
1178 
1179   if (!EnableReduxCost)
1180     return TTI::RK_None;
1181 
1182   // Need to extract the first element.
1183   ConstantInt *CI = dyn_cast<ConstantInt>(ReduxRoot->getOperand(1));
1184   unsigned Idx = ~0u;
1185   if (CI)
1186     Idx = CI->getZExtValue();
1187   if (Idx != 0)
1188     return TTI::RK_None;
1189 
1190   auto *RdxStart = dyn_cast<Instruction>(ReduxRoot->getOperand(0));
1191   if (!RdxStart)
1192     return TTI::RK_None;
1193   Optional<TTI::ReductionData> RD = getReductionData(RdxStart);
1194   if (!RD)
1195     return TTI::RK_None;
1196 
1197   auto *VecTy = cast<FixedVectorType>(ReduxRoot->getOperand(0)->getType());
1198   unsigned NumVecElems = VecTy->getNumElements();
1199   if (!isPowerOf2_32(NumVecElems))
1200     return TTI::RK_None;
1201 
1202   // We look for a sequence of shuffles and adds like the following matching one
1203   // fadd, shuffle vector pair at a time.
1204   //
1205   // %rdx.shuf = shufflevector <4 x float> %rdx, <4 x float> undef,
1206   //                           <4 x i32> <i32 2, i32 3, i32 undef, i32 undef>
1207   // %bin.rdx = fadd <4 x float> %rdx, %rdx.shuf
1208   // %rdx.shuf7 = shufflevector <4 x float> %bin.rdx, <4 x float> undef,
1209   //                          <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef>
1210   // %bin.rdx8 = fadd <4 x float> %bin.rdx, %rdx.shuf7
1211   // %r = extractelement <4 x float> %bin.rdx8, i32 0
1212 
1213   unsigned MaskStart = 1;
1214   Instruction *RdxOp = RdxStart;
1215   SmallVector<int, 32> ShuffleMask(NumVecElems, 0);
1216   unsigned NumVecElemsRemain = NumVecElems;
1217   while (NumVecElemsRemain - 1) {
1218     // Check for the right reduction operation.
1219     if (!RdxOp)
1220       return TTI::RK_None;
1221     Optional<TTI::ReductionData> RDLevel = getReductionData(RdxOp);
1222     if (!RDLevel || !RDLevel->hasSameData(*RD))
1223       return TTI::RK_None;
1224 
1225     Value *NextRdxOp;
1226     ShuffleVectorInst *Shuffle;
1227     std::tie(NextRdxOp, Shuffle) =
1228         getShuffleAndOtherOprd(RDLevel->LHS, RDLevel->RHS);
1229 
1230     // Check the current reduction operation and the shuffle use the same value.
1231     if (Shuffle == nullptr)
1232       return TTI::RK_None;
1233     if (Shuffle->getOperand(0) != NextRdxOp)
1234       return TTI::RK_None;
1235 
1236     // Check that shuffle masks matches.
1237     for (unsigned j = 0; j != MaskStart; ++j)
1238       ShuffleMask[j] = MaskStart + j;
1239     // Fill the rest of the mask with -1 for undef.
1240     std::fill(&ShuffleMask[MaskStart], ShuffleMask.end(), -1);
1241 
1242     ArrayRef<int> Mask = Shuffle->getShuffleMask();
1243     if (ShuffleMask != Mask)
1244       return TTI::RK_None;
1245 
1246     RdxOp = dyn_cast<Instruction>(NextRdxOp);
1247     NumVecElemsRemain /= 2;
1248     MaskStart *= 2;
1249   }
1250 
1251   Opcode = RD->Opcode;
1252   Ty = VecTy;
1253   return RD->Kind;
1254 }
1255 
1256 int TargetTransformInfo::getInstructionThroughput(const Instruction *I) const {
1257   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
1258 
1259   switch (I->getOpcode()) {
1260   case Instruction::GetElementPtr:
1261   case Instruction::Ret:
1262   case Instruction::PHI:
1263   case Instruction::Br:
1264   case Instruction::Add:
1265   case Instruction::FAdd:
1266   case Instruction::Sub:
1267   case Instruction::FSub:
1268   case Instruction::Mul:
1269   case Instruction::FMul:
1270   case Instruction::UDiv:
1271   case Instruction::SDiv:
1272   case Instruction::FDiv:
1273   case Instruction::URem:
1274   case Instruction::SRem:
1275   case Instruction::FRem:
1276   case Instruction::Shl:
1277   case Instruction::LShr:
1278   case Instruction::AShr:
1279   case Instruction::And:
1280   case Instruction::Or:
1281   case Instruction::Xor:
1282   case Instruction::FNeg:
1283   case Instruction::Select:
1284   case Instruction::ICmp:
1285   case Instruction::FCmp:
1286   case Instruction::Store:
1287   case Instruction::Load:
1288   case Instruction::ZExt:
1289   case Instruction::SExt:
1290   case Instruction::FPToUI:
1291   case Instruction::FPToSI:
1292   case Instruction::FPExt:
1293   case Instruction::PtrToInt:
1294   case Instruction::IntToPtr:
1295   case Instruction::SIToFP:
1296   case Instruction::UIToFP:
1297   case Instruction::Trunc:
1298   case Instruction::FPTrunc:
1299   case Instruction::BitCast:
1300   case Instruction::AddrSpaceCast:
1301   case Instruction::ExtractElement:
1302   case Instruction::InsertElement:
1303   case Instruction::ExtractValue:
1304   case Instruction::ShuffleVector:
1305   case Instruction::Call:
1306     return getUserCost(I, CostKind);
1307   default:
1308     // We don't have any information on this instruction.
1309     return -1;
1310   }
1311 }
1312 
1313 TargetTransformInfo::Concept::~Concept() {}
1314 
1315 TargetIRAnalysis::TargetIRAnalysis() : TTICallback(&getDefaultTTI) {}
1316 
1317 TargetIRAnalysis::TargetIRAnalysis(
1318     std::function<Result(const Function &)> TTICallback)
1319     : TTICallback(std::move(TTICallback)) {}
1320 
1321 TargetIRAnalysis::Result TargetIRAnalysis::run(const Function &F,
1322                                                FunctionAnalysisManager &) {
1323   return TTICallback(F);
1324 }
1325 
1326 AnalysisKey TargetIRAnalysis::Key;
1327 
1328 TargetIRAnalysis::Result TargetIRAnalysis::getDefaultTTI(const Function &F) {
1329   return Result(F.getParent()->getDataLayout());
1330 }
1331 
1332 // Register the basic pass.
1333 INITIALIZE_PASS(TargetTransformInfoWrapperPass, "tti",
1334                 "Target Transform Information", false, true)
1335 char TargetTransformInfoWrapperPass::ID = 0;
1336 
1337 void TargetTransformInfoWrapperPass::anchor() {}
1338 
1339 TargetTransformInfoWrapperPass::TargetTransformInfoWrapperPass()
1340     : ImmutablePass(ID) {
1341   initializeTargetTransformInfoWrapperPassPass(
1342       *PassRegistry::getPassRegistry());
1343 }
1344 
1345 TargetTransformInfoWrapperPass::TargetTransformInfoWrapperPass(
1346     TargetIRAnalysis TIRA)
1347     : ImmutablePass(ID), TIRA(std::move(TIRA)) {
1348   initializeTargetTransformInfoWrapperPassPass(
1349       *PassRegistry::getPassRegistry());
1350 }
1351 
1352 TargetTransformInfo &TargetTransformInfoWrapperPass::getTTI(const Function &F) {
1353   FunctionAnalysisManager DummyFAM;
1354   TTI = TIRA.run(F, DummyFAM);
1355   return *TTI;
1356 }
1357 
1358 ImmutablePass *
1359 llvm::createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA) {
1360   return new TargetTransformInfoWrapperPass(std::move(TIRA));
1361 }
1362