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