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