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                                         int Index, VectorType *SubTp) const {
710   int Cost = TTIImpl->getShuffleCost(Kind, Ty, Index, SubTp);
711   assert(Cost >= 0 && "TTI should not produce negative costs!");
712   return Cost;
713 }
714 
715 TTI::CastContextHint
716 TargetTransformInfo::getCastContextHint(const Instruction *I) {
717   if (!I)
718     return CastContextHint::None;
719 
720   auto getLoadStoreKind = [](const Value *V, unsigned LdStOp, unsigned MaskedOp,
721                              unsigned GatScatOp) {
722     const Instruction *I = dyn_cast<Instruction>(V);
723     if (!I)
724       return CastContextHint::None;
725 
726     if (I->getOpcode() == LdStOp)
727       return CastContextHint::Normal;
728 
729     if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
730       if (II->getIntrinsicID() == MaskedOp)
731         return TTI::CastContextHint::Masked;
732       if (II->getIntrinsicID() == GatScatOp)
733         return TTI::CastContextHint::GatherScatter;
734     }
735 
736     return TTI::CastContextHint::None;
737   };
738 
739   switch (I->getOpcode()) {
740   case Instruction::ZExt:
741   case Instruction::SExt:
742   case Instruction::FPExt:
743     return getLoadStoreKind(I->getOperand(0), Instruction::Load,
744                             Intrinsic::masked_load, Intrinsic::masked_gather);
745   case Instruction::Trunc:
746   case Instruction::FPTrunc:
747     if (I->hasOneUse())
748       return getLoadStoreKind(*I->user_begin(), Instruction::Store,
749                               Intrinsic::masked_store,
750                               Intrinsic::masked_scatter);
751     break;
752   default:
753     return CastContextHint::None;
754   }
755 
756   return TTI::CastContextHint::None;
757 }
758 
759 int TargetTransformInfo::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
760                                           CastContextHint CCH,
761                                           TTI::TargetCostKind CostKind,
762                                           const Instruction *I) const {
763   assert((I == nullptr || I->getOpcode() == Opcode) &&
764          "Opcode should reflect passed instruction.");
765   int Cost = TTIImpl->getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
766   assert(Cost >= 0 && "TTI should not produce negative costs!");
767   return Cost;
768 }
769 
770 int TargetTransformInfo::getExtractWithExtendCost(unsigned Opcode, Type *Dst,
771                                                   VectorType *VecTy,
772                                                   unsigned Index) const {
773   int Cost = TTIImpl->getExtractWithExtendCost(Opcode, Dst, VecTy, Index);
774   assert(Cost >= 0 && "TTI should not produce negative costs!");
775   return Cost;
776 }
777 
778 int TargetTransformInfo::getCFInstrCost(unsigned Opcode,
779                                         TTI::TargetCostKind CostKind) const {
780   int Cost = TTIImpl->getCFInstrCost(Opcode, CostKind);
781   assert(Cost >= 0 && "TTI should not produce negative costs!");
782   return Cost;
783 }
784 
785 int TargetTransformInfo::getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
786                                             Type *CondTy,
787                                             CmpInst::Predicate VecPred,
788                                             TTI::TargetCostKind CostKind,
789                                             const Instruction *I) const {
790   assert((I == nullptr || I->getOpcode() == Opcode) &&
791          "Opcode should reflect passed instruction.");
792   int Cost =
793       TTIImpl->getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind, I);
794   assert(Cost >= 0 && "TTI should not produce negative costs!");
795   return Cost;
796 }
797 
798 int TargetTransformInfo::getVectorInstrCost(unsigned Opcode, Type *Val,
799                                             unsigned Index) const {
800   int Cost = TTIImpl->getVectorInstrCost(Opcode, Val, Index);
801   assert(Cost >= 0 && "TTI should not produce negative costs!");
802   return Cost;
803 }
804 
805 int TargetTransformInfo::getMemoryOpCost(unsigned Opcode, Type *Src,
806                                          Align Alignment, unsigned AddressSpace,
807                                          TTI::TargetCostKind CostKind,
808                                          const Instruction *I) const {
809   assert((I == nullptr || I->getOpcode() == Opcode) &&
810          "Opcode should reflect passed instruction.");
811   int Cost = TTIImpl->getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
812                                       CostKind, I);
813   assert(Cost >= 0 && "TTI should not produce negative costs!");
814   return Cost;
815 }
816 
817 int TargetTransformInfo::getMaskedMemoryOpCost(
818     unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace,
819     TTI::TargetCostKind CostKind) const {
820   int Cost =
821       TTIImpl->getMaskedMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
822                                      CostKind);
823   assert(Cost >= 0 && "TTI should not produce negative costs!");
824   return Cost;
825 }
826 
827 int TargetTransformInfo::getGatherScatterOpCost(
828     unsigned Opcode, Type *DataTy, const Value *Ptr, bool VariableMask,
829     Align Alignment, TTI::TargetCostKind CostKind, const Instruction *I) const {
830   int Cost = TTIImpl->getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask,
831                                              Alignment, CostKind, I);
832   assert(Cost >= 0 && "TTI should not produce negative costs!");
833   return Cost;
834 }
835 
836 int TargetTransformInfo::getInterleavedMemoryOpCost(
837     unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
838     Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
839     bool UseMaskForCond, bool UseMaskForGaps) const {
840   int Cost = TTIImpl->getInterleavedMemoryOpCost(
841       Opcode, VecTy, Factor, Indices, Alignment, AddressSpace, CostKind,
842       UseMaskForCond, UseMaskForGaps);
843   assert(Cost >= 0 && "TTI should not produce negative costs!");
844   return Cost;
845 }
846 
847 int
848 TargetTransformInfo::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
849                                            TTI::TargetCostKind CostKind) const {
850   int Cost = TTIImpl->getIntrinsicInstrCost(ICA, CostKind);
851   assert(Cost >= 0 && "TTI should not produce negative costs!");
852   return Cost;
853 }
854 
855 int TargetTransformInfo::getCallInstrCost(Function *F, Type *RetTy,
856                                           ArrayRef<Type *> Tys,
857                                           TTI::TargetCostKind CostKind) const {
858   int Cost = TTIImpl->getCallInstrCost(F, RetTy, Tys, CostKind);
859   assert(Cost >= 0 && "TTI should not produce negative costs!");
860   return Cost;
861 }
862 
863 unsigned TargetTransformInfo::getNumberOfParts(Type *Tp) const {
864   return TTIImpl->getNumberOfParts(Tp);
865 }
866 
867 int TargetTransformInfo::getAddressComputationCost(Type *Tp,
868                                                    ScalarEvolution *SE,
869                                                    const SCEV *Ptr) const {
870   int Cost = TTIImpl->getAddressComputationCost(Tp, SE, Ptr);
871   assert(Cost >= 0 && "TTI should not produce negative costs!");
872   return Cost;
873 }
874 
875 int TargetTransformInfo::getMemcpyCost(const Instruction *I) const {
876   int Cost = TTIImpl->getMemcpyCost(I);
877   assert(Cost >= 0 && "TTI should not produce negative costs!");
878   return Cost;
879 }
880 
881 int TargetTransformInfo::getArithmeticReductionCost(unsigned Opcode,
882                                                     VectorType *Ty,
883                                                     bool IsPairwiseForm,
884                                                     TTI::TargetCostKind CostKind) const {
885   int Cost = TTIImpl->getArithmeticReductionCost(Opcode, Ty, IsPairwiseForm,
886                                                  CostKind);
887   assert(Cost >= 0 && "TTI should not produce negative costs!");
888   return Cost;
889 }
890 
891 int TargetTransformInfo::getMinMaxReductionCost(
892     VectorType *Ty, VectorType *CondTy, bool IsPairwiseForm, bool IsUnsigned,
893     TTI::TargetCostKind CostKind) const {
894   int Cost =
895       TTIImpl->getMinMaxReductionCost(Ty, CondTy, IsPairwiseForm, IsUnsigned,
896                                       CostKind);
897   assert(Cost >= 0 && "TTI should not produce negative costs!");
898   return Cost;
899 }
900 
901 InstructionCost TargetTransformInfo::getExtendedAddReductionCost(
902     bool IsMLA, bool IsUnsigned, Type *ResTy, VectorType *Ty,
903     TTI::TargetCostKind CostKind) const {
904   return TTIImpl->getExtendedAddReductionCost(IsMLA, IsUnsigned, ResTy, Ty,
905                                               CostKind);
906 }
907 
908 unsigned
909 TargetTransformInfo::getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) const {
910   return TTIImpl->getCostOfKeepingLiveOverCall(Tys);
911 }
912 
913 bool TargetTransformInfo::getTgtMemIntrinsic(IntrinsicInst *Inst,
914                                              MemIntrinsicInfo &Info) const {
915   return TTIImpl->getTgtMemIntrinsic(Inst, Info);
916 }
917 
918 unsigned TargetTransformInfo::getAtomicMemIntrinsicMaxElementSize() const {
919   return TTIImpl->getAtomicMemIntrinsicMaxElementSize();
920 }
921 
922 Value *TargetTransformInfo::getOrCreateResultFromMemIntrinsic(
923     IntrinsicInst *Inst, Type *ExpectedType) const {
924   return TTIImpl->getOrCreateResultFromMemIntrinsic(Inst, ExpectedType);
925 }
926 
927 Type *TargetTransformInfo::getMemcpyLoopLoweringType(
928     LLVMContext &Context, Value *Length, unsigned SrcAddrSpace,
929     unsigned DestAddrSpace, unsigned SrcAlign, unsigned DestAlign) const {
930   return TTIImpl->getMemcpyLoopLoweringType(Context, Length, SrcAddrSpace,
931                                             DestAddrSpace, SrcAlign, DestAlign);
932 }
933 
934 void TargetTransformInfo::getMemcpyLoopResidualLoweringType(
935     SmallVectorImpl<Type *> &OpsOut, LLVMContext &Context,
936     unsigned RemainingBytes, unsigned SrcAddrSpace, unsigned DestAddrSpace,
937     unsigned SrcAlign, unsigned DestAlign) const {
938   TTIImpl->getMemcpyLoopResidualLoweringType(OpsOut, Context, RemainingBytes,
939                                              SrcAddrSpace, DestAddrSpace,
940                                              SrcAlign, DestAlign);
941 }
942 
943 bool TargetTransformInfo::areInlineCompatible(const Function *Caller,
944                                               const Function *Callee) const {
945   return TTIImpl->areInlineCompatible(Caller, Callee);
946 }
947 
948 bool TargetTransformInfo::areFunctionArgsABICompatible(
949     const Function *Caller, const Function *Callee,
950     SmallPtrSetImpl<Argument *> &Args) const {
951   return TTIImpl->areFunctionArgsABICompatible(Caller, Callee, Args);
952 }
953 
954 bool TargetTransformInfo::isIndexedLoadLegal(MemIndexedMode Mode,
955                                              Type *Ty) const {
956   return TTIImpl->isIndexedLoadLegal(Mode, Ty);
957 }
958 
959 bool TargetTransformInfo::isIndexedStoreLegal(MemIndexedMode Mode,
960                                               Type *Ty) const {
961   return TTIImpl->isIndexedStoreLegal(Mode, Ty);
962 }
963 
964 unsigned TargetTransformInfo::getLoadStoreVecRegBitWidth(unsigned AS) const {
965   return TTIImpl->getLoadStoreVecRegBitWidth(AS);
966 }
967 
968 bool TargetTransformInfo::isLegalToVectorizeLoad(LoadInst *LI) const {
969   return TTIImpl->isLegalToVectorizeLoad(LI);
970 }
971 
972 bool TargetTransformInfo::isLegalToVectorizeStore(StoreInst *SI) const {
973   return TTIImpl->isLegalToVectorizeStore(SI);
974 }
975 
976 bool TargetTransformInfo::isLegalToVectorizeLoadChain(
977     unsigned ChainSizeInBytes, Align Alignment, unsigned AddrSpace) const {
978   return TTIImpl->isLegalToVectorizeLoadChain(ChainSizeInBytes, Alignment,
979                                               AddrSpace);
980 }
981 
982 bool TargetTransformInfo::isLegalToVectorizeStoreChain(
983     unsigned ChainSizeInBytes, Align Alignment, unsigned AddrSpace) const {
984   return TTIImpl->isLegalToVectorizeStoreChain(ChainSizeInBytes, Alignment,
985                                                AddrSpace);
986 }
987 
988 bool TargetTransformInfo::isLegalToVectorizeReduction(
989     RecurrenceDescriptor RdxDesc, ElementCount VF) const {
990   return TTIImpl->isLegalToVectorizeReduction(RdxDesc, VF);
991 }
992 
993 unsigned TargetTransformInfo::getLoadVectorFactor(unsigned VF,
994                                                   unsigned LoadSize,
995                                                   unsigned ChainSizeInBytes,
996                                                   VectorType *VecTy) const {
997   return TTIImpl->getLoadVectorFactor(VF, LoadSize, ChainSizeInBytes, VecTy);
998 }
999 
1000 unsigned TargetTransformInfo::getStoreVectorFactor(unsigned VF,
1001                                                    unsigned StoreSize,
1002                                                    unsigned ChainSizeInBytes,
1003                                                    VectorType *VecTy) const {
1004   return TTIImpl->getStoreVectorFactor(VF, StoreSize, ChainSizeInBytes, VecTy);
1005 }
1006 
1007 bool TargetTransformInfo::preferInLoopReduction(unsigned Opcode, Type *Ty,
1008                                                 ReductionFlags Flags) const {
1009   return TTIImpl->preferInLoopReduction(Opcode, Ty, Flags);
1010 }
1011 
1012 bool TargetTransformInfo::preferPredicatedReductionSelect(
1013     unsigned Opcode, Type *Ty, ReductionFlags Flags) const {
1014   return TTIImpl->preferPredicatedReductionSelect(Opcode, Ty, Flags);
1015 }
1016 
1017 bool TargetTransformInfo::shouldExpandReduction(const IntrinsicInst *II) const {
1018   return TTIImpl->shouldExpandReduction(II);
1019 }
1020 
1021 unsigned TargetTransformInfo::getGISelRematGlobalCost() const {
1022   return TTIImpl->getGISelRematGlobalCost();
1023 }
1024 
1025 bool TargetTransformInfo::supportsScalableVectors() const {
1026   return TTIImpl->supportsScalableVectors();
1027 }
1028 
1029 int TargetTransformInfo::getInstructionLatency(const Instruction *I) const {
1030   return TTIImpl->getInstructionLatency(I);
1031 }
1032 
1033 static bool matchPairwiseShuffleMask(ShuffleVectorInst *SI, bool IsLeft,
1034                                      unsigned Level) {
1035   // We don't need a shuffle if we just want to have element 0 in position 0 of
1036   // the vector.
1037   if (!SI && Level == 0 && IsLeft)
1038     return true;
1039   else if (!SI)
1040     return false;
1041 
1042   SmallVector<int, 32> Mask(
1043       cast<FixedVectorType>(SI->getType())->getNumElements(), -1);
1044 
1045   // Build a mask of 0, 2, ... (left) or 1, 3, ... (right) depending on whether
1046   // we look at the left or right side.
1047   for (unsigned i = 0, e = (1 << Level), val = !IsLeft; i != e; ++i, val += 2)
1048     Mask[i] = val;
1049 
1050   ArrayRef<int> ActualMask = SI->getShuffleMask();
1051   return Mask == ActualMask;
1052 }
1053 
1054 static Optional<TTI::ReductionData> getReductionData(Instruction *I) {
1055   Value *L, *R;
1056   if (m_BinOp(m_Value(L), m_Value(R)).match(I))
1057     return TTI::ReductionData(TTI::RK_Arithmetic, I->getOpcode(), L, R);
1058   if (auto *SI = dyn_cast<SelectInst>(I)) {
1059     if (m_SMin(m_Value(L), m_Value(R)).match(SI) ||
1060         m_SMax(m_Value(L), m_Value(R)).match(SI) ||
1061         m_OrdFMin(m_Value(L), m_Value(R)).match(SI) ||
1062         m_OrdFMax(m_Value(L), m_Value(R)).match(SI) ||
1063         m_UnordFMin(m_Value(L), m_Value(R)).match(SI) ||
1064         m_UnordFMax(m_Value(L), m_Value(R)).match(SI)) {
1065       auto *CI = cast<CmpInst>(SI->getCondition());
1066       return TTI::ReductionData(TTI::RK_MinMax, CI->getOpcode(), L, R);
1067     }
1068     if (m_UMin(m_Value(L), m_Value(R)).match(SI) ||
1069         m_UMax(m_Value(L), m_Value(R)).match(SI)) {
1070       auto *CI = cast<CmpInst>(SI->getCondition());
1071       return TTI::ReductionData(TTI::RK_UnsignedMinMax, CI->getOpcode(), L, R);
1072     }
1073   }
1074   return llvm::None;
1075 }
1076 
1077 static TTI::ReductionKind matchPairwiseReductionAtLevel(Instruction *I,
1078                                                         unsigned Level,
1079                                                         unsigned NumLevels) {
1080   // Match one level of pairwise operations.
1081   // %rdx.shuf.0.0 = shufflevector <4 x float> %rdx, <4 x float> undef,
1082   //       <4 x i32> <i32 0, i32 2 , i32 undef, i32 undef>
1083   // %rdx.shuf.0.1 = shufflevector <4 x float> %rdx, <4 x float> undef,
1084   //       <4 x i32> <i32 1, i32 3, i32 undef, i32 undef>
1085   // %bin.rdx.0 = fadd <4 x float> %rdx.shuf.0.0, %rdx.shuf.0.1
1086   if (!I)
1087     return TTI::RK_None;
1088 
1089   assert(I->getType()->isVectorTy() && "Expecting a vector type");
1090 
1091   Optional<TTI::ReductionData> RD = getReductionData(I);
1092   if (!RD)
1093     return TTI::RK_None;
1094 
1095   ShuffleVectorInst *LS = dyn_cast<ShuffleVectorInst>(RD->LHS);
1096   if (!LS && Level)
1097     return TTI::RK_None;
1098   ShuffleVectorInst *RS = dyn_cast<ShuffleVectorInst>(RD->RHS);
1099   if (!RS && Level)
1100     return TTI::RK_None;
1101 
1102   // On level 0 we can omit one shufflevector instruction.
1103   if (!Level && !RS && !LS)
1104     return TTI::RK_None;
1105 
1106   // Shuffle inputs must match.
1107   Value *NextLevelOpL = LS ? LS->getOperand(0) : nullptr;
1108   Value *NextLevelOpR = RS ? RS->getOperand(0) : nullptr;
1109   Value *NextLevelOp = nullptr;
1110   if (NextLevelOpR && NextLevelOpL) {
1111     // If we have two shuffles their operands must match.
1112     if (NextLevelOpL != NextLevelOpR)
1113       return TTI::RK_None;
1114 
1115     NextLevelOp = NextLevelOpL;
1116   } else if (Level == 0 && (NextLevelOpR || NextLevelOpL)) {
1117     // On the first level we can omit the shufflevector <0, undef,...>. So the
1118     // input to the other shufflevector <1, undef> must match with one of the
1119     // inputs to the current binary operation.
1120     // Example:
1121     //  %NextLevelOpL = shufflevector %R, <1, undef ...>
1122     //  %BinOp        = fadd          %NextLevelOpL, %R
1123     if (NextLevelOpL && NextLevelOpL != RD->RHS)
1124       return TTI::RK_None;
1125     else if (NextLevelOpR && NextLevelOpR != RD->LHS)
1126       return TTI::RK_None;
1127 
1128     NextLevelOp = NextLevelOpL ? RD->RHS : RD->LHS;
1129   } else
1130     return TTI::RK_None;
1131 
1132   // Check that the next levels binary operation exists and matches with the
1133   // current one.
1134   if (Level + 1 != NumLevels) {
1135     if (!isa<Instruction>(NextLevelOp))
1136       return TTI::RK_None;
1137     Optional<TTI::ReductionData> NextLevelRD =
1138         getReductionData(cast<Instruction>(NextLevelOp));
1139     if (!NextLevelRD || !RD->hasSameData(*NextLevelRD))
1140       return TTI::RK_None;
1141   }
1142 
1143   // Shuffle mask for pairwise operation must match.
1144   if (matchPairwiseShuffleMask(LS, /*IsLeft=*/true, Level)) {
1145     if (!matchPairwiseShuffleMask(RS, /*IsLeft=*/false, Level))
1146       return TTI::RK_None;
1147   } else if (matchPairwiseShuffleMask(RS, /*IsLeft=*/true, Level)) {
1148     if (!matchPairwiseShuffleMask(LS, /*IsLeft=*/false, Level))
1149       return TTI::RK_None;
1150   } else {
1151     return TTI::RK_None;
1152   }
1153 
1154   if (++Level == NumLevels)
1155     return RD->Kind;
1156 
1157   // Match next level.
1158   return matchPairwiseReductionAtLevel(dyn_cast<Instruction>(NextLevelOp), Level,
1159                                        NumLevels);
1160 }
1161 
1162 TTI::ReductionKind TTI::matchPairwiseReduction(
1163   const ExtractElementInst *ReduxRoot, unsigned &Opcode, VectorType *&Ty) {
1164   if (!EnableReduxCost)
1165     return TTI::RK_None;
1166 
1167   // Need to extract the first element.
1168   ConstantInt *CI = dyn_cast<ConstantInt>(ReduxRoot->getOperand(1));
1169   unsigned Idx = ~0u;
1170   if (CI)
1171     Idx = CI->getZExtValue();
1172   if (Idx != 0)
1173     return TTI::RK_None;
1174 
1175   auto *RdxStart = dyn_cast<Instruction>(ReduxRoot->getOperand(0));
1176   if (!RdxStart)
1177     return TTI::RK_None;
1178   Optional<TTI::ReductionData> RD = getReductionData(RdxStart);
1179   if (!RD)
1180     return TTI::RK_None;
1181 
1182   auto *VecTy = cast<FixedVectorType>(RdxStart->getType());
1183   unsigned NumVecElems = VecTy->getNumElements();
1184   if (!isPowerOf2_32(NumVecElems))
1185     return TTI::RK_None;
1186 
1187   // We look for a sequence of shuffle,shuffle,add triples like the following
1188   // that builds a pairwise reduction tree.
1189   //
1190   //  (X0, X1, X2, X3)
1191   //   (X0 + X1, X2 + X3, undef, undef)
1192   //    ((X0 + X1) + (X2 + X3), undef, undef, undef)
1193   //
1194   // %rdx.shuf.0.0 = shufflevector <4 x float> %rdx, <4 x float> undef,
1195   //       <4 x i32> <i32 0, i32 2 , i32 undef, i32 undef>
1196   // %rdx.shuf.0.1 = shufflevector <4 x float> %rdx, <4 x float> undef,
1197   //       <4 x i32> <i32 1, i32 3, i32 undef, i32 undef>
1198   // %bin.rdx.0 = fadd <4 x float> %rdx.shuf.0.0, %rdx.shuf.0.1
1199   // %rdx.shuf.1.0 = shufflevector <4 x float> %bin.rdx.0, <4 x float> undef,
1200   //       <4 x i32> <i32 0, i32 undef, i32 undef, i32 undef>
1201   // %rdx.shuf.1.1 = shufflevector <4 x float> %bin.rdx.0, <4 x float> undef,
1202   //       <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef>
1203   // %bin.rdx8 = fadd <4 x float> %rdx.shuf.1.0, %rdx.shuf.1.1
1204   // %r = extractelement <4 x float> %bin.rdx8, i32 0
1205   if (matchPairwiseReductionAtLevel(RdxStart, 0, Log2_32(NumVecElems)) ==
1206       TTI::RK_None)
1207     return TTI::RK_None;
1208 
1209   Opcode = RD->Opcode;
1210   Ty = VecTy;
1211 
1212   return RD->Kind;
1213 }
1214 
1215 static std::pair<Value *, ShuffleVectorInst *>
1216 getShuffleAndOtherOprd(Value *L, Value *R) {
1217   ShuffleVectorInst *S = nullptr;
1218 
1219   if ((S = dyn_cast<ShuffleVectorInst>(L)))
1220     return std::make_pair(R, S);
1221 
1222   S = dyn_cast<ShuffleVectorInst>(R);
1223   return std::make_pair(L, S);
1224 }
1225 
1226 TTI::ReductionKind TTI::matchVectorSplittingReduction(
1227   const ExtractElementInst *ReduxRoot, unsigned &Opcode, VectorType *&Ty) {
1228 
1229   if (!EnableReduxCost)
1230     return TTI::RK_None;
1231 
1232   // Need to extract the first element.
1233   ConstantInt *CI = dyn_cast<ConstantInt>(ReduxRoot->getOperand(1));
1234   unsigned Idx = ~0u;
1235   if (CI)
1236     Idx = CI->getZExtValue();
1237   if (Idx != 0)
1238     return TTI::RK_None;
1239 
1240   auto *RdxStart = dyn_cast<Instruction>(ReduxRoot->getOperand(0));
1241   if (!RdxStart)
1242     return TTI::RK_None;
1243   Optional<TTI::ReductionData> RD = getReductionData(RdxStart);
1244   if (!RD)
1245     return TTI::RK_None;
1246 
1247   auto *VecTy = cast<FixedVectorType>(ReduxRoot->getOperand(0)->getType());
1248   unsigned NumVecElems = VecTy->getNumElements();
1249   if (!isPowerOf2_32(NumVecElems))
1250     return TTI::RK_None;
1251 
1252   // We look for a sequence of shuffles and adds like the following matching one
1253   // fadd, shuffle vector pair at a time.
1254   //
1255   // %rdx.shuf = shufflevector <4 x float> %rdx, <4 x float> undef,
1256   //                           <4 x i32> <i32 2, i32 3, i32 undef, i32 undef>
1257   // %bin.rdx = fadd <4 x float> %rdx, %rdx.shuf
1258   // %rdx.shuf7 = shufflevector <4 x float> %bin.rdx, <4 x float> undef,
1259   //                          <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef>
1260   // %bin.rdx8 = fadd <4 x float> %bin.rdx, %rdx.shuf7
1261   // %r = extractelement <4 x float> %bin.rdx8, i32 0
1262 
1263   unsigned MaskStart = 1;
1264   Instruction *RdxOp = RdxStart;
1265   SmallVector<int, 32> ShuffleMask(NumVecElems, 0);
1266   unsigned NumVecElemsRemain = NumVecElems;
1267   while (NumVecElemsRemain - 1) {
1268     // Check for the right reduction operation.
1269     if (!RdxOp)
1270       return TTI::RK_None;
1271     Optional<TTI::ReductionData> RDLevel = getReductionData(RdxOp);
1272     if (!RDLevel || !RDLevel->hasSameData(*RD))
1273       return TTI::RK_None;
1274 
1275     Value *NextRdxOp;
1276     ShuffleVectorInst *Shuffle;
1277     std::tie(NextRdxOp, Shuffle) =
1278         getShuffleAndOtherOprd(RDLevel->LHS, RDLevel->RHS);
1279 
1280     // Check the current reduction operation and the shuffle use the same value.
1281     if (Shuffle == nullptr)
1282       return TTI::RK_None;
1283     if (Shuffle->getOperand(0) != NextRdxOp)
1284       return TTI::RK_None;
1285 
1286     // Check that shuffle masks matches.
1287     for (unsigned j = 0; j != MaskStart; ++j)
1288       ShuffleMask[j] = MaskStart + j;
1289     // Fill the rest of the mask with -1 for undef.
1290     std::fill(&ShuffleMask[MaskStart], ShuffleMask.end(), -1);
1291 
1292     ArrayRef<int> Mask = Shuffle->getShuffleMask();
1293     if (ShuffleMask != Mask)
1294       return TTI::RK_None;
1295 
1296     RdxOp = dyn_cast<Instruction>(NextRdxOp);
1297     NumVecElemsRemain /= 2;
1298     MaskStart *= 2;
1299   }
1300 
1301   Opcode = RD->Opcode;
1302   Ty = VecTy;
1303   return RD->Kind;
1304 }
1305 
1306 TTI::ReductionKind
1307 TTI::matchVectorReduction(const ExtractElementInst *Root, unsigned &Opcode,
1308                           VectorType *&Ty, bool &IsPairwise) {
1309   TTI::ReductionKind RdxKind = matchVectorSplittingReduction(Root, Opcode, Ty);
1310   if (RdxKind != TTI::ReductionKind::RK_None) {
1311     IsPairwise = false;
1312     return RdxKind;
1313   }
1314   IsPairwise = true;
1315   return matchPairwiseReduction(Root, Opcode, Ty);
1316 }
1317 
1318 int TargetTransformInfo::getInstructionThroughput(const Instruction *I) const {
1319   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
1320 
1321   switch (I->getOpcode()) {
1322   case Instruction::GetElementPtr:
1323   case Instruction::Ret:
1324   case Instruction::PHI:
1325   case Instruction::Br:
1326   case Instruction::Add:
1327   case Instruction::FAdd:
1328   case Instruction::Sub:
1329   case Instruction::FSub:
1330   case Instruction::Mul:
1331   case Instruction::FMul:
1332   case Instruction::UDiv:
1333   case Instruction::SDiv:
1334   case Instruction::FDiv:
1335   case Instruction::URem:
1336   case Instruction::SRem:
1337   case Instruction::FRem:
1338   case Instruction::Shl:
1339   case Instruction::LShr:
1340   case Instruction::AShr:
1341   case Instruction::And:
1342   case Instruction::Or:
1343   case Instruction::Xor:
1344   case Instruction::FNeg:
1345   case Instruction::Select:
1346   case Instruction::ICmp:
1347   case Instruction::FCmp:
1348   case Instruction::Store:
1349   case Instruction::Load:
1350   case Instruction::ZExt:
1351   case Instruction::SExt:
1352   case Instruction::FPToUI:
1353   case Instruction::FPToSI:
1354   case Instruction::FPExt:
1355   case Instruction::PtrToInt:
1356   case Instruction::IntToPtr:
1357   case Instruction::SIToFP:
1358   case Instruction::UIToFP:
1359   case Instruction::Trunc:
1360   case Instruction::FPTrunc:
1361   case Instruction::BitCast:
1362   case Instruction::AddrSpaceCast:
1363   case Instruction::ExtractElement:
1364   case Instruction::InsertElement:
1365   case Instruction::ExtractValue:
1366   case Instruction::ShuffleVector:
1367   case Instruction::Call:
1368     return getUserCost(I, CostKind);
1369   default:
1370     // We don't have any information on this instruction.
1371     return -1;
1372   }
1373 }
1374 
1375 TargetTransformInfo::Concept::~Concept() {}
1376 
1377 TargetIRAnalysis::TargetIRAnalysis() : TTICallback(&getDefaultTTI) {}
1378 
1379 TargetIRAnalysis::TargetIRAnalysis(
1380     std::function<Result(const Function &)> TTICallback)
1381     : TTICallback(std::move(TTICallback)) {}
1382 
1383 TargetIRAnalysis::Result TargetIRAnalysis::run(const Function &F,
1384                                                FunctionAnalysisManager &) {
1385   return TTICallback(F);
1386 }
1387 
1388 AnalysisKey TargetIRAnalysis::Key;
1389 
1390 TargetIRAnalysis::Result TargetIRAnalysis::getDefaultTTI(const Function &F) {
1391   return Result(F.getParent()->getDataLayout());
1392 }
1393 
1394 // Register the basic pass.
1395 INITIALIZE_PASS(TargetTransformInfoWrapperPass, "tti",
1396                 "Target Transform Information", false, true)
1397 char TargetTransformInfoWrapperPass::ID = 0;
1398 
1399 void TargetTransformInfoWrapperPass::anchor() {}
1400 
1401 TargetTransformInfoWrapperPass::TargetTransformInfoWrapperPass()
1402     : ImmutablePass(ID) {
1403   initializeTargetTransformInfoWrapperPassPass(
1404       *PassRegistry::getPassRegistry());
1405 }
1406 
1407 TargetTransformInfoWrapperPass::TargetTransformInfoWrapperPass(
1408     TargetIRAnalysis TIRA)
1409     : ImmutablePass(ID), TIRA(std::move(TIRA)) {
1410   initializeTargetTransformInfoWrapperPassPass(
1411       *PassRegistry::getPassRegistry());
1412 }
1413 
1414 TargetTransformInfo &TargetTransformInfoWrapperPass::getTTI(const Function &F) {
1415   FunctionAnalysisManager DummyFAM;
1416   TTI = TIRA.run(F, DummyFAM);
1417   return *TTI;
1418 }
1419 
1420 ImmutablePass *
1421 llvm::createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA) {
1422   return new TargetTransformInfoWrapperPass(std::move(TIRA));
1423 }
1424