1a17f03bdSSanjay Patel //===------- VectorCombine.cpp - Optimize partial vector operations -------===//
2a17f03bdSSanjay Patel //
3a17f03bdSSanjay Patel // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4a17f03bdSSanjay Patel // See https://llvm.org/LICENSE.txt for license information.
5a17f03bdSSanjay Patel // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6a17f03bdSSanjay Patel //
7a17f03bdSSanjay Patel //===----------------------------------------------------------------------===//
8a17f03bdSSanjay Patel //
9a17f03bdSSanjay Patel // This pass optimizes scalar/vector interactions using target cost models. The
10a17f03bdSSanjay Patel // transforms implemented here may not fit in traditional loop-based or SLP
11a17f03bdSSanjay Patel // vectorization passes.
12a17f03bdSSanjay Patel //
13a17f03bdSSanjay Patel //===----------------------------------------------------------------------===//
14a17f03bdSSanjay Patel 
15a17f03bdSSanjay Patel #include "llvm/Transforms/Vectorize/VectorCombine.h"
16a17f03bdSSanjay Patel #include "llvm/ADT/Statistic.h"
175006e551SSimon Pilgrim #include "llvm/Analysis/BasicAliasAnalysis.h"
18a17f03bdSSanjay Patel #include "llvm/Analysis/GlobalsModRef.h"
1943bdac29SSanjay Patel #include "llvm/Analysis/Loads.h"
20a17f03bdSSanjay Patel #include "llvm/Analysis/TargetTransformInfo.h"
2119b62b79SSanjay Patel #include "llvm/Analysis/ValueTracking.h"
22b6050ca1SSanjay Patel #include "llvm/Analysis/VectorUtils.h"
23a17f03bdSSanjay Patel #include "llvm/IR/Dominators.h"
24a17f03bdSSanjay Patel #include "llvm/IR/Function.h"
25a17f03bdSSanjay Patel #include "llvm/IR/IRBuilder.h"
26a17f03bdSSanjay Patel #include "llvm/IR/PatternMatch.h"
27a17f03bdSSanjay Patel #include "llvm/InitializePasses.h"
28a17f03bdSSanjay Patel #include "llvm/Pass.h"
2925c6544fSSanjay Patel #include "llvm/Support/CommandLine.h"
30a17f03bdSSanjay Patel #include "llvm/Transforms/Utils/Local.h"
315006e551SSimon Pilgrim #include "llvm/Transforms/Vectorize.h"
32a17f03bdSSanjay Patel 
33a17f03bdSSanjay Patel using namespace llvm;
34a17f03bdSSanjay Patel using namespace llvm::PatternMatch;
35a17f03bdSSanjay Patel 
36a17f03bdSSanjay Patel #define DEBUG_TYPE "vector-combine"
3743bdac29SSanjay Patel STATISTIC(NumVecLoad, "Number of vector loads formed");
38a17f03bdSSanjay Patel STATISTIC(NumVecCmp, "Number of vector compares formed");
3919b62b79SSanjay Patel STATISTIC(NumVecBO, "Number of vector binops formed");
40b6315aeeSSanjay Patel STATISTIC(NumVecCmpBO, "Number of vector compare + binop formed");
417aeb41b3SRoman Lebedev STATISTIC(NumShufOfBitcast, "Number of shuffles moved after bitcast");
420d2a0b44SSanjay Patel STATISTIC(NumScalarBO, "Number of scalar binops formed");
43ed67f5e7SSanjay Patel STATISTIC(NumScalarCmp, "Number of scalar compares formed");
44a17f03bdSSanjay Patel 
4525c6544fSSanjay Patel static cl::opt<bool> DisableVectorCombine(
4625c6544fSSanjay Patel     "disable-vector-combine", cl::init(false), cl::Hidden,
4725c6544fSSanjay Patel     cl::desc("Disable all vector combine transforms"));
4825c6544fSSanjay Patel 
49a69158c1SSanjay Patel static cl::opt<bool> DisableBinopExtractShuffle(
50a69158c1SSanjay Patel     "disable-binop-extract-shuffle", cl::init(false), cl::Hidden,
51a69158c1SSanjay Patel     cl::desc("Disable binop extract to shuffle transforms"));
52a69158c1SSanjay Patel 
532db4979cSQiu Chaofan static cl::opt<unsigned> MaxInstrsToScan(
542db4979cSQiu Chaofan     "vector-combine-max-scan-instrs", cl::init(30), cl::Hidden,
552db4979cSQiu Chaofan     cl::desc("Max number of instructions to scan for vector combining."));
562db4979cSQiu Chaofan 
57a0f96741SSanjay Patel static const unsigned InvalidIndex = std::numeric_limits<unsigned>::max();
58a0f96741SSanjay Patel 
59b4447054SBenjamin Kramer namespace {
606bdd531aSSanjay Patel class VectorCombine {
616bdd531aSSanjay Patel public:
626bdd531aSSanjay Patel   VectorCombine(Function &F, const TargetTransformInfo &TTI,
632db4979cSQiu Chaofan                 const DominatorTree &DT, AAResults &AA)
642db4979cSQiu Chaofan       : F(F), Builder(F.getContext()), TTI(TTI), DT(DT), AA(AA) {}
656bdd531aSSanjay Patel 
666bdd531aSSanjay Patel   bool run();
676bdd531aSSanjay Patel 
686bdd531aSSanjay Patel private:
696bdd531aSSanjay Patel   Function &F;
70de65b356SSanjay Patel   IRBuilder<> Builder;
716bdd531aSSanjay Patel   const TargetTransformInfo &TTI;
726bdd531aSSanjay Patel   const DominatorTree &DT;
732db4979cSQiu Chaofan   AAResults &AA;
746bdd531aSSanjay Patel 
7543bdac29SSanjay Patel   bool vectorizeLoadInsert(Instruction &I);
763b95d834SSanjay Patel   ExtractElementInst *getShuffleExtract(ExtractElementInst *Ext0,
773b95d834SSanjay Patel                                         ExtractElementInst *Ext1,
783b95d834SSanjay Patel                                         unsigned PreferredExtractIndex) const;
796bdd531aSSanjay Patel   bool isExtractExtractCheap(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
806bdd531aSSanjay Patel                              unsigned Opcode,
816bdd531aSSanjay Patel                              ExtractElementInst *&ConvertToShuffle,
826bdd531aSSanjay Patel                              unsigned PreferredExtractIndex);
83de65b356SSanjay Patel   void foldExtExtCmp(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
84de65b356SSanjay Patel                      Instruction &I);
85de65b356SSanjay Patel   void foldExtExtBinop(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
86de65b356SSanjay Patel                        Instruction &I);
876bdd531aSSanjay Patel   bool foldExtractExtract(Instruction &I);
886bdd531aSSanjay Patel   bool foldBitcastShuf(Instruction &I);
896bdd531aSSanjay Patel   bool scalarizeBinopOrCmp(Instruction &I);
90b6315aeeSSanjay Patel   bool foldExtractedCmps(Instruction &I);
912db4979cSQiu Chaofan   bool foldSingleElementStore(Instruction &I);
926bdd531aSSanjay Patel };
93b4447054SBenjamin Kramer } // namespace
94a69158c1SSanjay Patel 
9598c2f4eeSSanjay Patel static void replaceValue(Value &Old, Value &New) {
9698c2f4eeSSanjay Patel   Old.replaceAllUsesWith(&New);
9798c2f4eeSSanjay Patel   New.takeName(&Old);
9898c2f4eeSSanjay Patel }
9998c2f4eeSSanjay Patel 
10043bdac29SSanjay Patel bool VectorCombine::vectorizeLoadInsert(Instruction &I) {
101b2ef2640SSanjay Patel   // Match insert into fixed vector of scalar value.
10247aaa99cSSanjay Patel   // TODO: Handle non-zero insert index.
103ddd9575dSSanjay Patel   auto *Ty = dyn_cast<FixedVectorType>(I.getType());
10443bdac29SSanjay Patel   Value *Scalar;
10548a23bccSSanjay Patel   if (!Ty || !match(&I, m_InsertElt(m_Undef(), m_Value(Scalar), m_ZeroInt())) ||
10648a23bccSSanjay Patel       !Scalar->hasOneUse())
10743bdac29SSanjay Patel     return false;
108ddd9575dSSanjay Patel 
109b2ef2640SSanjay Patel   // Optionally match an extract from another vector.
110b2ef2640SSanjay Patel   Value *X;
111b2ef2640SSanjay Patel   bool HasExtract = match(Scalar, m_ExtractElt(m_Value(X), m_ZeroInt()));
112b2ef2640SSanjay Patel   if (!HasExtract)
113b2ef2640SSanjay Patel     X = Scalar;
114b2ef2640SSanjay Patel 
115b2ef2640SSanjay Patel   // Match source value as load of scalar or vector.
1164452cc40SFangrui Song   // Do not vectorize scalar load (widening) if atomic/volatile or under
1174452cc40SFangrui Song   // asan/hwasan/memtag/tsan. The widened load may load data from dirty regions
1184452cc40SFangrui Song   // or create data races non-existent in the source.
119b2ef2640SSanjay Patel   auto *Load = dyn_cast<LoadInst>(X);
120b2ef2640SSanjay Patel   if (!Load || !Load->isSimple() || !Load->hasOneUse() ||
1214452cc40SFangrui Song       Load->getFunction()->hasFnAttribute(Attribute::SanitizeMemTag) ||
1224452cc40SFangrui Song       mustSuppressSpeculation(*Load))
12343bdac29SSanjay Patel     return false;
12443bdac29SSanjay Patel 
12512b684aeSSanjay Patel   const DataLayout &DL = I.getModule()->getDataLayout();
12612b684aeSSanjay Patel   Value *SrcPtr = Load->getPointerOperand()->stripPointerCasts();
12712b684aeSSanjay Patel   assert(isa<PointerType>(SrcPtr->getType()) && "Expected a pointer type");
128c36c0fabSArtem Belevich 
129c36c0fabSArtem Belevich   // If original AS != Load's AS, we can't bitcast the original pointer and have
130c36c0fabSArtem Belevich   // to use Load's operand instead. Ideally we would want to strip pointer casts
131c36c0fabSArtem Belevich   // without changing AS, but there's no API to do that ATM.
13212b684aeSSanjay Patel   unsigned AS = Load->getPointerAddressSpace();
13312b684aeSSanjay Patel   if (AS != SrcPtr->getType()->getPointerAddressSpace())
13412b684aeSSanjay Patel     SrcPtr = Load->getPointerOperand();
13543bdac29SSanjay Patel 
13647aaa99cSSanjay Patel   // We are potentially transforming byte-sized (8-bit) memory accesses, so make
13747aaa99cSSanjay Patel   // sure we have all of our type-based constraints in place for this target.
138ddd9575dSSanjay Patel   Type *ScalarTy = Scalar->getType();
13943bdac29SSanjay Patel   uint64_t ScalarSize = ScalarTy->getPrimitiveSizeInBits();
140ddd9575dSSanjay Patel   unsigned MinVectorSize = TTI.getMinVectorRegisterBitWidth();
14147aaa99cSSanjay Patel   if (!ScalarSize || !MinVectorSize || MinVectorSize % ScalarSize != 0 ||
14247aaa99cSSanjay Patel       ScalarSize % 8 != 0)
14343bdac29SSanjay Patel     return false;
14443bdac29SSanjay Patel 
14543bdac29SSanjay Patel   // Check safety of replacing the scalar load with a larger vector load.
146aaaf0ec7SSanjay Patel   // We use minimal alignment (maximum flexibility) because we only care about
147aaaf0ec7SSanjay Patel   // the dereferenceable region. When calculating cost and creating a new op,
148aaaf0ec7SSanjay Patel   // we may use a larger value based on alignment attributes.
1498fb05593SSanjay Patel   unsigned MinVecNumElts = MinVectorSize / ScalarSize;
1508fb05593SSanjay Patel   auto *MinVecTy = VectorType::get(ScalarTy, MinVecNumElts, false);
15147aaa99cSSanjay Patel   unsigned OffsetEltIndex = 0;
15247aaa99cSSanjay Patel   Align Alignment = Load->getAlign();
15347aaa99cSSanjay Patel   if (!isSafeToLoadUnconditionally(SrcPtr, MinVecTy, Align(1), DL, Load, &DT)) {
15447aaa99cSSanjay Patel     // It is not safe to load directly from the pointer, but we can still peek
15547aaa99cSSanjay Patel     // through gep offsets and check if it safe to load from a base address with
15647aaa99cSSanjay Patel     // updated alignment. If it is, we can shuffle the element(s) into place
15747aaa99cSSanjay Patel     // after loading.
15847aaa99cSSanjay Patel     unsigned OffsetBitWidth = DL.getIndexTypeSizeInBits(SrcPtr->getType());
15947aaa99cSSanjay Patel     APInt Offset(OffsetBitWidth, 0);
16047aaa99cSSanjay Patel     SrcPtr = SrcPtr->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
16147aaa99cSSanjay Patel 
16247aaa99cSSanjay Patel     // We want to shuffle the result down from a high element of a vector, so
16347aaa99cSSanjay Patel     // the offset must be positive.
16447aaa99cSSanjay Patel     if (Offset.isNegative())
16547aaa99cSSanjay Patel       return false;
16647aaa99cSSanjay Patel 
16747aaa99cSSanjay Patel     // The offset must be a multiple of the scalar element to shuffle cleanly
16847aaa99cSSanjay Patel     // in the element's size.
16947aaa99cSSanjay Patel     uint64_t ScalarSizeInBytes = ScalarSize / 8;
17047aaa99cSSanjay Patel     if (Offset.urem(ScalarSizeInBytes) != 0)
17147aaa99cSSanjay Patel       return false;
17247aaa99cSSanjay Patel 
17347aaa99cSSanjay Patel     // If we load MinVecNumElts, will our target element still be loaded?
17447aaa99cSSanjay Patel     OffsetEltIndex = Offset.udiv(ScalarSizeInBytes).getZExtValue();
17547aaa99cSSanjay Patel     if (OffsetEltIndex >= MinVecNumElts)
17647aaa99cSSanjay Patel       return false;
17747aaa99cSSanjay Patel 
178aaaf0ec7SSanjay Patel     if (!isSafeToLoadUnconditionally(SrcPtr, MinVecTy, Align(1), DL, Load, &DT))
17943bdac29SSanjay Patel       return false;
18043bdac29SSanjay Patel 
18147aaa99cSSanjay Patel     // Update alignment with offset value. Note that the offset could be negated
18247aaa99cSSanjay Patel     // to more accurately represent "(new) SrcPtr - Offset = (old) SrcPtr", but
18347aaa99cSSanjay Patel     // negation does not change the result of the alignment calculation.
18447aaa99cSSanjay Patel     Alignment = commonAlignment(Alignment, Offset.getZExtValue());
18547aaa99cSSanjay Patel   }
18647aaa99cSSanjay Patel 
187b2ef2640SSanjay Patel   // Original pattern: insertelt undef, load [free casts of] PtrOp, 0
18838ebc1a1SSanjay Patel   // Use the greater of the alignment on the load or its source pointer.
18947aaa99cSSanjay Patel   Alignment = std::max(SrcPtr->getPointerAlignment(DL), Alignment);
190b2ef2640SSanjay Patel   Type *LoadTy = Load->getType();
19136710c38SCaroline Concatto   InstructionCost OldCost =
19236710c38SCaroline Concatto       TTI.getMemoryOpCost(Instruction::Load, LoadTy, Alignment, AS);
1938fb05593SSanjay Patel   APInt DemandedElts = APInt::getOneBitSet(MinVecNumElts, 0);
194b2ef2640SSanjay Patel   OldCost += TTI.getScalarizationOverhead(MinVecTy, DemandedElts,
195b2ef2640SSanjay Patel                                           /* Insert */ true, HasExtract);
19643bdac29SSanjay Patel 
19743bdac29SSanjay Patel   // New pattern: load VecPtr
19836710c38SCaroline Concatto   InstructionCost NewCost =
19936710c38SCaroline Concatto       TTI.getMemoryOpCost(Instruction::Load, MinVecTy, Alignment, AS);
20047aaa99cSSanjay Patel   // Optionally, we are shuffling the loaded vector element(s) into place.
201e2935dcfSDavid Green   // For the mask set everything but element 0 to undef to prevent poison from
202e2935dcfSDavid Green   // propagating from the extra loaded memory. This will also optionally
203e2935dcfSDavid Green   // shrink/grow the vector from the loaded size to the output size.
204e2935dcfSDavid Green   // We assume this operation has no cost in codegen if there was no offset.
205e2935dcfSDavid Green   // Note that we could use freeze to avoid poison problems, but then we might
206e2935dcfSDavid Green   // still need a shuffle to change the vector size.
207e2935dcfSDavid Green   unsigned OutputNumElts = Ty->getNumElements();
208e2935dcfSDavid Green   SmallVector<int, 16> Mask(OutputNumElts, UndefMaskElem);
209e2935dcfSDavid Green   assert(OffsetEltIndex < MinVecNumElts && "Address offset too big");
210e2935dcfSDavid Green   Mask[0] = OffsetEltIndex;
21147aaa99cSSanjay Patel   if (OffsetEltIndex)
212e2935dcfSDavid Green     NewCost += TTI.getShuffleCost(TTI::SK_PermuteSingleSrc, MinVecTy, Mask);
21343bdac29SSanjay Patel 
21443bdac29SSanjay Patel   // We can aggressively convert to the vector form because the backend can
21543bdac29SSanjay Patel   // invert this transform if it does not result in a performance win.
21636710c38SCaroline Concatto   if (OldCost < NewCost || !NewCost.isValid())
21743bdac29SSanjay Patel     return false;
21843bdac29SSanjay Patel 
21943bdac29SSanjay Patel   // It is safe and potentially profitable to load a vector directly:
22043bdac29SSanjay Patel   // inselt undef, load Scalar, 0 --> load VecPtr
22143bdac29SSanjay Patel   IRBuilder<> Builder(Load);
22212b684aeSSanjay Patel   Value *CastedPtr = Builder.CreateBitCast(SrcPtr, MinVecTy->getPointerTo(AS));
2238fb05593SSanjay Patel   Value *VecLd = Builder.CreateAlignedLoad(MinVecTy, CastedPtr, Alignment);
2241e6b240dSSanjay Patel   VecLd = Builder.CreateShuffleVector(VecLd, Mask);
225d399f870SSanjay Patel 
22643bdac29SSanjay Patel   replaceValue(I, *VecLd);
22743bdac29SSanjay Patel   ++NumVecLoad;
22843bdac29SSanjay Patel   return true;
22943bdac29SSanjay Patel }
23043bdac29SSanjay Patel 
2313b95d834SSanjay Patel /// Determine which, if any, of the inputs should be replaced by a shuffle
2323b95d834SSanjay Patel /// followed by extract from a different index.
2333b95d834SSanjay Patel ExtractElementInst *VectorCombine::getShuffleExtract(
2343b95d834SSanjay Patel     ExtractElementInst *Ext0, ExtractElementInst *Ext1,
2353b95d834SSanjay Patel     unsigned PreferredExtractIndex = InvalidIndex) const {
2363b95d834SSanjay Patel   assert(isa<ConstantInt>(Ext0->getIndexOperand()) &&
2373b95d834SSanjay Patel          isa<ConstantInt>(Ext1->getIndexOperand()) &&
2383b95d834SSanjay Patel          "Expected constant extract indexes");
2393b95d834SSanjay Patel 
2403b95d834SSanjay Patel   unsigned Index0 = cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue();
2413b95d834SSanjay Patel   unsigned Index1 = cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue();
2423b95d834SSanjay Patel 
2433b95d834SSanjay Patel   // If the extract indexes are identical, no shuffle is needed.
2443b95d834SSanjay Patel   if (Index0 == Index1)
2453b95d834SSanjay Patel     return nullptr;
2463b95d834SSanjay Patel 
2473b95d834SSanjay Patel   Type *VecTy = Ext0->getVectorOperand()->getType();
2483b95d834SSanjay Patel   assert(VecTy == Ext1->getVectorOperand()->getType() && "Need matching types");
24936710c38SCaroline Concatto   InstructionCost Cost0 =
25036710c38SCaroline Concatto       TTI.getVectorInstrCost(Ext0->getOpcode(), VecTy, Index0);
25136710c38SCaroline Concatto   InstructionCost Cost1 =
25236710c38SCaroline Concatto       TTI.getVectorInstrCost(Ext1->getOpcode(), VecTy, Index1);
25336710c38SCaroline Concatto 
25436710c38SCaroline Concatto   // If both costs are invalid no shuffle is needed
25536710c38SCaroline Concatto   if (!Cost0.isValid() && !Cost1.isValid())
25636710c38SCaroline Concatto     return nullptr;
2573b95d834SSanjay Patel 
2583b95d834SSanjay Patel   // We are extracting from 2 different indexes, so one operand must be shuffled
2593b95d834SSanjay Patel   // before performing a vector operation and/or extract. The more expensive
2603b95d834SSanjay Patel   // extract will be replaced by a shuffle.
2613b95d834SSanjay Patel   if (Cost0 > Cost1)
2623b95d834SSanjay Patel     return Ext0;
2633b95d834SSanjay Patel   if (Cost1 > Cost0)
2643b95d834SSanjay Patel     return Ext1;
2653b95d834SSanjay Patel 
2663b95d834SSanjay Patel   // If the costs are equal and there is a preferred extract index, shuffle the
2673b95d834SSanjay Patel   // opposite operand.
2683b95d834SSanjay Patel   if (PreferredExtractIndex == Index0)
2693b95d834SSanjay Patel     return Ext1;
2703b95d834SSanjay Patel   if (PreferredExtractIndex == Index1)
2713b95d834SSanjay Patel     return Ext0;
2723b95d834SSanjay Patel 
2733b95d834SSanjay Patel   // Otherwise, replace the extract with the higher index.
2743b95d834SSanjay Patel   return Index0 > Index1 ? Ext0 : Ext1;
2753b95d834SSanjay Patel }
2763b95d834SSanjay Patel 
277a69158c1SSanjay Patel /// Compare the relative costs of 2 extracts followed by scalar operation vs.
278a69158c1SSanjay Patel /// vector operation(s) followed by extract. Return true if the existing
279a69158c1SSanjay Patel /// instructions are cheaper than a vector alternative. Otherwise, return false
280a69158c1SSanjay Patel /// and if one of the extracts should be transformed to a shufflevector, set
281a69158c1SSanjay Patel /// \p ConvertToShuffle to that extract instruction.
2826bdd531aSSanjay Patel bool VectorCombine::isExtractExtractCheap(ExtractElementInst *Ext0,
2836bdd531aSSanjay Patel                                           ExtractElementInst *Ext1,
2846bdd531aSSanjay Patel                                           unsigned Opcode,
285216a37bbSSanjay Patel                                           ExtractElementInst *&ConvertToShuffle,
286ce97ce3aSSanjay Patel                                           unsigned PreferredExtractIndex) {
2874fa63fd4SAustin Kerbow   assert(isa<ConstantInt>(Ext0->getOperand(1)) &&
288a69158c1SSanjay Patel          isa<ConstantInt>(Ext1->getOperand(1)) &&
289a69158c1SSanjay Patel          "Expected constant extract indexes");
29034e34855SSanjay Patel   Type *ScalarTy = Ext0->getType();
291e3056ae9SSam Parker   auto *VecTy = cast<VectorType>(Ext0->getOperand(0)->getType());
29236710c38SCaroline Concatto   InstructionCost ScalarOpCost, VectorOpCost;
29334e34855SSanjay Patel 
29434e34855SSanjay Patel   // Get cost estimates for scalar and vector versions of the operation.
29534e34855SSanjay Patel   bool IsBinOp = Instruction::isBinaryOp(Opcode);
29634e34855SSanjay Patel   if (IsBinOp) {
29734e34855SSanjay Patel     ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
29834e34855SSanjay Patel     VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
29934e34855SSanjay Patel   } else {
30034e34855SSanjay Patel     assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
30134e34855SSanjay Patel            "Expected a compare");
30234e34855SSanjay Patel     ScalarOpCost = TTI.getCmpSelInstrCost(Opcode, ScalarTy,
30334e34855SSanjay Patel                                           CmpInst::makeCmpResultType(ScalarTy));
30434e34855SSanjay Patel     VectorOpCost = TTI.getCmpSelInstrCost(Opcode, VecTy,
30534e34855SSanjay Patel                                           CmpInst::makeCmpResultType(VecTy));
30634e34855SSanjay Patel   }
30734e34855SSanjay Patel 
308a69158c1SSanjay Patel   // Get cost estimates for the extract elements. These costs will factor into
30934e34855SSanjay Patel   // both sequences.
310a69158c1SSanjay Patel   unsigned Ext0Index = cast<ConstantInt>(Ext0->getOperand(1))->getZExtValue();
311a69158c1SSanjay Patel   unsigned Ext1Index = cast<ConstantInt>(Ext1->getOperand(1))->getZExtValue();
312a69158c1SSanjay Patel 
31336710c38SCaroline Concatto   InstructionCost Extract0Cost =
3146bdd531aSSanjay Patel       TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy, Ext0Index);
31536710c38SCaroline Concatto   InstructionCost Extract1Cost =
3166bdd531aSSanjay Patel       TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy, Ext1Index);
317a69158c1SSanjay Patel 
318a69158c1SSanjay Patel   // A more expensive extract will always be replaced by a splat shuffle.
319a69158c1SSanjay Patel   // For example, if Ext0 is more expensive:
320a69158c1SSanjay Patel   // opcode (extelt V0, Ext0), (ext V1, Ext1) -->
321a69158c1SSanjay Patel   // extelt (opcode (splat V0, Ext0), V1), Ext1
322a69158c1SSanjay Patel   // TODO: Evaluate whether that always results in lowest cost. Alternatively,
323a69158c1SSanjay Patel   //       check the cost of creating a broadcast shuffle and shuffling both
324a69158c1SSanjay Patel   //       operands to element 0.
32536710c38SCaroline Concatto   InstructionCost CheapExtractCost = std::min(Extract0Cost, Extract1Cost);
32634e34855SSanjay Patel 
32734e34855SSanjay Patel   // Extra uses of the extracts mean that we include those costs in the
32834e34855SSanjay Patel   // vector total because those instructions will not be eliminated.
32936710c38SCaroline Concatto   InstructionCost OldCost, NewCost;
330a69158c1SSanjay Patel   if (Ext0->getOperand(0) == Ext1->getOperand(0) && Ext0Index == Ext1Index) {
331a69158c1SSanjay Patel     // Handle a special case. If the 2 extracts are identical, adjust the
33234e34855SSanjay Patel     // formulas to account for that. The extra use charge allows for either the
33334e34855SSanjay Patel     // CSE'd pattern or an unoptimized form with identical values:
33434e34855SSanjay Patel     // opcode (extelt V, C), (extelt V, C) --> extelt (opcode V, V), C
33534e34855SSanjay Patel     bool HasUseTax = Ext0 == Ext1 ? !Ext0->hasNUses(2)
33634e34855SSanjay Patel                                   : !Ext0->hasOneUse() || !Ext1->hasOneUse();
337a69158c1SSanjay Patel     OldCost = CheapExtractCost + ScalarOpCost;
338a69158c1SSanjay Patel     NewCost = VectorOpCost + CheapExtractCost + HasUseTax * CheapExtractCost;
33934e34855SSanjay Patel   } else {
34034e34855SSanjay Patel     // Handle the general case. Each extract is actually a different value:
341a69158c1SSanjay Patel     // opcode (extelt V0, C0), (extelt V1, C1) --> extelt (opcode V0, V1), C
342a69158c1SSanjay Patel     OldCost = Extract0Cost + Extract1Cost + ScalarOpCost;
343a69158c1SSanjay Patel     NewCost = VectorOpCost + CheapExtractCost +
344a69158c1SSanjay Patel               !Ext0->hasOneUse() * Extract0Cost +
345a69158c1SSanjay Patel               !Ext1->hasOneUse() * Extract1Cost;
34634e34855SSanjay Patel   }
347a69158c1SSanjay Patel 
3483b95d834SSanjay Patel   ConvertToShuffle = getShuffleExtract(Ext0, Ext1, PreferredExtractIndex);
3493b95d834SSanjay Patel   if (ConvertToShuffle) {
350a69158c1SSanjay Patel     if (IsBinOp && DisableBinopExtractShuffle)
351a69158c1SSanjay Patel       return true;
352a69158c1SSanjay Patel 
353a69158c1SSanjay Patel     // If we are extracting from 2 different indexes, then one operand must be
354a69158c1SSanjay Patel     // shuffled before performing the vector operation. The shuffle mask is
355a69158c1SSanjay Patel     // undefined except for 1 lane that is being translated to the remaining
356a69158c1SSanjay Patel     // extraction lane. Therefore, it is a splat shuffle. Ex:
357a69158c1SSanjay Patel     // ShufMask = { undef, undef, 0, undef }
358a69158c1SSanjay Patel     // TODO: The cost model has an option for a "broadcast" shuffle
359a69158c1SSanjay Patel     //       (splat-from-element-0), but no option for a more general splat.
360a69158c1SSanjay Patel     NewCost +=
361a69158c1SSanjay Patel         TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, VecTy);
362a69158c1SSanjay Patel   }
363a69158c1SSanjay Patel 
36410ea01d8SSanjay Patel   // Aggressively form a vector op if the cost is equal because the transform
36510ea01d8SSanjay Patel   // may enable further optimization.
36610ea01d8SSanjay Patel   // Codegen can reverse this transform (scalarize) if it was not profitable.
36710ea01d8SSanjay Patel   return OldCost < NewCost;
36834e34855SSanjay Patel }
36934e34855SSanjay Patel 
3709934cc54SSanjay Patel /// Create a shuffle that translates (shifts) 1 element from the input vector
3719934cc54SSanjay Patel /// to a new element location.
3729934cc54SSanjay Patel static Value *createShiftShuffle(Value *Vec, unsigned OldIndex,
3739934cc54SSanjay Patel                                  unsigned NewIndex, IRBuilder<> &Builder) {
3749934cc54SSanjay Patel   // The shuffle mask is undefined except for 1 lane that is being translated
3759934cc54SSanjay Patel   // to the new element index. Example for OldIndex == 2 and NewIndex == 0:
3769934cc54SSanjay Patel   // ShufMask = { 2, undef, undef, undef }
3779934cc54SSanjay Patel   auto *VecTy = cast<FixedVectorType>(Vec->getType());
37854143e2bSSanjay Patel   SmallVector<int, 32> ShufMask(VecTy->getNumElements(), UndefMaskElem);
3799934cc54SSanjay Patel   ShufMask[NewIndex] = OldIndex;
3801e6b240dSSanjay Patel   return Builder.CreateShuffleVector(Vec, ShufMask, "shift");
3819934cc54SSanjay Patel }
3829934cc54SSanjay Patel 
383216a37bbSSanjay Patel /// Given an extract element instruction with constant index operand, shuffle
384216a37bbSSanjay Patel /// the source vector (shift the scalar element) to a NewIndex for extraction.
385216a37bbSSanjay Patel /// Return null if the input can be constant folded, so that we are not creating
386216a37bbSSanjay Patel /// unnecessary instructions.
3879934cc54SSanjay Patel static ExtractElementInst *translateExtract(ExtractElementInst *ExtElt,
3889934cc54SSanjay Patel                                             unsigned NewIndex,
3899934cc54SSanjay Patel                                             IRBuilder<> &Builder) {
390216a37bbSSanjay Patel   // If the extract can be constant-folded, this code is unsimplified. Defer
391216a37bbSSanjay Patel   // to other passes to handle that.
392216a37bbSSanjay Patel   Value *X = ExtElt->getVectorOperand();
393216a37bbSSanjay Patel   Value *C = ExtElt->getIndexOperand();
394de65b356SSanjay Patel   assert(isa<ConstantInt>(C) && "Expected a constant index operand");
395216a37bbSSanjay Patel   if (isa<Constant>(X))
396216a37bbSSanjay Patel     return nullptr;
397216a37bbSSanjay Patel 
3989934cc54SSanjay Patel   Value *Shuf = createShiftShuffle(X, cast<ConstantInt>(C)->getZExtValue(),
3999934cc54SSanjay Patel                                    NewIndex, Builder);
400216a37bbSSanjay Patel   return cast<ExtractElementInst>(Builder.CreateExtractElement(Shuf, NewIndex));
401216a37bbSSanjay Patel }
402216a37bbSSanjay Patel 
403fc445589SSanjay Patel /// Try to reduce extract element costs by converting scalar compares to vector
404fc445589SSanjay Patel /// compares followed by extract.
405e9c79a7aSSanjay Patel /// cmp (ext0 V0, C), (ext1 V1, C)
406de65b356SSanjay Patel void VectorCombine::foldExtExtCmp(ExtractElementInst *Ext0,
407de65b356SSanjay Patel                                   ExtractElementInst *Ext1, Instruction &I) {
408fc445589SSanjay Patel   assert(isa<CmpInst>(&I) && "Expected a compare");
409216a37bbSSanjay Patel   assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() ==
410216a37bbSSanjay Patel              cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() &&
411216a37bbSSanjay Patel          "Expected matching constant extract indexes");
412a17f03bdSSanjay Patel 
413a17f03bdSSanjay Patel   // cmp Pred (extelt V0, C), (extelt V1, C) --> extelt (cmp Pred V0, V1), C
414a17f03bdSSanjay Patel   ++NumVecCmp;
415fc445589SSanjay Patel   CmpInst::Predicate Pred = cast<CmpInst>(&I)->getPredicate();
416216a37bbSSanjay Patel   Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand();
41746a285adSSanjay Patel   Value *VecCmp = Builder.CreateCmp(Pred, V0, V1);
418216a37bbSSanjay Patel   Value *NewExt = Builder.CreateExtractElement(VecCmp, Ext0->getIndexOperand());
41998c2f4eeSSanjay Patel   replaceValue(I, *NewExt);
420a17f03bdSSanjay Patel }
421a17f03bdSSanjay Patel 
42219b62b79SSanjay Patel /// Try to reduce extract element costs by converting scalar binops to vector
42319b62b79SSanjay Patel /// binops followed by extract.
424e9c79a7aSSanjay Patel /// bo (ext0 V0, C), (ext1 V1, C)
425de65b356SSanjay Patel void VectorCombine::foldExtExtBinop(ExtractElementInst *Ext0,
426de65b356SSanjay Patel                                     ExtractElementInst *Ext1, Instruction &I) {
427fc445589SSanjay Patel   assert(isa<BinaryOperator>(&I) && "Expected a binary operator");
428216a37bbSSanjay Patel   assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() ==
429216a37bbSSanjay Patel              cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() &&
430216a37bbSSanjay Patel          "Expected matching constant extract indexes");
43119b62b79SSanjay Patel 
43234e34855SSanjay Patel   // bo (extelt V0, C), (extelt V1, C) --> extelt (bo V0, V1), C
43319b62b79SSanjay Patel   ++NumVecBO;
434216a37bbSSanjay Patel   Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand();
435e9c79a7aSSanjay Patel   Value *VecBO =
43634e34855SSanjay Patel       Builder.CreateBinOp(cast<BinaryOperator>(&I)->getOpcode(), V0, V1);
437e9c79a7aSSanjay Patel 
43819b62b79SSanjay Patel   // All IR flags are safe to back-propagate because any potential poison
43919b62b79SSanjay Patel   // created in unused vector elements is discarded by the extract.
440e9c79a7aSSanjay Patel   if (auto *VecBOInst = dyn_cast<Instruction>(VecBO))
44119b62b79SSanjay Patel     VecBOInst->copyIRFlags(&I);
442e9c79a7aSSanjay Patel 
443216a37bbSSanjay Patel   Value *NewExt = Builder.CreateExtractElement(VecBO, Ext0->getIndexOperand());
44498c2f4eeSSanjay Patel   replaceValue(I, *NewExt);
44519b62b79SSanjay Patel }
44619b62b79SSanjay Patel 
447fc445589SSanjay Patel /// Match an instruction with extracted vector operands.
4486bdd531aSSanjay Patel bool VectorCombine::foldExtractExtract(Instruction &I) {
449e9c79a7aSSanjay Patel   // It is not safe to transform things like div, urem, etc. because we may
450e9c79a7aSSanjay Patel   // create undefined behavior when executing those on unknown vector elements.
451e9c79a7aSSanjay Patel   if (!isSafeToSpeculativelyExecute(&I))
452e9c79a7aSSanjay Patel     return false;
453e9c79a7aSSanjay Patel 
454216a37bbSSanjay Patel   Instruction *I0, *I1;
455fc445589SSanjay Patel   CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
456216a37bbSSanjay Patel   if (!match(&I, m_Cmp(Pred, m_Instruction(I0), m_Instruction(I1))) &&
457216a37bbSSanjay Patel       !match(&I, m_BinOp(m_Instruction(I0), m_Instruction(I1))))
458fc445589SSanjay Patel     return false;
459fc445589SSanjay Patel 
460fc445589SSanjay Patel   Value *V0, *V1;
461fc445589SSanjay Patel   uint64_t C0, C1;
462216a37bbSSanjay Patel   if (!match(I0, m_ExtractElt(m_Value(V0), m_ConstantInt(C0))) ||
463216a37bbSSanjay Patel       !match(I1, m_ExtractElt(m_Value(V1), m_ConstantInt(C1))) ||
464fc445589SSanjay Patel       V0->getType() != V1->getType())
465fc445589SSanjay Patel     return false;
466fc445589SSanjay Patel 
467ce97ce3aSSanjay Patel   // If the scalar value 'I' is going to be re-inserted into a vector, then try
468ce97ce3aSSanjay Patel   // to create an extract to that same element. The extract/insert can be
469ce97ce3aSSanjay Patel   // reduced to a "select shuffle".
470ce97ce3aSSanjay Patel   // TODO: If we add a larger pattern match that starts from an insert, this
471ce97ce3aSSanjay Patel   //       probably becomes unnecessary.
472216a37bbSSanjay Patel   auto *Ext0 = cast<ExtractElementInst>(I0);
473216a37bbSSanjay Patel   auto *Ext1 = cast<ExtractElementInst>(I1);
474a0f96741SSanjay Patel   uint64_t InsertIndex = InvalidIndex;
475ce97ce3aSSanjay Patel   if (I.hasOneUse())
4767eed772aSSanjay Patel     match(I.user_back(),
4777eed772aSSanjay Patel           m_InsertElt(m_Value(), m_Value(), m_ConstantInt(InsertIndex)));
478ce97ce3aSSanjay Patel 
479216a37bbSSanjay Patel   ExtractElementInst *ExtractToChange;
4806bdd531aSSanjay Patel   if (isExtractExtractCheap(Ext0, Ext1, I.getOpcode(), ExtractToChange,
481ce97ce3aSSanjay Patel                             InsertIndex))
482fc445589SSanjay Patel     return false;
483e9c79a7aSSanjay Patel 
484216a37bbSSanjay Patel   if (ExtractToChange) {
485216a37bbSSanjay Patel     unsigned CheapExtractIdx = ExtractToChange == Ext0 ? C1 : C0;
486216a37bbSSanjay Patel     ExtractElementInst *NewExtract =
4879934cc54SSanjay Patel         translateExtract(ExtractToChange, CheapExtractIdx, Builder);
488216a37bbSSanjay Patel     if (!NewExtract)
4896d864097SSanjay Patel       return false;
490216a37bbSSanjay Patel     if (ExtractToChange == Ext0)
491216a37bbSSanjay Patel       Ext0 = NewExtract;
492a69158c1SSanjay Patel     else
493216a37bbSSanjay Patel       Ext1 = NewExtract;
494a69158c1SSanjay Patel   }
495e9c79a7aSSanjay Patel 
496e9c79a7aSSanjay Patel   if (Pred != CmpInst::BAD_ICMP_PREDICATE)
497039ff29eSSanjay Patel     foldExtExtCmp(Ext0, Ext1, I);
498e9c79a7aSSanjay Patel   else
499039ff29eSSanjay Patel     foldExtExtBinop(Ext0, Ext1, I);
500e9c79a7aSSanjay Patel 
501e9c79a7aSSanjay Patel   return true;
502fc445589SSanjay Patel }
503fc445589SSanjay Patel 
504bef6e67eSSanjay Patel /// If this is a bitcast of a shuffle, try to bitcast the source vector to the
505bef6e67eSSanjay Patel /// destination type followed by shuffle. This can enable further transforms by
506bef6e67eSSanjay Patel /// moving bitcasts or shuffles together.
5076bdd531aSSanjay Patel bool VectorCombine::foldBitcastShuf(Instruction &I) {
508b6050ca1SSanjay Patel   Value *V;
509b6050ca1SSanjay Patel   ArrayRef<int> Mask;
5107eed772aSSanjay Patel   if (!match(&I, m_BitCast(
5117eed772aSSanjay Patel                      m_OneUse(m_Shuffle(m_Value(V), m_Undef(), m_Mask(Mask))))))
512b6050ca1SSanjay Patel     return false;
513b6050ca1SSanjay Patel 
514b4f04d71SHuihui Zhang   // 1) Do not fold bitcast shuffle for scalable type. First, shuffle cost for
515b4f04d71SHuihui Zhang   // scalable type is unknown; Second, we cannot reason if the narrowed shuffle
516b4f04d71SHuihui Zhang   // mask for scalable type is a splat or not.
517b4f04d71SHuihui Zhang   // 2) Disallow non-vector casts and length-changing shuffles.
518bef6e67eSSanjay Patel   // TODO: We could allow any shuffle.
519b4f04d71SHuihui Zhang   auto *DestTy = dyn_cast<FixedVectorType>(I.getType());
520b4f04d71SHuihui Zhang   auto *SrcTy = dyn_cast<FixedVectorType>(V->getType());
521b4f04d71SHuihui Zhang   if (!SrcTy || !DestTy || I.getOperand(0)->getType() != SrcTy)
522b6050ca1SSanjay Patel     return false;
523b6050ca1SSanjay Patel 
524b4f04d71SHuihui Zhang   unsigned DestNumElts = DestTy->getNumElements();
525b4f04d71SHuihui Zhang   unsigned SrcNumElts = SrcTy->getNumElements();
526b6050ca1SSanjay Patel   SmallVector<int, 16> NewMask;
527bef6e67eSSanjay Patel   if (SrcNumElts <= DestNumElts) {
528bef6e67eSSanjay Patel     // The bitcast is from wide to narrow/equal elements. The shuffle mask can
529bef6e67eSSanjay Patel     // always be expanded to the equivalent form choosing narrower elements.
530b6050ca1SSanjay Patel     assert(DestNumElts % SrcNumElts == 0 && "Unexpected shuffle mask");
531b6050ca1SSanjay Patel     unsigned ScaleFactor = DestNumElts / SrcNumElts;
5321318ddbcSSanjay Patel     narrowShuffleMaskElts(ScaleFactor, Mask, NewMask);
533bef6e67eSSanjay Patel   } else {
534bef6e67eSSanjay Patel     // The bitcast is from narrow elements to wide elements. The shuffle mask
535bef6e67eSSanjay Patel     // must choose consecutive elements to allow casting first.
536bef6e67eSSanjay Patel     assert(SrcNumElts % DestNumElts == 0 && "Unexpected shuffle mask");
537bef6e67eSSanjay Patel     unsigned ScaleFactor = SrcNumElts / DestNumElts;
538bef6e67eSSanjay Patel     if (!widenShuffleMaskElts(ScaleFactor, Mask, NewMask))
539bef6e67eSSanjay Patel       return false;
540bef6e67eSSanjay Patel   }
541e2935dcfSDavid Green 
542e2935dcfSDavid Green   // The new shuffle must not cost more than the old shuffle. The bitcast is
543e2935dcfSDavid Green   // moved ahead of the shuffle, so assume that it has the same cost as before.
544e2935dcfSDavid Green   InstructionCost DestCost = TTI.getShuffleCost(
545e2935dcfSDavid Green       TargetTransformInfo::SK_PermuteSingleSrc, DestTy, NewMask);
546e2935dcfSDavid Green   InstructionCost SrcCost =
547e2935dcfSDavid Green       TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, SrcTy, Mask);
548e2935dcfSDavid Green   if (DestCost > SrcCost || !DestCost.isValid())
549e2935dcfSDavid Green     return false;
550e2935dcfSDavid Green 
551bef6e67eSSanjay Patel   // bitcast (shuf V, MaskC) --> shuf (bitcast V), MaskC'
5527aeb41b3SRoman Lebedev   ++NumShufOfBitcast;
553bef6e67eSSanjay Patel   Value *CastV = Builder.CreateBitCast(V, DestTy);
5541e6b240dSSanjay Patel   Value *Shuf = Builder.CreateShuffleVector(CastV, NewMask);
55598c2f4eeSSanjay Patel   replaceValue(I, *Shuf);
556b6050ca1SSanjay Patel   return true;
557b6050ca1SSanjay Patel }
558b6050ca1SSanjay Patel 
559ed67f5e7SSanjay Patel /// Match a vector binop or compare instruction with at least one inserted
560ed67f5e7SSanjay Patel /// scalar operand and convert to scalar binop/cmp followed by insertelement.
5616bdd531aSSanjay Patel bool VectorCombine::scalarizeBinopOrCmp(Instruction &I) {
562ed67f5e7SSanjay Patel   CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
5635dc4e7c2SSimon Pilgrim   Value *Ins0, *Ins1;
564ed67f5e7SSanjay Patel   if (!match(&I, m_BinOp(m_Value(Ins0), m_Value(Ins1))) &&
565ed67f5e7SSanjay Patel       !match(&I, m_Cmp(Pred, m_Value(Ins0), m_Value(Ins1))))
566ed67f5e7SSanjay Patel     return false;
567ed67f5e7SSanjay Patel 
568ed67f5e7SSanjay Patel   // Do not convert the vector condition of a vector select into a scalar
569ed67f5e7SSanjay Patel   // condition. That may cause problems for codegen because of differences in
570ed67f5e7SSanjay Patel   // boolean formats and register-file transfers.
571ed67f5e7SSanjay Patel   // TODO: Can we account for that in the cost model?
572ed67f5e7SSanjay Patel   bool IsCmp = Pred != CmpInst::Predicate::BAD_ICMP_PREDICATE;
573ed67f5e7SSanjay Patel   if (IsCmp)
574ed67f5e7SSanjay Patel     for (User *U : I.users())
575ed67f5e7SSanjay Patel       if (match(U, m_Select(m_Specific(&I), m_Value(), m_Value())))
5760d2a0b44SSanjay Patel         return false;
5770d2a0b44SSanjay Patel 
5785dc4e7c2SSimon Pilgrim   // Match against one or both scalar values being inserted into constant
5795dc4e7c2SSimon Pilgrim   // vectors:
580ed67f5e7SSanjay Patel   // vec_op VecC0, (inselt VecC1, V1, Index)
581ed67f5e7SSanjay Patel   // vec_op (inselt VecC0, V0, Index), VecC1
582ed67f5e7SSanjay Patel   // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index)
5830d2a0b44SSanjay Patel   // TODO: Deal with mismatched index constants and variable indexes?
5845dc4e7c2SSimon Pilgrim   Constant *VecC0 = nullptr, *VecC1 = nullptr;
5855dc4e7c2SSimon Pilgrim   Value *V0 = nullptr, *V1 = nullptr;
5865dc4e7c2SSimon Pilgrim   uint64_t Index0 = 0, Index1 = 0;
5877eed772aSSanjay Patel   if (!match(Ins0, m_InsertElt(m_Constant(VecC0), m_Value(V0),
5885dc4e7c2SSimon Pilgrim                                m_ConstantInt(Index0))) &&
5895dc4e7c2SSimon Pilgrim       !match(Ins0, m_Constant(VecC0)))
5905dc4e7c2SSimon Pilgrim     return false;
5915dc4e7c2SSimon Pilgrim   if (!match(Ins1, m_InsertElt(m_Constant(VecC1), m_Value(V1),
5925dc4e7c2SSimon Pilgrim                                m_ConstantInt(Index1))) &&
5935dc4e7c2SSimon Pilgrim       !match(Ins1, m_Constant(VecC1)))
5940d2a0b44SSanjay Patel     return false;
5950d2a0b44SSanjay Patel 
5965dc4e7c2SSimon Pilgrim   bool IsConst0 = !V0;
5975dc4e7c2SSimon Pilgrim   bool IsConst1 = !V1;
5985dc4e7c2SSimon Pilgrim   if (IsConst0 && IsConst1)
5995dc4e7c2SSimon Pilgrim     return false;
6005dc4e7c2SSimon Pilgrim   if (!IsConst0 && !IsConst1 && Index0 != Index1)
6015dc4e7c2SSimon Pilgrim     return false;
6025dc4e7c2SSimon Pilgrim 
6035dc4e7c2SSimon Pilgrim   // Bail for single insertion if it is a load.
6045dc4e7c2SSimon Pilgrim   // TODO: Handle this once getVectorInstrCost can cost for load/stores.
6055dc4e7c2SSimon Pilgrim   auto *I0 = dyn_cast_or_null<Instruction>(V0);
6065dc4e7c2SSimon Pilgrim   auto *I1 = dyn_cast_or_null<Instruction>(V1);
6075dc4e7c2SSimon Pilgrim   if ((IsConst0 && I1 && I1->mayReadFromMemory()) ||
6085dc4e7c2SSimon Pilgrim       (IsConst1 && I0 && I0->mayReadFromMemory()))
6095dc4e7c2SSimon Pilgrim     return false;
6105dc4e7c2SSimon Pilgrim 
6115dc4e7c2SSimon Pilgrim   uint64_t Index = IsConst0 ? Index1 : Index0;
6125dc4e7c2SSimon Pilgrim   Type *ScalarTy = IsConst0 ? V1->getType() : V0->getType();
6130d2a0b44SSanjay Patel   Type *VecTy = I.getType();
6145dc4e7c2SSimon Pilgrim   assert(VecTy->isVectorTy() &&
6155dc4e7c2SSimon Pilgrim          (IsConst0 || IsConst1 || V0->getType() == V1->getType()) &&
616741e20f3SSanjay Patel          (ScalarTy->isIntegerTy() || ScalarTy->isFloatingPointTy() ||
617741e20f3SSanjay Patel           ScalarTy->isPointerTy()) &&
618741e20f3SSanjay Patel          "Unexpected types for insert element into binop or cmp");
6190d2a0b44SSanjay Patel 
620ed67f5e7SSanjay Patel   unsigned Opcode = I.getOpcode();
62136710c38SCaroline Concatto   InstructionCost ScalarOpCost, VectorOpCost;
622ed67f5e7SSanjay Patel   if (IsCmp) {
623ed67f5e7SSanjay Patel     ScalarOpCost = TTI.getCmpSelInstrCost(Opcode, ScalarTy);
624ed67f5e7SSanjay Patel     VectorOpCost = TTI.getCmpSelInstrCost(Opcode, VecTy);
625ed67f5e7SSanjay Patel   } else {
626ed67f5e7SSanjay Patel     ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
627ed67f5e7SSanjay Patel     VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
628ed67f5e7SSanjay Patel   }
6290d2a0b44SSanjay Patel 
6300d2a0b44SSanjay Patel   // Get cost estimate for the insert element. This cost will factor into
6310d2a0b44SSanjay Patel   // both sequences.
63236710c38SCaroline Concatto   InstructionCost InsertCost =
6330d2a0b44SSanjay Patel       TTI.getVectorInstrCost(Instruction::InsertElement, VecTy, Index);
63436710c38SCaroline Concatto   InstructionCost OldCost =
63536710c38SCaroline Concatto       (IsConst0 ? 0 : InsertCost) + (IsConst1 ? 0 : InsertCost) + VectorOpCost;
63636710c38SCaroline Concatto   InstructionCost NewCost = ScalarOpCost + InsertCost +
6375dc4e7c2SSimon Pilgrim                             (IsConst0 ? 0 : !Ins0->hasOneUse() * InsertCost) +
6385dc4e7c2SSimon Pilgrim                             (IsConst1 ? 0 : !Ins1->hasOneUse() * InsertCost);
6390d2a0b44SSanjay Patel 
6400d2a0b44SSanjay Patel   // We want to scalarize unless the vector variant actually has lower cost.
64136710c38SCaroline Concatto   if (OldCost < NewCost || !NewCost.isValid())
6420d2a0b44SSanjay Patel     return false;
6430d2a0b44SSanjay Patel 
644ed67f5e7SSanjay Patel   // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index) -->
645ed67f5e7SSanjay Patel   // inselt NewVecC, (scalar_op V0, V1), Index
646ed67f5e7SSanjay Patel   if (IsCmp)
647ed67f5e7SSanjay Patel     ++NumScalarCmp;
648ed67f5e7SSanjay Patel   else
6490d2a0b44SSanjay Patel     ++NumScalarBO;
6505dc4e7c2SSimon Pilgrim 
6515dc4e7c2SSimon Pilgrim   // For constant cases, extract the scalar element, this should constant fold.
6525dc4e7c2SSimon Pilgrim   if (IsConst0)
6535dc4e7c2SSimon Pilgrim     V0 = ConstantExpr::getExtractElement(VecC0, Builder.getInt64(Index));
6545dc4e7c2SSimon Pilgrim   if (IsConst1)
6555dc4e7c2SSimon Pilgrim     V1 = ConstantExpr::getExtractElement(VecC1, Builder.getInt64(Index));
6565dc4e7c2SSimon Pilgrim 
657ed67f5e7SSanjay Patel   Value *Scalar =
65846a285adSSanjay Patel       IsCmp ? Builder.CreateCmp(Pred, V0, V1)
659ed67f5e7SSanjay Patel             : Builder.CreateBinOp((Instruction::BinaryOps)Opcode, V0, V1);
660ed67f5e7SSanjay Patel 
661ed67f5e7SSanjay Patel   Scalar->setName(I.getName() + ".scalar");
6620d2a0b44SSanjay Patel 
6630d2a0b44SSanjay Patel   // All IR flags are safe to back-propagate. There is no potential for extra
6640d2a0b44SSanjay Patel   // poison to be created by the scalar instruction.
6650d2a0b44SSanjay Patel   if (auto *ScalarInst = dyn_cast<Instruction>(Scalar))
6660d2a0b44SSanjay Patel     ScalarInst->copyIRFlags(&I);
6670d2a0b44SSanjay Patel 
6680d2a0b44SSanjay Patel   // Fold the vector constants in the original vectors into a new base vector.
669ed67f5e7SSanjay Patel   Constant *NewVecC = IsCmp ? ConstantExpr::getCompare(Pred, VecC0, VecC1)
670ed67f5e7SSanjay Patel                             : ConstantExpr::get(Opcode, VecC0, VecC1);
6710d2a0b44SSanjay Patel   Value *Insert = Builder.CreateInsertElement(NewVecC, Scalar, Index);
67298c2f4eeSSanjay Patel   replaceValue(I, *Insert);
6730d2a0b44SSanjay Patel   return true;
6740d2a0b44SSanjay Patel }
6750d2a0b44SSanjay Patel 
676b6315aeeSSanjay Patel /// Try to combine a scalar binop + 2 scalar compares of extracted elements of
677b6315aeeSSanjay Patel /// a vector into vector operations followed by extract. Note: The SLP pass
678b6315aeeSSanjay Patel /// may miss this pattern because of implementation problems.
679b6315aeeSSanjay Patel bool VectorCombine::foldExtractedCmps(Instruction &I) {
680b6315aeeSSanjay Patel   // We are looking for a scalar binop of booleans.
681b6315aeeSSanjay Patel   // binop i1 (cmp Pred I0, C0), (cmp Pred I1, C1)
682b6315aeeSSanjay Patel   if (!I.isBinaryOp() || !I.getType()->isIntegerTy(1))
683b6315aeeSSanjay Patel     return false;
684b6315aeeSSanjay Patel 
685b6315aeeSSanjay Patel   // The compare predicates should match, and each compare should have a
686b6315aeeSSanjay Patel   // constant operand.
687b6315aeeSSanjay Patel   // TODO: Relax the one-use constraints.
688b6315aeeSSanjay Patel   Value *B0 = I.getOperand(0), *B1 = I.getOperand(1);
689b6315aeeSSanjay Patel   Instruction *I0, *I1;
690b6315aeeSSanjay Patel   Constant *C0, *C1;
691b6315aeeSSanjay Patel   CmpInst::Predicate P0, P1;
692b6315aeeSSanjay Patel   if (!match(B0, m_OneUse(m_Cmp(P0, m_Instruction(I0), m_Constant(C0)))) ||
693b6315aeeSSanjay Patel       !match(B1, m_OneUse(m_Cmp(P1, m_Instruction(I1), m_Constant(C1)))) ||
694b6315aeeSSanjay Patel       P0 != P1)
695b6315aeeSSanjay Patel     return false;
696b6315aeeSSanjay Patel 
697b6315aeeSSanjay Patel   // The compare operands must be extracts of the same vector with constant
698b6315aeeSSanjay Patel   // extract indexes.
699b6315aeeSSanjay Patel   // TODO: Relax the one-use constraints.
700b6315aeeSSanjay Patel   Value *X;
701b6315aeeSSanjay Patel   uint64_t Index0, Index1;
702b6315aeeSSanjay Patel   if (!match(I0, m_OneUse(m_ExtractElt(m_Value(X), m_ConstantInt(Index0)))) ||
703b6315aeeSSanjay Patel       !match(I1, m_OneUse(m_ExtractElt(m_Specific(X), m_ConstantInt(Index1)))))
704b6315aeeSSanjay Patel     return false;
705b6315aeeSSanjay Patel 
706b6315aeeSSanjay Patel   auto *Ext0 = cast<ExtractElementInst>(I0);
707b6315aeeSSanjay Patel   auto *Ext1 = cast<ExtractElementInst>(I1);
708b6315aeeSSanjay Patel   ExtractElementInst *ConvertToShuf = getShuffleExtract(Ext0, Ext1);
709b6315aeeSSanjay Patel   if (!ConvertToShuf)
710b6315aeeSSanjay Patel     return false;
711b6315aeeSSanjay Patel 
712b6315aeeSSanjay Patel   // The original scalar pattern is:
713b6315aeeSSanjay Patel   // binop i1 (cmp Pred (ext X, Index0), C0), (cmp Pred (ext X, Index1), C1)
714b6315aeeSSanjay Patel   CmpInst::Predicate Pred = P0;
715b6315aeeSSanjay Patel   unsigned CmpOpcode = CmpInst::isFPPredicate(Pred) ? Instruction::FCmp
716b6315aeeSSanjay Patel                                                     : Instruction::ICmp;
717b6315aeeSSanjay Patel   auto *VecTy = dyn_cast<FixedVectorType>(X->getType());
718b6315aeeSSanjay Patel   if (!VecTy)
719b6315aeeSSanjay Patel     return false;
720b6315aeeSSanjay Patel 
72136710c38SCaroline Concatto   InstructionCost OldCost =
72236710c38SCaroline Concatto       TTI.getVectorInstrCost(Ext0->getOpcode(), VecTy, Index0);
723b6315aeeSSanjay Patel   OldCost += TTI.getVectorInstrCost(Ext1->getOpcode(), VecTy, Index1);
724b6315aeeSSanjay Patel   OldCost += TTI.getCmpSelInstrCost(CmpOpcode, I0->getType()) * 2;
725b6315aeeSSanjay Patel   OldCost += TTI.getArithmeticInstrCost(I.getOpcode(), I.getType());
726b6315aeeSSanjay Patel 
727b6315aeeSSanjay Patel   // The proposed vector pattern is:
728b6315aeeSSanjay Patel   // vcmp = cmp Pred X, VecC
729b6315aeeSSanjay Patel   // ext (binop vNi1 vcmp, (shuffle vcmp, Index1)), Index0
730b6315aeeSSanjay Patel   int CheapIndex = ConvertToShuf == Ext0 ? Index1 : Index0;
731b6315aeeSSanjay Patel   int ExpensiveIndex = ConvertToShuf == Ext0 ? Index0 : Index1;
732b6315aeeSSanjay Patel   auto *CmpTy = cast<FixedVectorType>(CmpInst::makeCmpResultType(X->getType()));
73336710c38SCaroline Concatto   InstructionCost NewCost = TTI.getCmpSelInstrCost(CmpOpcode, X->getType());
734e2935dcfSDavid Green   SmallVector<int, 32> ShufMask(VecTy->getNumElements(), UndefMaskElem);
735e2935dcfSDavid Green   ShufMask[CheapIndex] = ExpensiveIndex;
736e2935dcfSDavid Green   NewCost += TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, CmpTy,
737e2935dcfSDavid Green                                 ShufMask);
738b6315aeeSSanjay Patel   NewCost += TTI.getArithmeticInstrCost(I.getOpcode(), CmpTy);
739b6315aeeSSanjay Patel   NewCost += TTI.getVectorInstrCost(Ext0->getOpcode(), CmpTy, CheapIndex);
740b6315aeeSSanjay Patel 
741b6315aeeSSanjay Patel   // Aggressively form vector ops if the cost is equal because the transform
742b6315aeeSSanjay Patel   // may enable further optimization.
743b6315aeeSSanjay Patel   // Codegen can reverse this transform (scalarize) if it was not profitable.
74436710c38SCaroline Concatto   if (OldCost < NewCost || !NewCost.isValid())
745b6315aeeSSanjay Patel     return false;
746b6315aeeSSanjay Patel 
747b6315aeeSSanjay Patel   // Create a vector constant from the 2 scalar constants.
748b6315aeeSSanjay Patel   SmallVector<Constant *, 32> CmpC(VecTy->getNumElements(),
749b6315aeeSSanjay Patel                                    UndefValue::get(VecTy->getElementType()));
750b6315aeeSSanjay Patel   CmpC[Index0] = C0;
751b6315aeeSSanjay Patel   CmpC[Index1] = C1;
752b6315aeeSSanjay Patel   Value *VCmp = Builder.CreateCmp(Pred, X, ConstantVector::get(CmpC));
753b6315aeeSSanjay Patel 
754b6315aeeSSanjay Patel   Value *Shuf = createShiftShuffle(VCmp, ExpensiveIndex, CheapIndex, Builder);
755b6315aeeSSanjay Patel   Value *VecLogic = Builder.CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
756b6315aeeSSanjay Patel                                         VCmp, Shuf);
757b6315aeeSSanjay Patel   Value *NewExt = Builder.CreateExtractElement(VecLogic, CheapIndex);
758b6315aeeSSanjay Patel   replaceValue(I, *NewExt);
759b6315aeeSSanjay Patel   ++NumVecCmpBO;
760b6315aeeSSanjay Patel   return true;
761b6315aeeSSanjay Patel }
762b6315aeeSSanjay Patel 
7632db4979cSQiu Chaofan // Check if memory loc modified between two instrs in the same BB
7642db4979cSQiu Chaofan static bool isMemModifiedBetween(BasicBlock::iterator Begin,
7652db4979cSQiu Chaofan                                  BasicBlock::iterator End,
7662db4979cSQiu Chaofan                                  const MemoryLocation &Loc, AAResults &AA) {
7672db4979cSQiu Chaofan   unsigned NumScanned = 0;
7682db4979cSQiu Chaofan   return std::any_of(Begin, End, [&](const Instruction &Instr) {
7692db4979cSQiu Chaofan     return isModSet(AA.getModRefInfo(&Instr, Loc)) ||
7702db4979cSQiu Chaofan            ++NumScanned > MaxInstrsToScan;
7712db4979cSQiu Chaofan   });
7722db4979cSQiu Chaofan }
7732db4979cSQiu Chaofan 
7742db4979cSQiu Chaofan // Combine patterns like:
7752db4979cSQiu Chaofan //   %0 = load <4 x i32>, <4 x i32>* %a
7762db4979cSQiu Chaofan //   %1 = insertelement <4 x i32> %0, i32 %b, i32 1
7772db4979cSQiu Chaofan //   store <4 x i32> %1, <4 x i32>* %a
7782db4979cSQiu Chaofan // to:
7792db4979cSQiu Chaofan //   %0 = bitcast <4 x i32>* %a to i32*
7802db4979cSQiu Chaofan //   %1 = getelementptr inbounds i32, i32* %0, i64 0, i64 1
7812db4979cSQiu Chaofan //   store i32 %b, i32* %1
7822db4979cSQiu Chaofan bool VectorCombine::foldSingleElementStore(Instruction &I) {
7832db4979cSQiu Chaofan   StoreInst *SI = dyn_cast<StoreInst>(&I);
784*6d2df181SQiu Chaofan   if (!SI || !SI->isSimple() ||
785*6d2df181SQiu Chaofan       !isa<FixedVectorType>(SI->getValueOperand()->getType()))
7862db4979cSQiu Chaofan     return false;
7872db4979cSQiu Chaofan 
7882db4979cSQiu Chaofan   // TODO: Combine more complicated patterns (multiple insert) by referencing
7892db4979cSQiu Chaofan   // TargetTransformInfo.
7902db4979cSQiu Chaofan   Instruction *Source;
791*6d2df181SQiu Chaofan   Value *NewElement;
792*6d2df181SQiu Chaofan   ConstantInt *Idx;
7932db4979cSQiu Chaofan   if (!match(SI->getValueOperand(),
7942db4979cSQiu Chaofan              m_InsertElt(m_Instruction(Source), m_Value(NewElement),
795*6d2df181SQiu Chaofan                          m_ConstantInt(Idx))))
7962db4979cSQiu Chaofan     return false;
7972db4979cSQiu Chaofan 
7982db4979cSQiu Chaofan   if (auto *Load = dyn_cast<LoadInst>(Source)) {
799*6d2df181SQiu Chaofan     auto VecTy = cast<FixedVectorType>(SI->getValueOperand()->getType());
8002db4979cSQiu Chaofan     const DataLayout &DL = I.getModule()->getDataLayout();
8012db4979cSQiu Chaofan     Value *SrcAddr = Load->getPointerOperand()->stripPointerCasts();
802*6d2df181SQiu Chaofan     // Don't optimize for atomic/volatile load or store. Ensure memory is not
803*6d2df181SQiu Chaofan     // modified between, vector type matches store size, and index is inbounds.
8042db4979cSQiu Chaofan     if (!Load->isSimple() || Load->getParent() != SI->getParent() ||
8052db4979cSQiu Chaofan         !DL.typeSizeEqualsStoreSize(Load->getType()) ||
806*6d2df181SQiu Chaofan         Idx->uge(VecTy->getNumElements()) ||
8072db4979cSQiu Chaofan         SrcAddr != SI->getPointerOperand()->stripPointerCasts() ||
8082db4979cSQiu Chaofan         isMemModifiedBetween(Load->getIterator(), SI->getIterator(),
8092db4979cSQiu Chaofan                              MemoryLocation::get(SI), AA))
8102db4979cSQiu Chaofan       return false;
8112db4979cSQiu Chaofan 
8122db4979cSQiu Chaofan     Value *GEP = GetElementPtrInst::CreateInBounds(
8132db4979cSQiu Chaofan         SI->getPointerOperand(), {ConstantInt::get(Idx->getType(), 0), Idx});
8142db4979cSQiu Chaofan     Builder.Insert(GEP);
8152db4979cSQiu Chaofan     StoreInst *NSI = Builder.CreateStore(NewElement, GEP);
8162db4979cSQiu Chaofan     NSI->copyMetadata(*SI);
8172db4979cSQiu Chaofan     if (SI->getAlign() < NSI->getAlign())
8182db4979cSQiu Chaofan       NSI->setAlignment(SI->getAlign());
8192db4979cSQiu Chaofan     replaceValue(I, *NSI);
8202db4979cSQiu Chaofan     // Need erasing the store manually.
8212db4979cSQiu Chaofan     I.eraseFromParent();
8222db4979cSQiu Chaofan     return true;
8232db4979cSQiu Chaofan   }
8242db4979cSQiu Chaofan 
8252db4979cSQiu Chaofan   return false;
8262db4979cSQiu Chaofan }
8272db4979cSQiu Chaofan 
828a17f03bdSSanjay Patel /// This is the entry point for all transforms. Pass manager differences are
829a17f03bdSSanjay Patel /// handled in the callers of this function.
8306bdd531aSSanjay Patel bool VectorCombine::run() {
83125c6544fSSanjay Patel   if (DisableVectorCombine)
83225c6544fSSanjay Patel     return false;
83325c6544fSSanjay Patel 
834cc892fd9SSanjay Patel   // Don't attempt vectorization if the target does not support vectors.
835cc892fd9SSanjay Patel   if (!TTI.getNumberOfRegisters(TTI.getRegisterClassForType(/*Vector*/ true)))
836cc892fd9SSanjay Patel     return false;
837cc892fd9SSanjay Patel 
838a17f03bdSSanjay Patel   bool MadeChange = false;
839a17f03bdSSanjay Patel   for (BasicBlock &BB : F) {
840a17f03bdSSanjay Patel     // Ignore unreachable basic blocks.
841a17f03bdSSanjay Patel     if (!DT.isReachableFromEntry(&BB))
842a17f03bdSSanjay Patel       continue;
8432db4979cSQiu Chaofan     // Use early increment range so that we can erase instructions in loop.
8442db4979cSQiu Chaofan     for (Instruction &I : make_early_inc_range(BB)) {
845fc3cc8a4SSanjay Patel       if (isa<DbgInfoIntrinsic>(I))
846fc3cc8a4SSanjay Patel         continue;
847de65b356SSanjay Patel       Builder.SetInsertPoint(&I);
84843bdac29SSanjay Patel       MadeChange |= vectorizeLoadInsert(I);
8496bdd531aSSanjay Patel       MadeChange |= foldExtractExtract(I);
8506bdd531aSSanjay Patel       MadeChange |= foldBitcastShuf(I);
8516bdd531aSSanjay Patel       MadeChange |= scalarizeBinopOrCmp(I);
852b6315aeeSSanjay Patel       MadeChange |= foldExtractedCmps(I);
8532db4979cSQiu Chaofan       MadeChange |= foldSingleElementStore(I);
854a17f03bdSSanjay Patel     }
855fc3cc8a4SSanjay Patel   }
856a17f03bdSSanjay Patel 
857a17f03bdSSanjay Patel   // We're done with transforms, so remove dead instructions.
858a17f03bdSSanjay Patel   if (MadeChange)
859a17f03bdSSanjay Patel     for (BasicBlock &BB : F)
860a17f03bdSSanjay Patel       SimplifyInstructionsInBlock(&BB);
861a17f03bdSSanjay Patel 
862a17f03bdSSanjay Patel   return MadeChange;
863a17f03bdSSanjay Patel }
864a17f03bdSSanjay Patel 
865a17f03bdSSanjay Patel // Pass manager boilerplate below here.
866a17f03bdSSanjay Patel 
867a17f03bdSSanjay Patel namespace {
868a17f03bdSSanjay Patel class VectorCombineLegacyPass : public FunctionPass {
869a17f03bdSSanjay Patel public:
870a17f03bdSSanjay Patel   static char ID;
871a17f03bdSSanjay Patel   VectorCombineLegacyPass() : FunctionPass(ID) {
872a17f03bdSSanjay Patel     initializeVectorCombineLegacyPassPass(*PassRegistry::getPassRegistry());
873a17f03bdSSanjay Patel   }
874a17f03bdSSanjay Patel 
875a17f03bdSSanjay Patel   void getAnalysisUsage(AnalysisUsage &AU) const override {
876a17f03bdSSanjay Patel     AU.addRequired<DominatorTreeWrapperPass>();
877a17f03bdSSanjay Patel     AU.addRequired<TargetTransformInfoWrapperPass>();
8782db4979cSQiu Chaofan     AU.addRequired<AAResultsWrapperPass>();
879a17f03bdSSanjay Patel     AU.setPreservesCFG();
880a17f03bdSSanjay Patel     AU.addPreserved<DominatorTreeWrapperPass>();
881a17f03bdSSanjay Patel     AU.addPreserved<GlobalsAAWrapperPass>();
882024098aeSSanjay Patel     AU.addPreserved<AAResultsWrapperPass>();
883024098aeSSanjay Patel     AU.addPreserved<BasicAAWrapperPass>();
884a17f03bdSSanjay Patel     FunctionPass::getAnalysisUsage(AU);
885a17f03bdSSanjay Patel   }
886a17f03bdSSanjay Patel 
887a17f03bdSSanjay Patel   bool runOnFunction(Function &F) override {
888a17f03bdSSanjay Patel     if (skipFunction(F))
889a17f03bdSSanjay Patel       return false;
890a17f03bdSSanjay Patel     auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
891a17f03bdSSanjay Patel     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
8922db4979cSQiu Chaofan     auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
8932db4979cSQiu Chaofan     VectorCombine Combiner(F, TTI, DT, AA);
8946bdd531aSSanjay Patel     return Combiner.run();
895a17f03bdSSanjay Patel   }
896a17f03bdSSanjay Patel };
897a17f03bdSSanjay Patel } // namespace
898a17f03bdSSanjay Patel 
899a17f03bdSSanjay Patel char VectorCombineLegacyPass::ID = 0;
900a17f03bdSSanjay Patel INITIALIZE_PASS_BEGIN(VectorCombineLegacyPass, "vector-combine",
901a17f03bdSSanjay Patel                       "Optimize scalar/vector ops", false,
902a17f03bdSSanjay Patel                       false)
903a17f03bdSSanjay Patel INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
904a17f03bdSSanjay Patel INITIALIZE_PASS_END(VectorCombineLegacyPass, "vector-combine",
905a17f03bdSSanjay Patel                     "Optimize scalar/vector ops", false, false)
906a17f03bdSSanjay Patel Pass *llvm::createVectorCombinePass() {
907a17f03bdSSanjay Patel   return new VectorCombineLegacyPass();
908a17f03bdSSanjay Patel }
909a17f03bdSSanjay Patel 
910a17f03bdSSanjay Patel PreservedAnalyses VectorCombinePass::run(Function &F,
911a17f03bdSSanjay Patel                                          FunctionAnalysisManager &FAM) {
912a17f03bdSSanjay Patel   TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(F);
913a17f03bdSSanjay Patel   DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F);
9142db4979cSQiu Chaofan   AAResults &AA = FAM.getResult<AAManager>(F);
9152db4979cSQiu Chaofan   VectorCombine Combiner(F, TTI, DT, AA);
9166bdd531aSSanjay Patel   if (!Combiner.run())
917a17f03bdSSanjay Patel     return PreservedAnalyses::all();
918a17f03bdSSanjay Patel   PreservedAnalyses PA;
919a17f03bdSSanjay Patel   PA.preserveSet<CFGAnalyses>();
920a17f03bdSSanjay Patel   PA.preserve<GlobalsAA>();
921024098aeSSanjay Patel   PA.preserve<AAManager>();
922024098aeSSanjay Patel   PA.preserve<BasicAA>();
923a17f03bdSSanjay Patel   return PA;
924a17f03bdSSanjay Patel }
925