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