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