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