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