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"
17*575e2affSFlorian Hahn #include "llvm/Analysis/AssumptionCache.h"
185006e551SSimon Pilgrim #include "llvm/Analysis/BasicAliasAnalysis.h"
19a17f03bdSSanjay Patel #include "llvm/Analysis/GlobalsModRef.h"
2043bdac29SSanjay Patel #include "llvm/Analysis/Loads.h"
21a17f03bdSSanjay Patel #include "llvm/Analysis/TargetTransformInfo.h"
2219b62b79SSanjay Patel #include "llvm/Analysis/ValueTracking.h"
23b6050ca1SSanjay Patel #include "llvm/Analysis/VectorUtils.h"
24a17f03bdSSanjay Patel #include "llvm/IR/Dominators.h"
25a17f03bdSSanjay Patel #include "llvm/IR/Function.h"
26a17f03bdSSanjay Patel #include "llvm/IR/IRBuilder.h"
27a17f03bdSSanjay Patel #include "llvm/IR/PatternMatch.h"
28a17f03bdSSanjay Patel #include "llvm/InitializePasses.h"
29a17f03bdSSanjay Patel #include "llvm/Pass.h"
3025c6544fSSanjay Patel #include "llvm/Support/CommandLine.h"
31a17f03bdSSanjay Patel #include "llvm/Transforms/Utils/Local.h"
325006e551SSimon Pilgrim #include "llvm/Transforms/Vectorize.h"
33a17f03bdSSanjay Patel 
34a17f03bdSSanjay Patel using namespace llvm;
35a17f03bdSSanjay Patel using namespace llvm::PatternMatch;
36a17f03bdSSanjay Patel 
37a17f03bdSSanjay Patel #define DEBUG_TYPE "vector-combine"
3843bdac29SSanjay Patel STATISTIC(NumVecLoad, "Number of vector loads formed");
39a17f03bdSSanjay Patel STATISTIC(NumVecCmp, "Number of vector compares formed");
4019b62b79SSanjay Patel STATISTIC(NumVecBO, "Number of vector binops formed");
41b6315aeeSSanjay Patel STATISTIC(NumVecCmpBO, "Number of vector compare + binop formed");
427aeb41b3SRoman Lebedev STATISTIC(NumShufOfBitcast, "Number of shuffles moved after bitcast");
430d2a0b44SSanjay Patel STATISTIC(NumScalarBO, "Number of scalar binops formed");
44ed67f5e7SSanjay Patel STATISTIC(NumScalarCmp, "Number of scalar compares formed");
45a17f03bdSSanjay Patel 
4625c6544fSSanjay Patel static cl::opt<bool> DisableVectorCombine(
4725c6544fSSanjay Patel     "disable-vector-combine", cl::init(false), cl::Hidden,
4825c6544fSSanjay Patel     cl::desc("Disable all vector combine transforms"));
4925c6544fSSanjay Patel 
50a69158c1SSanjay Patel static cl::opt<bool> DisableBinopExtractShuffle(
51a69158c1SSanjay Patel     "disable-binop-extract-shuffle", cl::init(false), cl::Hidden,
52a69158c1SSanjay Patel     cl::desc("Disable binop extract to shuffle transforms"));
53a69158c1SSanjay Patel 
542db4979cSQiu Chaofan static cl::opt<unsigned> MaxInstrsToScan(
552db4979cSQiu Chaofan     "vector-combine-max-scan-instrs", cl::init(30), cl::Hidden,
562db4979cSQiu Chaofan     cl::desc("Max number of instructions to scan for vector combining."));
572db4979cSQiu Chaofan 
58a0f96741SSanjay Patel static const unsigned InvalidIndex = std::numeric_limits<unsigned>::max();
59a0f96741SSanjay Patel 
60b4447054SBenjamin Kramer namespace {
616bdd531aSSanjay Patel class VectorCombine {
626bdd531aSSanjay Patel public:
636bdd531aSSanjay Patel   VectorCombine(Function &F, const TargetTransformInfo &TTI,
64*575e2affSFlorian Hahn                 const DominatorTree &DT, AAResults &AA, AssumptionCache &AC)
65*575e2affSFlorian Hahn       : F(F), Builder(F.getContext()), TTI(TTI), DT(DT), AA(AA), AC(AC) {}
666bdd531aSSanjay Patel 
676bdd531aSSanjay Patel   bool run();
686bdd531aSSanjay Patel 
696bdd531aSSanjay Patel private:
706bdd531aSSanjay Patel   Function &F;
71de65b356SSanjay Patel   IRBuilder<> Builder;
726bdd531aSSanjay Patel   const TargetTransformInfo &TTI;
736bdd531aSSanjay Patel   const DominatorTree &DT;
742db4979cSQiu Chaofan   AAResults &AA;
75*575e2affSFlorian Hahn   AssumptionCache &AC;
766bdd531aSSanjay Patel 
7743bdac29SSanjay Patel   bool vectorizeLoadInsert(Instruction &I);
783b95d834SSanjay Patel   ExtractElementInst *getShuffleExtract(ExtractElementInst *Ext0,
793b95d834SSanjay Patel                                         ExtractElementInst *Ext1,
803b95d834SSanjay Patel                                         unsigned PreferredExtractIndex) const;
816bdd531aSSanjay Patel   bool isExtractExtractCheap(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
826bdd531aSSanjay Patel                              unsigned Opcode,
836bdd531aSSanjay Patel                              ExtractElementInst *&ConvertToShuffle,
846bdd531aSSanjay Patel                              unsigned PreferredExtractIndex);
85de65b356SSanjay Patel   void foldExtExtCmp(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
86de65b356SSanjay Patel                      Instruction &I);
87de65b356SSanjay Patel   void foldExtExtBinop(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
88de65b356SSanjay Patel                        Instruction &I);
896bdd531aSSanjay Patel   bool foldExtractExtract(Instruction &I);
906bdd531aSSanjay Patel   bool foldBitcastShuf(Instruction &I);
916bdd531aSSanjay Patel   bool scalarizeBinopOrCmp(Instruction &I);
92b6315aeeSSanjay Patel   bool foldExtractedCmps(Instruction &I);
932db4979cSQiu Chaofan   bool foldSingleElementStore(Instruction &I);
944e8c28b6SFlorian Hahn   bool scalarizeLoadExtract(Instruction &I);
956bdd531aSSanjay Patel };
96b4447054SBenjamin Kramer } // namespace
97a69158c1SSanjay Patel 
9898c2f4eeSSanjay Patel static void replaceValue(Value &Old, Value &New) {
9998c2f4eeSSanjay Patel   Old.replaceAllUsesWith(&New);
10098c2f4eeSSanjay Patel   New.takeName(&Old);
10198c2f4eeSSanjay Patel }
10298c2f4eeSSanjay Patel 
10343bdac29SSanjay Patel bool VectorCombine::vectorizeLoadInsert(Instruction &I) {
104b2ef2640SSanjay Patel   // Match insert into fixed vector of scalar value.
10547aaa99cSSanjay Patel   // TODO: Handle non-zero insert index.
106ddd9575dSSanjay Patel   auto *Ty = dyn_cast<FixedVectorType>(I.getType());
10743bdac29SSanjay Patel   Value *Scalar;
10848a23bccSSanjay Patel   if (!Ty || !match(&I, m_InsertElt(m_Undef(), m_Value(Scalar), m_ZeroInt())) ||
10948a23bccSSanjay Patel       !Scalar->hasOneUse())
11043bdac29SSanjay Patel     return false;
111ddd9575dSSanjay Patel 
112b2ef2640SSanjay Patel   // Optionally match an extract from another vector.
113b2ef2640SSanjay Patel   Value *X;
114b2ef2640SSanjay Patel   bool HasExtract = match(Scalar, m_ExtractElt(m_Value(X), m_ZeroInt()));
115b2ef2640SSanjay Patel   if (!HasExtract)
116b2ef2640SSanjay Patel     X = Scalar;
117b2ef2640SSanjay Patel 
118b2ef2640SSanjay Patel   // Match source value as load of scalar or vector.
1194452cc40SFangrui Song   // Do not vectorize scalar load (widening) if atomic/volatile or under
1204452cc40SFangrui Song   // asan/hwasan/memtag/tsan. The widened load may load data from dirty regions
1214452cc40SFangrui Song   // or create data races non-existent in the source.
122b2ef2640SSanjay Patel   auto *Load = dyn_cast<LoadInst>(X);
123b2ef2640SSanjay Patel   if (!Load || !Load->isSimple() || !Load->hasOneUse() ||
1244452cc40SFangrui Song       Load->getFunction()->hasFnAttribute(Attribute::SanitizeMemTag) ||
1254452cc40SFangrui Song       mustSuppressSpeculation(*Load))
12643bdac29SSanjay Patel     return false;
12743bdac29SSanjay Patel 
12812b684aeSSanjay Patel   const DataLayout &DL = I.getModule()->getDataLayout();
12912b684aeSSanjay Patel   Value *SrcPtr = Load->getPointerOperand()->stripPointerCasts();
13012b684aeSSanjay Patel   assert(isa<PointerType>(SrcPtr->getType()) && "Expected a pointer type");
131c36c0fabSArtem Belevich 
132c36c0fabSArtem Belevich   // If original AS != Load's AS, we can't bitcast the original pointer and have
133c36c0fabSArtem Belevich   // to use Load's operand instead. Ideally we would want to strip pointer casts
134c36c0fabSArtem Belevich   // without changing AS, but there's no API to do that ATM.
13512b684aeSSanjay Patel   unsigned AS = Load->getPointerAddressSpace();
13612b684aeSSanjay Patel   if (AS != SrcPtr->getType()->getPointerAddressSpace())
13712b684aeSSanjay Patel     SrcPtr = Load->getPointerOperand();
13843bdac29SSanjay Patel 
13947aaa99cSSanjay Patel   // We are potentially transforming byte-sized (8-bit) memory accesses, so make
14047aaa99cSSanjay Patel   // sure we have all of our type-based constraints in place for this target.
141ddd9575dSSanjay Patel   Type *ScalarTy = Scalar->getType();
14243bdac29SSanjay Patel   uint64_t ScalarSize = ScalarTy->getPrimitiveSizeInBits();
143ddd9575dSSanjay Patel   unsigned MinVectorSize = TTI.getMinVectorRegisterBitWidth();
14447aaa99cSSanjay Patel   if (!ScalarSize || !MinVectorSize || MinVectorSize % ScalarSize != 0 ||
14547aaa99cSSanjay Patel       ScalarSize % 8 != 0)
14643bdac29SSanjay Patel     return false;
14743bdac29SSanjay Patel 
14843bdac29SSanjay Patel   // Check safety of replacing the scalar load with a larger vector load.
149aaaf0ec7SSanjay Patel   // We use minimal alignment (maximum flexibility) because we only care about
150aaaf0ec7SSanjay Patel   // the dereferenceable region. When calculating cost and creating a new op,
151aaaf0ec7SSanjay Patel   // we may use a larger value based on alignment attributes.
1528fb05593SSanjay Patel   unsigned MinVecNumElts = MinVectorSize / ScalarSize;
1538fb05593SSanjay Patel   auto *MinVecTy = VectorType::get(ScalarTy, MinVecNumElts, false);
15447aaa99cSSanjay Patel   unsigned OffsetEltIndex = 0;
15547aaa99cSSanjay Patel   Align Alignment = Load->getAlign();
15647aaa99cSSanjay Patel   if (!isSafeToLoadUnconditionally(SrcPtr, MinVecTy, Align(1), DL, Load, &DT)) {
15747aaa99cSSanjay Patel     // It is not safe to load directly from the pointer, but we can still peek
15847aaa99cSSanjay Patel     // through gep offsets and check if it safe to load from a base address with
15947aaa99cSSanjay Patel     // updated alignment. If it is, we can shuffle the element(s) into place
16047aaa99cSSanjay Patel     // after loading.
16147aaa99cSSanjay Patel     unsigned OffsetBitWidth = DL.getIndexTypeSizeInBits(SrcPtr->getType());
16247aaa99cSSanjay Patel     APInt Offset(OffsetBitWidth, 0);
16347aaa99cSSanjay Patel     SrcPtr = SrcPtr->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
16447aaa99cSSanjay Patel 
16547aaa99cSSanjay Patel     // We want to shuffle the result down from a high element of a vector, so
16647aaa99cSSanjay Patel     // the offset must be positive.
16747aaa99cSSanjay Patel     if (Offset.isNegative())
16847aaa99cSSanjay Patel       return false;
16947aaa99cSSanjay Patel 
17047aaa99cSSanjay Patel     // The offset must be a multiple of the scalar element to shuffle cleanly
17147aaa99cSSanjay Patel     // in the element's size.
17247aaa99cSSanjay Patel     uint64_t ScalarSizeInBytes = ScalarSize / 8;
17347aaa99cSSanjay Patel     if (Offset.urem(ScalarSizeInBytes) != 0)
17447aaa99cSSanjay Patel       return false;
17547aaa99cSSanjay Patel 
17647aaa99cSSanjay Patel     // If we load MinVecNumElts, will our target element still be loaded?
17747aaa99cSSanjay Patel     OffsetEltIndex = Offset.udiv(ScalarSizeInBytes).getZExtValue();
17847aaa99cSSanjay Patel     if (OffsetEltIndex >= MinVecNumElts)
17947aaa99cSSanjay Patel       return false;
18047aaa99cSSanjay Patel 
181aaaf0ec7SSanjay Patel     if (!isSafeToLoadUnconditionally(SrcPtr, MinVecTy, Align(1), DL, Load, &DT))
18243bdac29SSanjay Patel       return false;
18343bdac29SSanjay Patel 
18447aaa99cSSanjay Patel     // Update alignment with offset value. Note that the offset could be negated
18547aaa99cSSanjay Patel     // to more accurately represent "(new) SrcPtr - Offset = (old) SrcPtr", but
18647aaa99cSSanjay Patel     // negation does not change the result of the alignment calculation.
18747aaa99cSSanjay Patel     Alignment = commonAlignment(Alignment, Offset.getZExtValue());
18847aaa99cSSanjay Patel   }
18947aaa99cSSanjay Patel 
190b2ef2640SSanjay Patel   // Original pattern: insertelt undef, load [free casts of] PtrOp, 0
19138ebc1a1SSanjay Patel   // Use the greater of the alignment on the load or its source pointer.
19247aaa99cSSanjay Patel   Alignment = std::max(SrcPtr->getPointerAlignment(DL), Alignment);
193b2ef2640SSanjay Patel   Type *LoadTy = Load->getType();
19436710c38SCaroline Concatto   InstructionCost OldCost =
19536710c38SCaroline Concatto       TTI.getMemoryOpCost(Instruction::Load, LoadTy, Alignment, AS);
1968fb05593SSanjay Patel   APInt DemandedElts = APInt::getOneBitSet(MinVecNumElts, 0);
197b2ef2640SSanjay Patel   OldCost += TTI.getScalarizationOverhead(MinVecTy, DemandedElts,
198b2ef2640SSanjay Patel                                           /* Insert */ true, HasExtract);
19943bdac29SSanjay Patel 
20043bdac29SSanjay Patel   // New pattern: load VecPtr
20136710c38SCaroline Concatto   InstructionCost NewCost =
20236710c38SCaroline Concatto       TTI.getMemoryOpCost(Instruction::Load, MinVecTy, Alignment, AS);
20347aaa99cSSanjay Patel   // Optionally, we are shuffling the loaded vector element(s) into place.
204e2935dcfSDavid Green   // For the mask set everything but element 0 to undef to prevent poison from
205e2935dcfSDavid Green   // propagating from the extra loaded memory. This will also optionally
206e2935dcfSDavid Green   // shrink/grow the vector from the loaded size to the output size.
207e2935dcfSDavid Green   // We assume this operation has no cost in codegen if there was no offset.
208e2935dcfSDavid Green   // Note that we could use freeze to avoid poison problems, but then we might
209e2935dcfSDavid Green   // still need a shuffle to change the vector size.
210e2935dcfSDavid Green   unsigned OutputNumElts = Ty->getNumElements();
211e2935dcfSDavid Green   SmallVector<int, 16> Mask(OutputNumElts, UndefMaskElem);
212e2935dcfSDavid Green   assert(OffsetEltIndex < MinVecNumElts && "Address offset too big");
213e2935dcfSDavid Green   Mask[0] = OffsetEltIndex;
21447aaa99cSSanjay Patel   if (OffsetEltIndex)
215e2935dcfSDavid Green     NewCost += TTI.getShuffleCost(TTI::SK_PermuteSingleSrc, MinVecTy, Mask);
21643bdac29SSanjay Patel 
21743bdac29SSanjay Patel   // We can aggressively convert to the vector form because the backend can
21843bdac29SSanjay Patel   // invert this transform if it does not result in a performance win.
21936710c38SCaroline Concatto   if (OldCost < NewCost || !NewCost.isValid())
22043bdac29SSanjay Patel     return false;
22143bdac29SSanjay Patel 
22243bdac29SSanjay Patel   // It is safe and potentially profitable to load a vector directly:
22343bdac29SSanjay Patel   // inselt undef, load Scalar, 0 --> load VecPtr
22443bdac29SSanjay Patel   IRBuilder<> Builder(Load);
22512b684aeSSanjay Patel   Value *CastedPtr = Builder.CreateBitCast(SrcPtr, MinVecTy->getPointerTo(AS));
2268fb05593SSanjay Patel   Value *VecLd = Builder.CreateAlignedLoad(MinVecTy, CastedPtr, Alignment);
2271e6b240dSSanjay Patel   VecLd = Builder.CreateShuffleVector(VecLd, Mask);
228d399f870SSanjay Patel 
22943bdac29SSanjay Patel   replaceValue(I, *VecLd);
23043bdac29SSanjay Patel   ++NumVecLoad;
23143bdac29SSanjay Patel   return true;
23243bdac29SSanjay Patel }
23343bdac29SSanjay Patel 
2343b95d834SSanjay Patel /// Determine which, if any, of the inputs should be replaced by a shuffle
2353b95d834SSanjay Patel /// followed by extract from a different index.
2363b95d834SSanjay Patel ExtractElementInst *VectorCombine::getShuffleExtract(
2373b95d834SSanjay Patel     ExtractElementInst *Ext0, ExtractElementInst *Ext1,
2383b95d834SSanjay Patel     unsigned PreferredExtractIndex = InvalidIndex) const {
2393b95d834SSanjay Patel   assert(isa<ConstantInt>(Ext0->getIndexOperand()) &&
2403b95d834SSanjay Patel          isa<ConstantInt>(Ext1->getIndexOperand()) &&
2413b95d834SSanjay Patel          "Expected constant extract indexes");
2423b95d834SSanjay Patel 
2433b95d834SSanjay Patel   unsigned Index0 = cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue();
2443b95d834SSanjay Patel   unsigned Index1 = cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue();
2453b95d834SSanjay Patel 
2463b95d834SSanjay Patel   // If the extract indexes are identical, no shuffle is needed.
2473b95d834SSanjay Patel   if (Index0 == Index1)
2483b95d834SSanjay Patel     return nullptr;
2493b95d834SSanjay Patel 
2503b95d834SSanjay Patel   Type *VecTy = Ext0->getVectorOperand()->getType();
2513b95d834SSanjay Patel   assert(VecTy == Ext1->getVectorOperand()->getType() && "Need matching types");
25236710c38SCaroline Concatto   InstructionCost Cost0 =
25336710c38SCaroline Concatto       TTI.getVectorInstrCost(Ext0->getOpcode(), VecTy, Index0);
25436710c38SCaroline Concatto   InstructionCost Cost1 =
25536710c38SCaroline Concatto       TTI.getVectorInstrCost(Ext1->getOpcode(), VecTy, Index1);
25636710c38SCaroline Concatto 
25736710c38SCaroline Concatto   // If both costs are invalid no shuffle is needed
25836710c38SCaroline Concatto   if (!Cost0.isValid() && !Cost1.isValid())
25936710c38SCaroline Concatto     return nullptr;
2603b95d834SSanjay Patel 
2613b95d834SSanjay Patel   // We are extracting from 2 different indexes, so one operand must be shuffled
2623b95d834SSanjay Patel   // before performing a vector operation and/or extract. The more expensive
2633b95d834SSanjay Patel   // extract will be replaced by a shuffle.
2643b95d834SSanjay Patel   if (Cost0 > Cost1)
2653b95d834SSanjay Patel     return Ext0;
2663b95d834SSanjay Patel   if (Cost1 > Cost0)
2673b95d834SSanjay Patel     return Ext1;
2683b95d834SSanjay Patel 
2693b95d834SSanjay Patel   // If the costs are equal and there is a preferred extract index, shuffle the
2703b95d834SSanjay Patel   // opposite operand.
2713b95d834SSanjay Patel   if (PreferredExtractIndex == Index0)
2723b95d834SSanjay Patel     return Ext1;
2733b95d834SSanjay Patel   if (PreferredExtractIndex == Index1)
2743b95d834SSanjay Patel     return Ext0;
2753b95d834SSanjay Patel 
2763b95d834SSanjay Patel   // Otherwise, replace the extract with the higher index.
2773b95d834SSanjay Patel   return Index0 > Index1 ? Ext0 : Ext1;
2783b95d834SSanjay Patel }
2793b95d834SSanjay Patel 
280a69158c1SSanjay Patel /// Compare the relative costs of 2 extracts followed by scalar operation vs.
281a69158c1SSanjay Patel /// vector operation(s) followed by extract. Return true if the existing
282a69158c1SSanjay Patel /// instructions are cheaper than a vector alternative. Otherwise, return false
283a69158c1SSanjay Patel /// and if one of the extracts should be transformed to a shufflevector, set
284a69158c1SSanjay Patel /// \p ConvertToShuffle to that extract instruction.
2856bdd531aSSanjay Patel bool VectorCombine::isExtractExtractCheap(ExtractElementInst *Ext0,
2866bdd531aSSanjay Patel                                           ExtractElementInst *Ext1,
2876bdd531aSSanjay Patel                                           unsigned Opcode,
288216a37bbSSanjay Patel                                           ExtractElementInst *&ConvertToShuffle,
289ce97ce3aSSanjay Patel                                           unsigned PreferredExtractIndex) {
2904fa63fd4SAustin Kerbow   assert(isa<ConstantInt>(Ext0->getOperand(1)) &&
291a69158c1SSanjay Patel          isa<ConstantInt>(Ext1->getOperand(1)) &&
292a69158c1SSanjay Patel          "Expected constant extract indexes");
29334e34855SSanjay Patel   Type *ScalarTy = Ext0->getType();
294e3056ae9SSam Parker   auto *VecTy = cast<VectorType>(Ext0->getOperand(0)->getType());
29536710c38SCaroline Concatto   InstructionCost ScalarOpCost, VectorOpCost;
29634e34855SSanjay Patel 
29734e34855SSanjay Patel   // Get cost estimates for scalar and vector versions of the operation.
29834e34855SSanjay Patel   bool IsBinOp = Instruction::isBinaryOp(Opcode);
29934e34855SSanjay Patel   if (IsBinOp) {
30034e34855SSanjay Patel     ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
30134e34855SSanjay Patel     VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
30234e34855SSanjay Patel   } else {
30334e34855SSanjay Patel     assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
30434e34855SSanjay Patel            "Expected a compare");
30534e34855SSanjay Patel     ScalarOpCost = TTI.getCmpSelInstrCost(Opcode, ScalarTy,
30634e34855SSanjay Patel                                           CmpInst::makeCmpResultType(ScalarTy));
30734e34855SSanjay Patel     VectorOpCost = TTI.getCmpSelInstrCost(Opcode, VecTy,
30834e34855SSanjay Patel                                           CmpInst::makeCmpResultType(VecTy));
30934e34855SSanjay Patel   }
31034e34855SSanjay Patel 
311a69158c1SSanjay Patel   // Get cost estimates for the extract elements. These costs will factor into
31234e34855SSanjay Patel   // both sequences.
313a69158c1SSanjay Patel   unsigned Ext0Index = cast<ConstantInt>(Ext0->getOperand(1))->getZExtValue();
314a69158c1SSanjay Patel   unsigned Ext1Index = cast<ConstantInt>(Ext1->getOperand(1))->getZExtValue();
315a69158c1SSanjay Patel 
31636710c38SCaroline Concatto   InstructionCost Extract0Cost =
3176bdd531aSSanjay Patel       TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy, Ext0Index);
31836710c38SCaroline Concatto   InstructionCost Extract1Cost =
3196bdd531aSSanjay Patel       TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy, Ext1Index);
320a69158c1SSanjay Patel 
321a69158c1SSanjay Patel   // A more expensive extract will always be replaced by a splat shuffle.
322a69158c1SSanjay Patel   // For example, if Ext0 is more expensive:
323a69158c1SSanjay Patel   // opcode (extelt V0, Ext0), (ext V1, Ext1) -->
324a69158c1SSanjay Patel   // extelt (opcode (splat V0, Ext0), V1), Ext1
325a69158c1SSanjay Patel   // TODO: Evaluate whether that always results in lowest cost. Alternatively,
326a69158c1SSanjay Patel   //       check the cost of creating a broadcast shuffle and shuffling both
327a69158c1SSanjay Patel   //       operands to element 0.
32836710c38SCaroline Concatto   InstructionCost CheapExtractCost = std::min(Extract0Cost, Extract1Cost);
32934e34855SSanjay Patel 
33034e34855SSanjay Patel   // Extra uses of the extracts mean that we include those costs in the
33134e34855SSanjay Patel   // vector total because those instructions will not be eliminated.
33236710c38SCaroline Concatto   InstructionCost OldCost, NewCost;
333a69158c1SSanjay Patel   if (Ext0->getOperand(0) == Ext1->getOperand(0) && Ext0Index == Ext1Index) {
334a69158c1SSanjay Patel     // Handle a special case. If the 2 extracts are identical, adjust the
33534e34855SSanjay Patel     // formulas to account for that. The extra use charge allows for either the
33634e34855SSanjay Patel     // CSE'd pattern or an unoptimized form with identical values:
33734e34855SSanjay Patel     // opcode (extelt V, C), (extelt V, C) --> extelt (opcode V, V), C
33834e34855SSanjay Patel     bool HasUseTax = Ext0 == Ext1 ? !Ext0->hasNUses(2)
33934e34855SSanjay Patel                                   : !Ext0->hasOneUse() || !Ext1->hasOneUse();
340a69158c1SSanjay Patel     OldCost = CheapExtractCost + ScalarOpCost;
341a69158c1SSanjay Patel     NewCost = VectorOpCost + CheapExtractCost + HasUseTax * CheapExtractCost;
34234e34855SSanjay Patel   } else {
34334e34855SSanjay Patel     // Handle the general case. Each extract is actually a different value:
344a69158c1SSanjay Patel     // opcode (extelt V0, C0), (extelt V1, C1) --> extelt (opcode V0, V1), C
345a69158c1SSanjay Patel     OldCost = Extract0Cost + Extract1Cost + ScalarOpCost;
346a69158c1SSanjay Patel     NewCost = VectorOpCost + CheapExtractCost +
347a69158c1SSanjay Patel               !Ext0->hasOneUse() * Extract0Cost +
348a69158c1SSanjay Patel               !Ext1->hasOneUse() * Extract1Cost;
34934e34855SSanjay Patel   }
350a69158c1SSanjay Patel 
3513b95d834SSanjay Patel   ConvertToShuffle = getShuffleExtract(Ext0, Ext1, PreferredExtractIndex);
3523b95d834SSanjay Patel   if (ConvertToShuffle) {
353a69158c1SSanjay Patel     if (IsBinOp && DisableBinopExtractShuffle)
354a69158c1SSanjay Patel       return true;
355a69158c1SSanjay Patel 
356a69158c1SSanjay Patel     // If we are extracting from 2 different indexes, then one operand must be
357a69158c1SSanjay Patel     // shuffled before performing the vector operation. The shuffle mask is
358a69158c1SSanjay Patel     // undefined except for 1 lane that is being translated to the remaining
359a69158c1SSanjay Patel     // extraction lane. Therefore, it is a splat shuffle. Ex:
360a69158c1SSanjay Patel     // ShufMask = { undef, undef, 0, undef }
361a69158c1SSanjay Patel     // TODO: The cost model has an option for a "broadcast" shuffle
362a69158c1SSanjay Patel     //       (splat-from-element-0), but no option for a more general splat.
363a69158c1SSanjay Patel     NewCost +=
364a69158c1SSanjay Patel         TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, VecTy);
365a69158c1SSanjay Patel   }
366a69158c1SSanjay Patel 
36710ea01d8SSanjay Patel   // Aggressively form a vector op if the cost is equal because the transform
36810ea01d8SSanjay Patel   // may enable further optimization.
36910ea01d8SSanjay Patel   // Codegen can reverse this transform (scalarize) if it was not profitable.
37010ea01d8SSanjay Patel   return OldCost < NewCost;
37134e34855SSanjay Patel }
37234e34855SSanjay Patel 
3739934cc54SSanjay Patel /// Create a shuffle that translates (shifts) 1 element from the input vector
3749934cc54SSanjay Patel /// to a new element location.
3759934cc54SSanjay Patel static Value *createShiftShuffle(Value *Vec, unsigned OldIndex,
3769934cc54SSanjay Patel                                  unsigned NewIndex, IRBuilder<> &Builder) {
3779934cc54SSanjay Patel   // The shuffle mask is undefined except for 1 lane that is being translated
3789934cc54SSanjay Patel   // to the new element index. Example for OldIndex == 2 and NewIndex == 0:
3799934cc54SSanjay Patel   // ShufMask = { 2, undef, undef, undef }
3809934cc54SSanjay Patel   auto *VecTy = cast<FixedVectorType>(Vec->getType());
38154143e2bSSanjay Patel   SmallVector<int, 32> ShufMask(VecTy->getNumElements(), UndefMaskElem);
3829934cc54SSanjay Patel   ShufMask[NewIndex] = OldIndex;
3831e6b240dSSanjay Patel   return Builder.CreateShuffleVector(Vec, ShufMask, "shift");
3849934cc54SSanjay Patel }
3859934cc54SSanjay Patel 
386216a37bbSSanjay Patel /// Given an extract element instruction with constant index operand, shuffle
387216a37bbSSanjay Patel /// the source vector (shift the scalar element) to a NewIndex for extraction.
388216a37bbSSanjay Patel /// Return null if the input can be constant folded, so that we are not creating
389216a37bbSSanjay Patel /// unnecessary instructions.
3909934cc54SSanjay Patel static ExtractElementInst *translateExtract(ExtractElementInst *ExtElt,
3919934cc54SSanjay Patel                                             unsigned NewIndex,
3929934cc54SSanjay Patel                                             IRBuilder<> &Builder) {
393216a37bbSSanjay Patel   // If the extract can be constant-folded, this code is unsimplified. Defer
394216a37bbSSanjay Patel   // to other passes to handle that.
395216a37bbSSanjay Patel   Value *X = ExtElt->getVectorOperand();
396216a37bbSSanjay Patel   Value *C = ExtElt->getIndexOperand();
397de65b356SSanjay Patel   assert(isa<ConstantInt>(C) && "Expected a constant index operand");
398216a37bbSSanjay Patel   if (isa<Constant>(X))
399216a37bbSSanjay Patel     return nullptr;
400216a37bbSSanjay Patel 
4019934cc54SSanjay Patel   Value *Shuf = createShiftShuffle(X, cast<ConstantInt>(C)->getZExtValue(),
4029934cc54SSanjay Patel                                    NewIndex, Builder);
403216a37bbSSanjay Patel   return cast<ExtractElementInst>(Builder.CreateExtractElement(Shuf, NewIndex));
404216a37bbSSanjay Patel }
405216a37bbSSanjay Patel 
406fc445589SSanjay Patel /// Try to reduce extract element costs by converting scalar compares to vector
407fc445589SSanjay Patel /// compares followed by extract.
408e9c79a7aSSanjay Patel /// cmp (ext0 V0, C), (ext1 V1, C)
409de65b356SSanjay Patel void VectorCombine::foldExtExtCmp(ExtractElementInst *Ext0,
410de65b356SSanjay Patel                                   ExtractElementInst *Ext1, Instruction &I) {
411fc445589SSanjay Patel   assert(isa<CmpInst>(&I) && "Expected a compare");
412216a37bbSSanjay Patel   assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() ==
413216a37bbSSanjay Patel              cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() &&
414216a37bbSSanjay Patel          "Expected matching constant extract indexes");
415a17f03bdSSanjay Patel 
416a17f03bdSSanjay Patel   // cmp Pred (extelt V0, C), (extelt V1, C) --> extelt (cmp Pred V0, V1), C
417a17f03bdSSanjay Patel   ++NumVecCmp;
418fc445589SSanjay Patel   CmpInst::Predicate Pred = cast<CmpInst>(&I)->getPredicate();
419216a37bbSSanjay Patel   Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand();
42046a285adSSanjay Patel   Value *VecCmp = Builder.CreateCmp(Pred, V0, V1);
421216a37bbSSanjay Patel   Value *NewExt = Builder.CreateExtractElement(VecCmp, Ext0->getIndexOperand());
42298c2f4eeSSanjay Patel   replaceValue(I, *NewExt);
423a17f03bdSSanjay Patel }
424a17f03bdSSanjay Patel 
42519b62b79SSanjay Patel /// Try to reduce extract element costs by converting scalar binops to vector
42619b62b79SSanjay Patel /// binops followed by extract.
427e9c79a7aSSanjay Patel /// bo (ext0 V0, C), (ext1 V1, C)
428de65b356SSanjay Patel void VectorCombine::foldExtExtBinop(ExtractElementInst *Ext0,
429de65b356SSanjay Patel                                     ExtractElementInst *Ext1, Instruction &I) {
430fc445589SSanjay Patel   assert(isa<BinaryOperator>(&I) && "Expected a binary operator");
431216a37bbSSanjay Patel   assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() ==
432216a37bbSSanjay Patel              cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() &&
433216a37bbSSanjay Patel          "Expected matching constant extract indexes");
43419b62b79SSanjay Patel 
43534e34855SSanjay Patel   // bo (extelt V0, C), (extelt V1, C) --> extelt (bo V0, V1), C
43619b62b79SSanjay Patel   ++NumVecBO;
437216a37bbSSanjay Patel   Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand();
438e9c79a7aSSanjay Patel   Value *VecBO =
43934e34855SSanjay Patel       Builder.CreateBinOp(cast<BinaryOperator>(&I)->getOpcode(), V0, V1);
440e9c79a7aSSanjay Patel 
44119b62b79SSanjay Patel   // All IR flags are safe to back-propagate because any potential poison
44219b62b79SSanjay Patel   // created in unused vector elements is discarded by the extract.
443e9c79a7aSSanjay Patel   if (auto *VecBOInst = dyn_cast<Instruction>(VecBO))
44419b62b79SSanjay Patel     VecBOInst->copyIRFlags(&I);
445e9c79a7aSSanjay Patel 
446216a37bbSSanjay Patel   Value *NewExt = Builder.CreateExtractElement(VecBO, Ext0->getIndexOperand());
44798c2f4eeSSanjay Patel   replaceValue(I, *NewExt);
44819b62b79SSanjay Patel }
44919b62b79SSanjay Patel 
450fc445589SSanjay Patel /// Match an instruction with extracted vector operands.
4516bdd531aSSanjay Patel bool VectorCombine::foldExtractExtract(Instruction &I) {
452e9c79a7aSSanjay Patel   // It is not safe to transform things like div, urem, etc. because we may
453e9c79a7aSSanjay Patel   // create undefined behavior when executing those on unknown vector elements.
454e9c79a7aSSanjay Patel   if (!isSafeToSpeculativelyExecute(&I))
455e9c79a7aSSanjay Patel     return false;
456e9c79a7aSSanjay Patel 
457216a37bbSSanjay Patel   Instruction *I0, *I1;
458fc445589SSanjay Patel   CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
459216a37bbSSanjay Patel   if (!match(&I, m_Cmp(Pred, m_Instruction(I0), m_Instruction(I1))) &&
460216a37bbSSanjay Patel       !match(&I, m_BinOp(m_Instruction(I0), m_Instruction(I1))))
461fc445589SSanjay Patel     return false;
462fc445589SSanjay Patel 
463fc445589SSanjay Patel   Value *V0, *V1;
464fc445589SSanjay Patel   uint64_t C0, C1;
465216a37bbSSanjay Patel   if (!match(I0, m_ExtractElt(m_Value(V0), m_ConstantInt(C0))) ||
466216a37bbSSanjay Patel       !match(I1, m_ExtractElt(m_Value(V1), m_ConstantInt(C1))) ||
467fc445589SSanjay Patel       V0->getType() != V1->getType())
468fc445589SSanjay Patel     return false;
469fc445589SSanjay Patel 
470ce97ce3aSSanjay Patel   // If the scalar value 'I' is going to be re-inserted into a vector, then try
471ce97ce3aSSanjay Patel   // to create an extract to that same element. The extract/insert can be
472ce97ce3aSSanjay Patel   // reduced to a "select shuffle".
473ce97ce3aSSanjay Patel   // TODO: If we add a larger pattern match that starts from an insert, this
474ce97ce3aSSanjay Patel   //       probably becomes unnecessary.
475216a37bbSSanjay Patel   auto *Ext0 = cast<ExtractElementInst>(I0);
476216a37bbSSanjay Patel   auto *Ext1 = cast<ExtractElementInst>(I1);
477a0f96741SSanjay Patel   uint64_t InsertIndex = InvalidIndex;
478ce97ce3aSSanjay Patel   if (I.hasOneUse())
4797eed772aSSanjay Patel     match(I.user_back(),
4807eed772aSSanjay Patel           m_InsertElt(m_Value(), m_Value(), m_ConstantInt(InsertIndex)));
481ce97ce3aSSanjay Patel 
482216a37bbSSanjay Patel   ExtractElementInst *ExtractToChange;
4836bdd531aSSanjay Patel   if (isExtractExtractCheap(Ext0, Ext1, I.getOpcode(), ExtractToChange,
484ce97ce3aSSanjay Patel                             InsertIndex))
485fc445589SSanjay Patel     return false;
486e9c79a7aSSanjay Patel 
487216a37bbSSanjay Patel   if (ExtractToChange) {
488216a37bbSSanjay Patel     unsigned CheapExtractIdx = ExtractToChange == Ext0 ? C1 : C0;
489216a37bbSSanjay Patel     ExtractElementInst *NewExtract =
4909934cc54SSanjay Patel         translateExtract(ExtractToChange, CheapExtractIdx, Builder);
491216a37bbSSanjay Patel     if (!NewExtract)
4926d864097SSanjay Patel       return false;
493216a37bbSSanjay Patel     if (ExtractToChange == Ext0)
494216a37bbSSanjay Patel       Ext0 = NewExtract;
495a69158c1SSanjay Patel     else
496216a37bbSSanjay Patel       Ext1 = NewExtract;
497a69158c1SSanjay Patel   }
498e9c79a7aSSanjay Patel 
499e9c79a7aSSanjay Patel   if (Pred != CmpInst::BAD_ICMP_PREDICATE)
500039ff29eSSanjay Patel     foldExtExtCmp(Ext0, Ext1, I);
501e9c79a7aSSanjay Patel   else
502039ff29eSSanjay Patel     foldExtExtBinop(Ext0, Ext1, I);
503e9c79a7aSSanjay Patel 
504e9c79a7aSSanjay Patel   return true;
505fc445589SSanjay Patel }
506fc445589SSanjay Patel 
507bef6e67eSSanjay Patel /// If this is a bitcast of a shuffle, try to bitcast the source vector to the
508bef6e67eSSanjay Patel /// destination type followed by shuffle. This can enable further transforms by
509bef6e67eSSanjay Patel /// moving bitcasts or shuffles together.
5106bdd531aSSanjay Patel bool VectorCombine::foldBitcastShuf(Instruction &I) {
511b6050ca1SSanjay Patel   Value *V;
512b6050ca1SSanjay Patel   ArrayRef<int> Mask;
5137eed772aSSanjay Patel   if (!match(&I, m_BitCast(
5147eed772aSSanjay Patel                      m_OneUse(m_Shuffle(m_Value(V), m_Undef(), m_Mask(Mask))))))
515b6050ca1SSanjay Patel     return false;
516b6050ca1SSanjay Patel 
517b4f04d71SHuihui Zhang   // 1) Do not fold bitcast shuffle for scalable type. First, shuffle cost for
518b4f04d71SHuihui Zhang   // scalable type is unknown; Second, we cannot reason if the narrowed shuffle
519b4f04d71SHuihui Zhang   // mask for scalable type is a splat or not.
520b4f04d71SHuihui Zhang   // 2) Disallow non-vector casts and length-changing shuffles.
521bef6e67eSSanjay Patel   // TODO: We could allow any shuffle.
522b4f04d71SHuihui Zhang   auto *DestTy = dyn_cast<FixedVectorType>(I.getType());
523b4f04d71SHuihui Zhang   auto *SrcTy = dyn_cast<FixedVectorType>(V->getType());
524b4f04d71SHuihui Zhang   if (!SrcTy || !DestTy || I.getOperand(0)->getType() != SrcTy)
525b6050ca1SSanjay Patel     return false;
526b6050ca1SSanjay Patel 
527b4f04d71SHuihui Zhang   unsigned DestNumElts = DestTy->getNumElements();
528b4f04d71SHuihui Zhang   unsigned SrcNumElts = SrcTy->getNumElements();
529b6050ca1SSanjay Patel   SmallVector<int, 16> NewMask;
530bef6e67eSSanjay Patel   if (SrcNumElts <= DestNumElts) {
531bef6e67eSSanjay Patel     // The bitcast is from wide to narrow/equal elements. The shuffle mask can
532bef6e67eSSanjay Patel     // always be expanded to the equivalent form choosing narrower elements.
533b6050ca1SSanjay Patel     assert(DestNumElts % SrcNumElts == 0 && "Unexpected shuffle mask");
534b6050ca1SSanjay Patel     unsigned ScaleFactor = DestNumElts / SrcNumElts;
5351318ddbcSSanjay Patel     narrowShuffleMaskElts(ScaleFactor, Mask, NewMask);
536bef6e67eSSanjay Patel   } else {
537bef6e67eSSanjay Patel     // The bitcast is from narrow elements to wide elements. The shuffle mask
538bef6e67eSSanjay Patel     // must choose consecutive elements to allow casting first.
539bef6e67eSSanjay Patel     assert(SrcNumElts % DestNumElts == 0 && "Unexpected shuffle mask");
540bef6e67eSSanjay Patel     unsigned ScaleFactor = SrcNumElts / DestNumElts;
541bef6e67eSSanjay Patel     if (!widenShuffleMaskElts(ScaleFactor, Mask, NewMask))
542bef6e67eSSanjay Patel       return false;
543bef6e67eSSanjay Patel   }
544e2935dcfSDavid Green 
545e2935dcfSDavid Green   // The new shuffle must not cost more than the old shuffle. The bitcast is
546e2935dcfSDavid Green   // moved ahead of the shuffle, so assume that it has the same cost as before.
547e2935dcfSDavid Green   InstructionCost DestCost = TTI.getShuffleCost(
548e2935dcfSDavid Green       TargetTransformInfo::SK_PermuteSingleSrc, DestTy, NewMask);
549e2935dcfSDavid Green   InstructionCost SrcCost =
550e2935dcfSDavid Green       TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, SrcTy, Mask);
551e2935dcfSDavid Green   if (DestCost > SrcCost || !DestCost.isValid())
552e2935dcfSDavid Green     return false;
553e2935dcfSDavid Green 
554bef6e67eSSanjay Patel   // bitcast (shuf V, MaskC) --> shuf (bitcast V), MaskC'
5557aeb41b3SRoman Lebedev   ++NumShufOfBitcast;
556bef6e67eSSanjay Patel   Value *CastV = Builder.CreateBitCast(V, DestTy);
5571e6b240dSSanjay Patel   Value *Shuf = Builder.CreateShuffleVector(CastV, NewMask);
55898c2f4eeSSanjay Patel   replaceValue(I, *Shuf);
559b6050ca1SSanjay Patel   return true;
560b6050ca1SSanjay Patel }
561b6050ca1SSanjay Patel 
562ed67f5e7SSanjay Patel /// Match a vector binop or compare instruction with at least one inserted
563ed67f5e7SSanjay Patel /// scalar operand and convert to scalar binop/cmp followed by insertelement.
5646bdd531aSSanjay Patel bool VectorCombine::scalarizeBinopOrCmp(Instruction &I) {
565ed67f5e7SSanjay Patel   CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
5665dc4e7c2SSimon Pilgrim   Value *Ins0, *Ins1;
567ed67f5e7SSanjay Patel   if (!match(&I, m_BinOp(m_Value(Ins0), m_Value(Ins1))) &&
568ed67f5e7SSanjay Patel       !match(&I, m_Cmp(Pred, m_Value(Ins0), m_Value(Ins1))))
569ed67f5e7SSanjay Patel     return false;
570ed67f5e7SSanjay Patel 
571ed67f5e7SSanjay Patel   // Do not convert the vector condition of a vector select into a scalar
572ed67f5e7SSanjay Patel   // condition. That may cause problems for codegen because of differences in
573ed67f5e7SSanjay Patel   // boolean formats and register-file transfers.
574ed67f5e7SSanjay Patel   // TODO: Can we account for that in the cost model?
575ed67f5e7SSanjay Patel   bool IsCmp = Pred != CmpInst::Predicate::BAD_ICMP_PREDICATE;
576ed67f5e7SSanjay Patel   if (IsCmp)
577ed67f5e7SSanjay Patel     for (User *U : I.users())
578ed67f5e7SSanjay Patel       if (match(U, m_Select(m_Specific(&I), m_Value(), m_Value())))
5790d2a0b44SSanjay Patel         return false;
5800d2a0b44SSanjay Patel 
5815dc4e7c2SSimon Pilgrim   // Match against one or both scalar values being inserted into constant
5825dc4e7c2SSimon Pilgrim   // vectors:
583ed67f5e7SSanjay Patel   // vec_op VecC0, (inselt VecC1, V1, Index)
584ed67f5e7SSanjay Patel   // vec_op (inselt VecC0, V0, Index), VecC1
585ed67f5e7SSanjay Patel   // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index)
5860d2a0b44SSanjay Patel   // TODO: Deal with mismatched index constants and variable indexes?
5875dc4e7c2SSimon Pilgrim   Constant *VecC0 = nullptr, *VecC1 = nullptr;
5885dc4e7c2SSimon Pilgrim   Value *V0 = nullptr, *V1 = nullptr;
5895dc4e7c2SSimon Pilgrim   uint64_t Index0 = 0, Index1 = 0;
5907eed772aSSanjay Patel   if (!match(Ins0, m_InsertElt(m_Constant(VecC0), m_Value(V0),
5915dc4e7c2SSimon Pilgrim                                m_ConstantInt(Index0))) &&
5925dc4e7c2SSimon Pilgrim       !match(Ins0, m_Constant(VecC0)))
5935dc4e7c2SSimon Pilgrim     return false;
5945dc4e7c2SSimon Pilgrim   if (!match(Ins1, m_InsertElt(m_Constant(VecC1), m_Value(V1),
5955dc4e7c2SSimon Pilgrim                                m_ConstantInt(Index1))) &&
5965dc4e7c2SSimon Pilgrim       !match(Ins1, m_Constant(VecC1)))
5970d2a0b44SSanjay Patel     return false;
5980d2a0b44SSanjay Patel 
5995dc4e7c2SSimon Pilgrim   bool IsConst0 = !V0;
6005dc4e7c2SSimon Pilgrim   bool IsConst1 = !V1;
6015dc4e7c2SSimon Pilgrim   if (IsConst0 && IsConst1)
6025dc4e7c2SSimon Pilgrim     return false;
6035dc4e7c2SSimon Pilgrim   if (!IsConst0 && !IsConst1 && Index0 != Index1)
6045dc4e7c2SSimon Pilgrim     return false;
6055dc4e7c2SSimon Pilgrim 
6065dc4e7c2SSimon Pilgrim   // Bail for single insertion if it is a load.
6075dc4e7c2SSimon Pilgrim   // TODO: Handle this once getVectorInstrCost can cost for load/stores.
6085dc4e7c2SSimon Pilgrim   auto *I0 = dyn_cast_or_null<Instruction>(V0);
6095dc4e7c2SSimon Pilgrim   auto *I1 = dyn_cast_or_null<Instruction>(V1);
6105dc4e7c2SSimon Pilgrim   if ((IsConst0 && I1 && I1->mayReadFromMemory()) ||
6115dc4e7c2SSimon Pilgrim       (IsConst1 && I0 && I0->mayReadFromMemory()))
6125dc4e7c2SSimon Pilgrim     return false;
6135dc4e7c2SSimon Pilgrim 
6145dc4e7c2SSimon Pilgrim   uint64_t Index = IsConst0 ? Index1 : Index0;
6155dc4e7c2SSimon Pilgrim   Type *ScalarTy = IsConst0 ? V1->getType() : V0->getType();
6160d2a0b44SSanjay Patel   Type *VecTy = I.getType();
6175dc4e7c2SSimon Pilgrim   assert(VecTy->isVectorTy() &&
6185dc4e7c2SSimon Pilgrim          (IsConst0 || IsConst1 || V0->getType() == V1->getType()) &&
619741e20f3SSanjay Patel          (ScalarTy->isIntegerTy() || ScalarTy->isFloatingPointTy() ||
620741e20f3SSanjay Patel           ScalarTy->isPointerTy()) &&
621741e20f3SSanjay Patel          "Unexpected types for insert element into binop or cmp");
6220d2a0b44SSanjay Patel 
623ed67f5e7SSanjay Patel   unsigned Opcode = I.getOpcode();
62436710c38SCaroline Concatto   InstructionCost ScalarOpCost, VectorOpCost;
625ed67f5e7SSanjay Patel   if (IsCmp) {
626ed67f5e7SSanjay Patel     ScalarOpCost = TTI.getCmpSelInstrCost(Opcode, ScalarTy);
627ed67f5e7SSanjay Patel     VectorOpCost = TTI.getCmpSelInstrCost(Opcode, VecTy);
628ed67f5e7SSanjay Patel   } else {
629ed67f5e7SSanjay Patel     ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
630ed67f5e7SSanjay Patel     VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
631ed67f5e7SSanjay Patel   }
6320d2a0b44SSanjay Patel 
6330d2a0b44SSanjay Patel   // Get cost estimate for the insert element. This cost will factor into
6340d2a0b44SSanjay Patel   // both sequences.
63536710c38SCaroline Concatto   InstructionCost InsertCost =
6360d2a0b44SSanjay Patel       TTI.getVectorInstrCost(Instruction::InsertElement, VecTy, Index);
63736710c38SCaroline Concatto   InstructionCost OldCost =
63836710c38SCaroline Concatto       (IsConst0 ? 0 : InsertCost) + (IsConst1 ? 0 : InsertCost) + VectorOpCost;
63936710c38SCaroline Concatto   InstructionCost NewCost = ScalarOpCost + InsertCost +
6405dc4e7c2SSimon Pilgrim                             (IsConst0 ? 0 : !Ins0->hasOneUse() * InsertCost) +
6415dc4e7c2SSimon Pilgrim                             (IsConst1 ? 0 : !Ins1->hasOneUse() * InsertCost);
6420d2a0b44SSanjay Patel 
6430d2a0b44SSanjay Patel   // We want to scalarize unless the vector variant actually has lower cost.
64436710c38SCaroline Concatto   if (OldCost < NewCost || !NewCost.isValid())
6450d2a0b44SSanjay Patel     return false;
6460d2a0b44SSanjay Patel 
647ed67f5e7SSanjay Patel   // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index) -->
648ed67f5e7SSanjay Patel   // inselt NewVecC, (scalar_op V0, V1), Index
649ed67f5e7SSanjay Patel   if (IsCmp)
650ed67f5e7SSanjay Patel     ++NumScalarCmp;
651ed67f5e7SSanjay Patel   else
6520d2a0b44SSanjay Patel     ++NumScalarBO;
6535dc4e7c2SSimon Pilgrim 
6545dc4e7c2SSimon Pilgrim   // For constant cases, extract the scalar element, this should constant fold.
6555dc4e7c2SSimon Pilgrim   if (IsConst0)
6565dc4e7c2SSimon Pilgrim     V0 = ConstantExpr::getExtractElement(VecC0, Builder.getInt64(Index));
6575dc4e7c2SSimon Pilgrim   if (IsConst1)
6585dc4e7c2SSimon Pilgrim     V1 = ConstantExpr::getExtractElement(VecC1, Builder.getInt64(Index));
6595dc4e7c2SSimon Pilgrim 
660ed67f5e7SSanjay Patel   Value *Scalar =
66146a285adSSanjay Patel       IsCmp ? Builder.CreateCmp(Pred, V0, V1)
662ed67f5e7SSanjay Patel             : Builder.CreateBinOp((Instruction::BinaryOps)Opcode, V0, V1);
663ed67f5e7SSanjay Patel 
664ed67f5e7SSanjay Patel   Scalar->setName(I.getName() + ".scalar");
6650d2a0b44SSanjay Patel 
6660d2a0b44SSanjay Patel   // All IR flags are safe to back-propagate. There is no potential for extra
6670d2a0b44SSanjay Patel   // poison to be created by the scalar instruction.
6680d2a0b44SSanjay Patel   if (auto *ScalarInst = dyn_cast<Instruction>(Scalar))
6690d2a0b44SSanjay Patel     ScalarInst->copyIRFlags(&I);
6700d2a0b44SSanjay Patel 
6710d2a0b44SSanjay Patel   // Fold the vector constants in the original vectors into a new base vector.
672ed67f5e7SSanjay Patel   Constant *NewVecC = IsCmp ? ConstantExpr::getCompare(Pred, VecC0, VecC1)
673ed67f5e7SSanjay Patel                             : ConstantExpr::get(Opcode, VecC0, VecC1);
6740d2a0b44SSanjay Patel   Value *Insert = Builder.CreateInsertElement(NewVecC, Scalar, Index);
67598c2f4eeSSanjay Patel   replaceValue(I, *Insert);
6760d2a0b44SSanjay Patel   return true;
6770d2a0b44SSanjay Patel }
6780d2a0b44SSanjay Patel 
679b6315aeeSSanjay Patel /// Try to combine a scalar binop + 2 scalar compares of extracted elements of
680b6315aeeSSanjay Patel /// a vector into vector operations followed by extract. Note: The SLP pass
681b6315aeeSSanjay Patel /// may miss this pattern because of implementation problems.
682b6315aeeSSanjay Patel bool VectorCombine::foldExtractedCmps(Instruction &I) {
683b6315aeeSSanjay Patel   // We are looking for a scalar binop of booleans.
684b6315aeeSSanjay Patel   // binop i1 (cmp Pred I0, C0), (cmp Pred I1, C1)
685b6315aeeSSanjay Patel   if (!I.isBinaryOp() || !I.getType()->isIntegerTy(1))
686b6315aeeSSanjay Patel     return false;
687b6315aeeSSanjay Patel 
688b6315aeeSSanjay Patel   // The compare predicates should match, and each compare should have a
689b6315aeeSSanjay Patel   // constant operand.
690b6315aeeSSanjay Patel   // TODO: Relax the one-use constraints.
691b6315aeeSSanjay Patel   Value *B0 = I.getOperand(0), *B1 = I.getOperand(1);
692b6315aeeSSanjay Patel   Instruction *I0, *I1;
693b6315aeeSSanjay Patel   Constant *C0, *C1;
694b6315aeeSSanjay Patel   CmpInst::Predicate P0, P1;
695b6315aeeSSanjay Patel   if (!match(B0, m_OneUse(m_Cmp(P0, m_Instruction(I0), m_Constant(C0)))) ||
696b6315aeeSSanjay Patel       !match(B1, m_OneUse(m_Cmp(P1, m_Instruction(I1), m_Constant(C1)))) ||
697b6315aeeSSanjay Patel       P0 != P1)
698b6315aeeSSanjay Patel     return false;
699b6315aeeSSanjay Patel 
700b6315aeeSSanjay Patel   // The compare operands must be extracts of the same vector with constant
701b6315aeeSSanjay Patel   // extract indexes.
702b6315aeeSSanjay Patel   // TODO: Relax the one-use constraints.
703b6315aeeSSanjay Patel   Value *X;
704b6315aeeSSanjay Patel   uint64_t Index0, Index1;
705b6315aeeSSanjay Patel   if (!match(I0, m_OneUse(m_ExtractElt(m_Value(X), m_ConstantInt(Index0)))) ||
706b6315aeeSSanjay Patel       !match(I1, m_OneUse(m_ExtractElt(m_Specific(X), m_ConstantInt(Index1)))))
707b6315aeeSSanjay Patel     return false;
708b6315aeeSSanjay Patel 
709b6315aeeSSanjay Patel   auto *Ext0 = cast<ExtractElementInst>(I0);
710b6315aeeSSanjay Patel   auto *Ext1 = cast<ExtractElementInst>(I1);
711b6315aeeSSanjay Patel   ExtractElementInst *ConvertToShuf = getShuffleExtract(Ext0, Ext1);
712b6315aeeSSanjay Patel   if (!ConvertToShuf)
713b6315aeeSSanjay Patel     return false;
714b6315aeeSSanjay Patel 
715b6315aeeSSanjay Patel   // The original scalar pattern is:
716b6315aeeSSanjay Patel   // binop i1 (cmp Pred (ext X, Index0), C0), (cmp Pred (ext X, Index1), C1)
717b6315aeeSSanjay Patel   CmpInst::Predicate Pred = P0;
718b6315aeeSSanjay Patel   unsigned CmpOpcode = CmpInst::isFPPredicate(Pred) ? Instruction::FCmp
719b6315aeeSSanjay Patel                                                     : Instruction::ICmp;
720b6315aeeSSanjay Patel   auto *VecTy = dyn_cast<FixedVectorType>(X->getType());
721b6315aeeSSanjay Patel   if (!VecTy)
722b6315aeeSSanjay Patel     return false;
723b6315aeeSSanjay Patel 
72436710c38SCaroline Concatto   InstructionCost OldCost =
72536710c38SCaroline Concatto       TTI.getVectorInstrCost(Ext0->getOpcode(), VecTy, Index0);
726b6315aeeSSanjay Patel   OldCost += TTI.getVectorInstrCost(Ext1->getOpcode(), VecTy, Index1);
727b6315aeeSSanjay Patel   OldCost += TTI.getCmpSelInstrCost(CmpOpcode, I0->getType()) * 2;
728b6315aeeSSanjay Patel   OldCost += TTI.getArithmeticInstrCost(I.getOpcode(), I.getType());
729b6315aeeSSanjay Patel 
730b6315aeeSSanjay Patel   // The proposed vector pattern is:
731b6315aeeSSanjay Patel   // vcmp = cmp Pred X, VecC
732b6315aeeSSanjay Patel   // ext (binop vNi1 vcmp, (shuffle vcmp, Index1)), Index0
733b6315aeeSSanjay Patel   int CheapIndex = ConvertToShuf == Ext0 ? Index1 : Index0;
734b6315aeeSSanjay Patel   int ExpensiveIndex = ConvertToShuf == Ext0 ? Index0 : Index1;
735b6315aeeSSanjay Patel   auto *CmpTy = cast<FixedVectorType>(CmpInst::makeCmpResultType(X->getType()));
73636710c38SCaroline Concatto   InstructionCost NewCost = TTI.getCmpSelInstrCost(CmpOpcode, X->getType());
737e2935dcfSDavid Green   SmallVector<int, 32> ShufMask(VecTy->getNumElements(), UndefMaskElem);
738e2935dcfSDavid Green   ShufMask[CheapIndex] = ExpensiveIndex;
739e2935dcfSDavid Green   NewCost += TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, CmpTy,
740e2935dcfSDavid Green                                 ShufMask);
741b6315aeeSSanjay Patel   NewCost += TTI.getArithmeticInstrCost(I.getOpcode(), CmpTy);
742b6315aeeSSanjay Patel   NewCost += TTI.getVectorInstrCost(Ext0->getOpcode(), CmpTy, CheapIndex);
743b6315aeeSSanjay Patel 
744b6315aeeSSanjay Patel   // Aggressively form vector ops if the cost is equal because the transform
745b6315aeeSSanjay Patel   // may enable further optimization.
746b6315aeeSSanjay Patel   // Codegen can reverse this transform (scalarize) if it was not profitable.
74736710c38SCaroline Concatto   if (OldCost < NewCost || !NewCost.isValid())
748b6315aeeSSanjay Patel     return false;
749b6315aeeSSanjay Patel 
750b6315aeeSSanjay Patel   // Create a vector constant from the 2 scalar constants.
751b6315aeeSSanjay Patel   SmallVector<Constant *, 32> CmpC(VecTy->getNumElements(),
752b6315aeeSSanjay Patel                                    UndefValue::get(VecTy->getElementType()));
753b6315aeeSSanjay Patel   CmpC[Index0] = C0;
754b6315aeeSSanjay Patel   CmpC[Index1] = C1;
755b6315aeeSSanjay Patel   Value *VCmp = Builder.CreateCmp(Pred, X, ConstantVector::get(CmpC));
756b6315aeeSSanjay Patel 
757b6315aeeSSanjay Patel   Value *Shuf = createShiftShuffle(VCmp, ExpensiveIndex, CheapIndex, Builder);
758b6315aeeSSanjay Patel   Value *VecLogic = Builder.CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
759b6315aeeSSanjay Patel                                         VCmp, Shuf);
760b6315aeeSSanjay Patel   Value *NewExt = Builder.CreateExtractElement(VecLogic, CheapIndex);
761b6315aeeSSanjay Patel   replaceValue(I, *NewExt);
762b6315aeeSSanjay Patel   ++NumVecCmpBO;
763b6315aeeSSanjay Patel   return true;
764b6315aeeSSanjay Patel }
765b6315aeeSSanjay Patel 
7662db4979cSQiu Chaofan // Check if memory loc modified between two instrs in the same BB
7672db4979cSQiu Chaofan static bool isMemModifiedBetween(BasicBlock::iterator Begin,
7682db4979cSQiu Chaofan                                  BasicBlock::iterator End,
7692db4979cSQiu Chaofan                                  const MemoryLocation &Loc, AAResults &AA) {
7702db4979cSQiu Chaofan   unsigned NumScanned = 0;
7712db4979cSQiu Chaofan   return std::any_of(Begin, End, [&](const Instruction &Instr) {
7722db4979cSQiu Chaofan     return isModSet(AA.getModRefInfo(&Instr, Loc)) ||
7732db4979cSQiu Chaofan            ++NumScanned > MaxInstrsToScan;
7742db4979cSQiu Chaofan   });
7752db4979cSQiu Chaofan }
7762db4979cSQiu Chaofan 
7774e8c28b6SFlorian Hahn /// Check if it is legal to scalarize a memory access to \p VecTy at index \p
7784e8c28b6SFlorian Hahn /// Idx. \p Idx must access a valid vector element.
779*575e2affSFlorian Hahn static bool canScalarizeAccess(FixedVectorType *VecTy, Value *Idx,
780*575e2affSFlorian Hahn                                Instruction *CtxI, AssumptionCache &AC) {
781*575e2affSFlorian Hahn   if (auto *C = dyn_cast<ConstantInt>(Idx))
782*575e2affSFlorian Hahn     return C->getValue().ult(VecTy->getNumElements());
783*575e2affSFlorian Hahn 
784*575e2affSFlorian Hahn   APInt Zero(Idx->getType()->getScalarSizeInBits(), 0);
785*575e2affSFlorian Hahn   APInt MaxElts(Idx->getType()->getScalarSizeInBits(), VecTy->getNumElements());
786*575e2affSFlorian Hahn   ConstantRange ValidIndices(Zero, MaxElts);
787*575e2affSFlorian Hahn   ConstantRange IdxRange = computeConstantRange(Idx, true, &AC, CtxI, 0);
788*575e2affSFlorian Hahn   return ValidIndices.contains(IdxRange);
7894e8c28b6SFlorian Hahn }
7904e8c28b6SFlorian Hahn 
7912db4979cSQiu Chaofan // Combine patterns like:
7922db4979cSQiu Chaofan //   %0 = load <4 x i32>, <4 x i32>* %a
7932db4979cSQiu Chaofan //   %1 = insertelement <4 x i32> %0, i32 %b, i32 1
7942db4979cSQiu Chaofan //   store <4 x i32> %1, <4 x i32>* %a
7952db4979cSQiu Chaofan // to:
7962db4979cSQiu Chaofan //   %0 = bitcast <4 x i32>* %a to i32*
7972db4979cSQiu Chaofan //   %1 = getelementptr inbounds i32, i32* %0, i64 0, i64 1
7982db4979cSQiu Chaofan //   store i32 %b, i32* %1
7992db4979cSQiu Chaofan bool VectorCombine::foldSingleElementStore(Instruction &I) {
8002db4979cSQiu Chaofan   StoreInst *SI = dyn_cast<StoreInst>(&I);
8016d2df181SQiu Chaofan   if (!SI || !SI->isSimple() ||
8026d2df181SQiu Chaofan       !isa<FixedVectorType>(SI->getValueOperand()->getType()))
8032db4979cSQiu Chaofan     return false;
8042db4979cSQiu Chaofan 
8052db4979cSQiu Chaofan   // TODO: Combine more complicated patterns (multiple insert) by referencing
8062db4979cSQiu Chaofan   // TargetTransformInfo.
8072db4979cSQiu Chaofan   Instruction *Source;
8086d2df181SQiu Chaofan   Value *NewElement;
809*575e2affSFlorian Hahn   Value *Idx;
8102db4979cSQiu Chaofan   if (!match(SI->getValueOperand(),
8112db4979cSQiu Chaofan              m_InsertElt(m_Instruction(Source), m_Value(NewElement),
812*575e2affSFlorian Hahn                          m_Value(Idx))))
8132db4979cSQiu Chaofan     return false;
8142db4979cSQiu Chaofan 
8152db4979cSQiu Chaofan   if (auto *Load = dyn_cast<LoadInst>(Source)) {
8166d2df181SQiu Chaofan     auto VecTy = cast<FixedVectorType>(SI->getValueOperand()->getType());
8172db4979cSQiu Chaofan     const DataLayout &DL = I.getModule()->getDataLayout();
8182db4979cSQiu Chaofan     Value *SrcAddr = Load->getPointerOperand()->stripPointerCasts();
8196d2df181SQiu Chaofan     // Don't optimize for atomic/volatile load or store. Ensure memory is not
8206d2df181SQiu Chaofan     // modified between, vector type matches store size, and index is inbounds.
8212db4979cSQiu Chaofan     if (!Load->isSimple() || Load->getParent() != SI->getParent() ||
8222db4979cSQiu Chaofan         !DL.typeSizeEqualsStoreSize(Load->getType()) ||
823*575e2affSFlorian Hahn         !canScalarizeAccess(VecTy, Idx, Load, AC) ||
8242db4979cSQiu Chaofan         SrcAddr != SI->getPointerOperand()->stripPointerCasts() ||
8252db4979cSQiu Chaofan         isMemModifiedBetween(Load->getIterator(), SI->getIterator(),
8262db4979cSQiu Chaofan                              MemoryLocation::get(SI), AA))
8272db4979cSQiu Chaofan       return false;
8282db4979cSQiu Chaofan 
8292db4979cSQiu Chaofan     Value *GEP = GetElementPtrInst::CreateInBounds(
8302db4979cSQiu Chaofan         SI->getPointerOperand(), {ConstantInt::get(Idx->getType(), 0), Idx});
8312db4979cSQiu Chaofan     Builder.Insert(GEP);
8322db4979cSQiu Chaofan     StoreInst *NSI = Builder.CreateStore(NewElement, GEP);
8332db4979cSQiu Chaofan     NSI->copyMetadata(*SI);
8342db4979cSQiu Chaofan     if (SI->getAlign() < NSI->getAlign())
8352db4979cSQiu Chaofan       NSI->setAlignment(SI->getAlign());
8362db4979cSQiu Chaofan     replaceValue(I, *NSI);
8372db4979cSQiu Chaofan     // Need erasing the store manually.
8382db4979cSQiu Chaofan     I.eraseFromParent();
8392db4979cSQiu Chaofan     return true;
8402db4979cSQiu Chaofan   }
8412db4979cSQiu Chaofan 
8422db4979cSQiu Chaofan   return false;
8432db4979cSQiu Chaofan }
8442db4979cSQiu Chaofan 
8454e8c28b6SFlorian Hahn /// Try to scalarize vector loads feeding extractelement instructions.
8464e8c28b6SFlorian Hahn bool VectorCombine::scalarizeLoadExtract(Instruction &I) {
8474e8c28b6SFlorian Hahn   Value *Ptr;
848*575e2affSFlorian Hahn   Value *Idx;
849*575e2affSFlorian Hahn   if (!match(&I, m_ExtractElt(m_Load(m_Value(Ptr)), m_Value(Idx))))
8504e8c28b6SFlorian Hahn     return false;
8514e8c28b6SFlorian Hahn 
8524e8c28b6SFlorian Hahn   auto *LI = cast<LoadInst>(I.getOperand(0));
8534e8c28b6SFlorian Hahn   const DataLayout &DL = I.getModule()->getDataLayout();
8544e8c28b6SFlorian Hahn   if (LI->isVolatile() || !DL.typeSizeEqualsStoreSize(LI->getType()))
8554e8c28b6SFlorian Hahn     return false;
8564e8c28b6SFlorian Hahn 
8574e8c28b6SFlorian Hahn   auto *FixedVT = dyn_cast<FixedVectorType>(LI->getType());
8584e8c28b6SFlorian Hahn   if (!FixedVT)
8594e8c28b6SFlorian Hahn     return false;
8604e8c28b6SFlorian Hahn 
861*575e2affSFlorian Hahn   if (!canScalarizeAccess(FixedVT, Idx, &I, AC))
8624e8c28b6SFlorian Hahn     return false;
8634e8c28b6SFlorian Hahn 
8644e8c28b6SFlorian Hahn   InstructionCost OriginalCost = TTI.getMemoryOpCost(
8654e8c28b6SFlorian Hahn       Instruction::Load, LI->getType(), Align(LI->getAlignment()),
8664e8c28b6SFlorian Hahn       LI->getPointerAddressSpace());
8674e8c28b6SFlorian Hahn   InstructionCost ScalarizedCost = 0;
8684e8c28b6SFlorian Hahn 
8694e8c28b6SFlorian Hahn   Instruction *LastCheckedInst = LI;
8704e8c28b6SFlorian Hahn   unsigned NumInstChecked = 0;
8714e8c28b6SFlorian Hahn   // Check if all users of the load are extracts with no memory modifications
8724e8c28b6SFlorian Hahn   // between the load and the extract. Compute the cost of both the original
8734e8c28b6SFlorian Hahn   // code and the scalarized version.
8744e8c28b6SFlorian Hahn   for (User *U : LI->users()) {
8754e8c28b6SFlorian Hahn     auto *UI = dyn_cast<ExtractElementInst>(U);
8764e8c28b6SFlorian Hahn     if (!UI || UI->getParent() != LI->getParent())
8774e8c28b6SFlorian Hahn       return false;
8784e8c28b6SFlorian Hahn 
8794e8c28b6SFlorian Hahn     // Check if any instruction between the load and the extract may modify
8804e8c28b6SFlorian Hahn     // memory.
8814e8c28b6SFlorian Hahn     if (LastCheckedInst->comesBefore(UI)) {
8824e8c28b6SFlorian Hahn       for (Instruction &I :
8834e8c28b6SFlorian Hahn            make_range(std::next(LI->getIterator()), UI->getIterator())) {
8844e8c28b6SFlorian Hahn         // Bail out if we reached the check limit or the instruction may write
8854e8c28b6SFlorian Hahn         // to memory.
8864e8c28b6SFlorian Hahn         if (NumInstChecked == MaxInstrsToScan || I.mayWriteToMemory())
8874e8c28b6SFlorian Hahn           return false;
8884e8c28b6SFlorian Hahn         NumInstChecked++;
8894e8c28b6SFlorian Hahn       }
8904e8c28b6SFlorian Hahn     }
8914e8c28b6SFlorian Hahn 
8924e8c28b6SFlorian Hahn     if (!LastCheckedInst)
8934e8c28b6SFlorian Hahn       LastCheckedInst = UI;
8944e8c28b6SFlorian Hahn     else if (LastCheckedInst->comesBefore(UI))
8954e8c28b6SFlorian Hahn       LastCheckedInst = UI;
8964e8c28b6SFlorian Hahn 
8974e8c28b6SFlorian Hahn     auto *Index = dyn_cast<ConstantInt>(UI->getOperand(1));
8984e8c28b6SFlorian Hahn     OriginalCost +=
8994e8c28b6SFlorian Hahn         TTI.getVectorInstrCost(Instruction::ExtractElement, LI->getType(),
9004e8c28b6SFlorian Hahn                                Index ? Index->getZExtValue() : -1);
9014e8c28b6SFlorian Hahn     ScalarizedCost +=
9024e8c28b6SFlorian Hahn         TTI.getMemoryOpCost(Instruction::Load, FixedVT->getElementType(),
9034e8c28b6SFlorian Hahn                             Align(1), LI->getPointerAddressSpace());
9044e8c28b6SFlorian Hahn     ScalarizedCost += TTI.getAddressComputationCost(FixedVT->getElementType());
9054e8c28b6SFlorian Hahn   }
9064e8c28b6SFlorian Hahn 
9074e8c28b6SFlorian Hahn   if (ScalarizedCost >= OriginalCost)
9084e8c28b6SFlorian Hahn     return false;
9094e8c28b6SFlorian Hahn 
9104e8c28b6SFlorian Hahn   // Replace extracts with narrow scalar loads.
9114e8c28b6SFlorian Hahn   for (User *U : LI->users()) {
9124e8c28b6SFlorian Hahn     auto *EI = cast<ExtractElementInst>(U);
9134e8c28b6SFlorian Hahn     IRBuilder<>::InsertPointGuard Guard(Builder);
9144e8c28b6SFlorian Hahn     Builder.SetInsertPoint(EI);
9154e8c28b6SFlorian Hahn     Value *GEP = Builder.CreateInBoundsGEP(
9164e8c28b6SFlorian Hahn         FixedVT, Ptr, {Builder.getInt32(0), EI->getOperand(1)});
9174e8c28b6SFlorian Hahn     auto *NewLoad = cast<LoadInst>(Builder.CreateLoad(
9184e8c28b6SFlorian Hahn         FixedVT->getElementType(), GEP, EI->getName() + ".scalar"));
9194e8c28b6SFlorian Hahn 
9204e8c28b6SFlorian Hahn     // Set the alignment for the new load. For index 0, we can use the original
9214e8c28b6SFlorian Hahn     // alignment. Otherwise choose the common alignment of the load's align and
9224e8c28b6SFlorian Hahn     // the alignment for the scalar type.
9234e8c28b6SFlorian Hahn     auto *ConstIdx = dyn_cast<ConstantInt>(EI->getOperand(1));
9244e8c28b6SFlorian Hahn     if (ConstIdx && ConstIdx->isNullValue())
9254e8c28b6SFlorian Hahn       NewLoad->setAlignment(LI->getAlign());
9264e8c28b6SFlorian Hahn     else
9274e8c28b6SFlorian Hahn       NewLoad->setAlignment(commonAlignment(
9284e8c28b6SFlorian Hahn           DL.getABITypeAlign(NewLoad->getType()), LI->getAlign()));
9294e8c28b6SFlorian Hahn     replaceValue(*EI, *NewLoad);
9304e8c28b6SFlorian Hahn   }
9314e8c28b6SFlorian Hahn 
9324e8c28b6SFlorian Hahn   return true;
9334e8c28b6SFlorian Hahn }
9344e8c28b6SFlorian Hahn 
935a17f03bdSSanjay Patel /// This is the entry point for all transforms. Pass manager differences are
936a17f03bdSSanjay Patel /// handled in the callers of this function.
9376bdd531aSSanjay Patel bool VectorCombine::run() {
93825c6544fSSanjay Patel   if (DisableVectorCombine)
93925c6544fSSanjay Patel     return false;
94025c6544fSSanjay Patel 
941cc892fd9SSanjay Patel   // Don't attempt vectorization if the target does not support vectors.
942cc892fd9SSanjay Patel   if (!TTI.getNumberOfRegisters(TTI.getRegisterClassForType(/*Vector*/ true)))
943cc892fd9SSanjay Patel     return false;
944cc892fd9SSanjay Patel 
945a17f03bdSSanjay Patel   bool MadeChange = false;
946a17f03bdSSanjay Patel   for (BasicBlock &BB : F) {
947a17f03bdSSanjay Patel     // Ignore unreachable basic blocks.
948a17f03bdSSanjay Patel     if (!DT.isReachableFromEntry(&BB))
949a17f03bdSSanjay Patel       continue;
9502db4979cSQiu Chaofan     // Use early increment range so that we can erase instructions in loop.
9512db4979cSQiu Chaofan     for (Instruction &I : make_early_inc_range(BB)) {
952fc3cc8a4SSanjay Patel       if (isa<DbgInfoIntrinsic>(I))
953fc3cc8a4SSanjay Patel         continue;
954de65b356SSanjay Patel       Builder.SetInsertPoint(&I);
95543bdac29SSanjay Patel       MadeChange |= vectorizeLoadInsert(I);
9566bdd531aSSanjay Patel       MadeChange |= foldExtractExtract(I);
9576bdd531aSSanjay Patel       MadeChange |= foldBitcastShuf(I);
9586bdd531aSSanjay Patel       MadeChange |= scalarizeBinopOrCmp(I);
959b6315aeeSSanjay Patel       MadeChange |= foldExtractedCmps(I);
9604e8c28b6SFlorian Hahn       MadeChange |= scalarizeLoadExtract(I);
9612db4979cSQiu Chaofan       MadeChange |= foldSingleElementStore(I);
962a17f03bdSSanjay Patel     }
963fc3cc8a4SSanjay Patel   }
964a17f03bdSSanjay Patel 
965a17f03bdSSanjay Patel   // We're done with transforms, so remove dead instructions.
966a17f03bdSSanjay Patel   if (MadeChange)
967a17f03bdSSanjay Patel     for (BasicBlock &BB : F)
968a17f03bdSSanjay Patel       SimplifyInstructionsInBlock(&BB);
969a17f03bdSSanjay Patel 
970a17f03bdSSanjay Patel   return MadeChange;
971a17f03bdSSanjay Patel }
972a17f03bdSSanjay Patel 
973a17f03bdSSanjay Patel // Pass manager boilerplate below here.
974a17f03bdSSanjay Patel 
975a17f03bdSSanjay Patel namespace {
976a17f03bdSSanjay Patel class VectorCombineLegacyPass : public FunctionPass {
977a17f03bdSSanjay Patel public:
978a17f03bdSSanjay Patel   static char ID;
979a17f03bdSSanjay Patel   VectorCombineLegacyPass() : FunctionPass(ID) {
980a17f03bdSSanjay Patel     initializeVectorCombineLegacyPassPass(*PassRegistry::getPassRegistry());
981a17f03bdSSanjay Patel   }
982a17f03bdSSanjay Patel 
983a17f03bdSSanjay Patel   void getAnalysisUsage(AnalysisUsage &AU) const override {
984*575e2affSFlorian Hahn     AU.addRequired<AssumptionCacheTracker>();
985a17f03bdSSanjay Patel     AU.addRequired<DominatorTreeWrapperPass>();
986a17f03bdSSanjay Patel     AU.addRequired<TargetTransformInfoWrapperPass>();
9872db4979cSQiu Chaofan     AU.addRequired<AAResultsWrapperPass>();
988a17f03bdSSanjay Patel     AU.setPreservesCFG();
989a17f03bdSSanjay Patel     AU.addPreserved<DominatorTreeWrapperPass>();
990a17f03bdSSanjay Patel     AU.addPreserved<GlobalsAAWrapperPass>();
991024098aeSSanjay Patel     AU.addPreserved<AAResultsWrapperPass>();
992024098aeSSanjay Patel     AU.addPreserved<BasicAAWrapperPass>();
993a17f03bdSSanjay Patel     FunctionPass::getAnalysisUsage(AU);
994a17f03bdSSanjay Patel   }
995a17f03bdSSanjay Patel 
996a17f03bdSSanjay Patel   bool runOnFunction(Function &F) override {
997a17f03bdSSanjay Patel     if (skipFunction(F))
998a17f03bdSSanjay Patel       return false;
999*575e2affSFlorian Hahn     auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1000a17f03bdSSanjay Patel     auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1001a17f03bdSSanjay Patel     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
10022db4979cSQiu Chaofan     auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1003*575e2affSFlorian Hahn     VectorCombine Combiner(F, TTI, DT, AA, AC);
10046bdd531aSSanjay Patel     return Combiner.run();
1005a17f03bdSSanjay Patel   }
1006a17f03bdSSanjay Patel };
1007a17f03bdSSanjay Patel } // namespace
1008a17f03bdSSanjay Patel 
1009a17f03bdSSanjay Patel char VectorCombineLegacyPass::ID = 0;
1010a17f03bdSSanjay Patel INITIALIZE_PASS_BEGIN(VectorCombineLegacyPass, "vector-combine",
1011a17f03bdSSanjay Patel                       "Optimize scalar/vector ops", false,
1012a17f03bdSSanjay Patel                       false)
1013*575e2affSFlorian Hahn INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1014a17f03bdSSanjay Patel INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1015a17f03bdSSanjay Patel INITIALIZE_PASS_END(VectorCombineLegacyPass, "vector-combine",
1016a17f03bdSSanjay Patel                     "Optimize scalar/vector ops", false, false)
1017a17f03bdSSanjay Patel Pass *llvm::createVectorCombinePass() {
1018a17f03bdSSanjay Patel   return new VectorCombineLegacyPass();
1019a17f03bdSSanjay Patel }
1020a17f03bdSSanjay Patel 
1021a17f03bdSSanjay Patel PreservedAnalyses VectorCombinePass::run(Function &F,
1022a17f03bdSSanjay Patel                                          FunctionAnalysisManager &FAM) {
1023*575e2affSFlorian Hahn   auto &AC = FAM.getResult<AssumptionAnalysis>(F);
1024a17f03bdSSanjay Patel   TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(F);
1025a17f03bdSSanjay Patel   DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F);
10262db4979cSQiu Chaofan   AAResults &AA = FAM.getResult<AAManager>(F);
1027*575e2affSFlorian Hahn   VectorCombine Combiner(F, TTI, DT, AA, AC);
10286bdd531aSSanjay Patel   if (!Combiner.run())
1029a17f03bdSSanjay Patel     return PreservedAnalyses::all();
1030a17f03bdSSanjay Patel   PreservedAnalyses PA;
1031a17f03bdSSanjay Patel   PA.preserveSet<CFGAnalyses>();
1032a17f03bdSSanjay Patel   return PA;
1033a17f03bdSSanjay Patel }
1034