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"
17575e2affSFlorian 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 
34300870a9SFlorian Hahn #define DEBUG_TYPE "vector-combine"
35300870a9SFlorian Hahn #include "llvm/Transforms/Utils/InstructionWorklist.h"
36300870a9SFlorian Hahn 
37a17f03bdSSanjay Patel using namespace llvm;
38a17f03bdSSanjay Patel using namespace llvm::PatternMatch;
39a17f03bdSSanjay Patel 
4043bdac29SSanjay Patel STATISTIC(NumVecLoad, "Number of vector loads formed");
41a17f03bdSSanjay Patel STATISTIC(NumVecCmp, "Number of vector compares formed");
4219b62b79SSanjay Patel STATISTIC(NumVecBO, "Number of vector binops formed");
43b6315aeeSSanjay Patel STATISTIC(NumVecCmpBO, "Number of vector compare + binop formed");
447aeb41b3SRoman Lebedev STATISTIC(NumShufOfBitcast, "Number of shuffles moved after bitcast");
450d2a0b44SSanjay Patel STATISTIC(NumScalarBO, "Number of scalar binops formed");
46ed67f5e7SSanjay Patel STATISTIC(NumScalarCmp, "Number of scalar compares formed");
47a17f03bdSSanjay Patel 
4825c6544fSSanjay Patel static cl::opt<bool> DisableVectorCombine(
4925c6544fSSanjay Patel     "disable-vector-combine", cl::init(false), cl::Hidden,
5025c6544fSSanjay Patel     cl::desc("Disable all vector combine transforms"));
5125c6544fSSanjay Patel 
52a69158c1SSanjay Patel static cl::opt<bool> DisableBinopExtractShuffle(
53a69158c1SSanjay Patel     "disable-binop-extract-shuffle", cl::init(false), cl::Hidden,
54a69158c1SSanjay Patel     cl::desc("Disable binop extract to shuffle transforms"));
55a69158c1SSanjay Patel 
562db4979cSQiu Chaofan static cl::opt<unsigned> MaxInstrsToScan(
572db4979cSQiu Chaofan     "vector-combine-max-scan-instrs", cl::init(30), cl::Hidden,
582db4979cSQiu Chaofan     cl::desc("Max number of instructions to scan for vector combining."));
592db4979cSQiu Chaofan 
60a0f96741SSanjay Patel static const unsigned InvalidIndex = std::numeric_limits<unsigned>::max();
61a0f96741SSanjay Patel 
62b4447054SBenjamin Kramer namespace {
636bdd531aSSanjay Patel class VectorCombine {
646bdd531aSSanjay Patel public:
656bdd531aSSanjay Patel   VectorCombine(Function &F, const TargetTransformInfo &TTI,
66575e2affSFlorian Hahn                 const DominatorTree &DT, AAResults &AA, AssumptionCache &AC)
67575e2affSFlorian Hahn       : F(F), Builder(F.getContext()), TTI(TTI), DT(DT), AA(AA), AC(AC) {}
686bdd531aSSanjay Patel 
696bdd531aSSanjay Patel   bool run();
706bdd531aSSanjay Patel 
716bdd531aSSanjay Patel private:
726bdd531aSSanjay Patel   Function &F;
73de65b356SSanjay Patel   IRBuilder<> Builder;
746bdd531aSSanjay Patel   const TargetTransformInfo &TTI;
756bdd531aSSanjay Patel   const DominatorTree &DT;
762db4979cSQiu Chaofan   AAResults &AA;
77575e2affSFlorian Hahn   AssumptionCache &AC;
78300870a9SFlorian Hahn   InstructionWorklist Worklist;
796bdd531aSSanjay Patel 
8043bdac29SSanjay Patel   bool vectorizeLoadInsert(Instruction &I);
813b95d834SSanjay Patel   ExtractElementInst *getShuffleExtract(ExtractElementInst *Ext0,
823b95d834SSanjay Patel                                         ExtractElementInst *Ext1,
833b95d834SSanjay Patel                                         unsigned PreferredExtractIndex) const;
846bdd531aSSanjay Patel   bool isExtractExtractCheap(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
85*0dcd2b40SSimon Pilgrim                              const Instruction &I,
866bdd531aSSanjay Patel                              ExtractElementInst *&ConvertToShuffle,
876bdd531aSSanjay Patel                              unsigned PreferredExtractIndex);
88de65b356SSanjay Patel   void foldExtExtCmp(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
89de65b356SSanjay Patel                      Instruction &I);
90de65b356SSanjay Patel   void foldExtExtBinop(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
91de65b356SSanjay Patel                        Instruction &I);
926bdd531aSSanjay Patel   bool foldExtractExtract(Instruction &I);
936bdd531aSSanjay Patel   bool foldBitcastShuf(Instruction &I);
946bdd531aSSanjay Patel   bool scalarizeBinopOrCmp(Instruction &I);
95b6315aeeSSanjay Patel   bool foldExtractedCmps(Instruction &I);
962db4979cSQiu Chaofan   bool foldSingleElementStore(Instruction &I);
974e8c28b6SFlorian Hahn   bool scalarizeLoadExtract(Instruction &I);
98a69158c1SSanjay Patel 
99300870a9SFlorian Hahn   void replaceValue(Value &Old, Value &New) {
10098c2f4eeSSanjay Patel     Old.replaceAllUsesWith(&New);
10198c2f4eeSSanjay Patel     New.takeName(&Old);
102300870a9SFlorian Hahn     if (auto *NewI = dyn_cast<Instruction>(&New)) {
103300870a9SFlorian Hahn       Worklist.pushUsersToWorkList(*NewI);
104300870a9SFlorian Hahn       Worklist.pushValue(NewI);
10598c2f4eeSSanjay Patel     }
106300870a9SFlorian Hahn     Worklist.pushValue(&Old);
107300870a9SFlorian Hahn   }
108300870a9SFlorian Hahn 
109300870a9SFlorian Hahn   void eraseInstruction(Instruction &I) {
110300870a9SFlorian Hahn     for (Value *Op : I.operands())
111300870a9SFlorian Hahn       Worklist.pushValue(Op);
112300870a9SFlorian Hahn     Worklist.remove(&I);
113300870a9SFlorian Hahn     I.eraseFromParent();
114300870a9SFlorian Hahn   }
115300870a9SFlorian Hahn };
116300870a9SFlorian Hahn } // namespace
11798c2f4eeSSanjay Patel 
11843bdac29SSanjay Patel bool VectorCombine::vectorizeLoadInsert(Instruction &I) {
119b2ef2640SSanjay Patel   // Match insert into fixed vector of scalar value.
12047aaa99cSSanjay Patel   // TODO: Handle non-zero insert index.
121ddd9575dSSanjay Patel   auto *Ty = dyn_cast<FixedVectorType>(I.getType());
12243bdac29SSanjay Patel   Value *Scalar;
12348a23bccSSanjay Patel   if (!Ty || !match(&I, m_InsertElt(m_Undef(), m_Value(Scalar), m_ZeroInt())) ||
12448a23bccSSanjay Patel       !Scalar->hasOneUse())
12543bdac29SSanjay Patel     return false;
126ddd9575dSSanjay Patel 
127b2ef2640SSanjay Patel   // Optionally match an extract from another vector.
128b2ef2640SSanjay Patel   Value *X;
129b2ef2640SSanjay Patel   bool HasExtract = match(Scalar, m_ExtractElt(m_Value(X), m_ZeroInt()));
130b2ef2640SSanjay Patel   if (!HasExtract)
131b2ef2640SSanjay Patel     X = Scalar;
132b2ef2640SSanjay Patel 
133b2ef2640SSanjay Patel   // Match source value as load of scalar or vector.
1344452cc40SFangrui Song   // Do not vectorize scalar load (widening) if atomic/volatile or under
1354452cc40SFangrui Song   // asan/hwasan/memtag/tsan. The widened load may load data from dirty regions
1364452cc40SFangrui Song   // or create data races non-existent in the source.
137b2ef2640SSanjay Patel   auto *Load = dyn_cast<LoadInst>(X);
138b2ef2640SSanjay Patel   if (!Load || !Load->isSimple() || !Load->hasOneUse() ||
1394452cc40SFangrui Song       Load->getFunction()->hasFnAttribute(Attribute::SanitizeMemTag) ||
1404452cc40SFangrui Song       mustSuppressSpeculation(*Load))
14143bdac29SSanjay Patel     return false;
14243bdac29SSanjay Patel 
14312b684aeSSanjay Patel   const DataLayout &DL = I.getModule()->getDataLayout();
14412b684aeSSanjay Patel   Value *SrcPtr = Load->getPointerOperand()->stripPointerCasts();
14512b684aeSSanjay Patel   assert(isa<PointerType>(SrcPtr->getType()) && "Expected a pointer type");
146c36c0fabSArtem Belevich 
147c36c0fabSArtem Belevich   // If original AS != Load's AS, we can't bitcast the original pointer and have
148c36c0fabSArtem Belevich   // to use Load's operand instead. Ideally we would want to strip pointer casts
149c36c0fabSArtem Belevich   // without changing AS, but there's no API to do that ATM.
15012b684aeSSanjay Patel   unsigned AS = Load->getPointerAddressSpace();
15112b684aeSSanjay Patel   if (AS != SrcPtr->getType()->getPointerAddressSpace())
15212b684aeSSanjay Patel     SrcPtr = Load->getPointerOperand();
15343bdac29SSanjay Patel 
15447aaa99cSSanjay Patel   // We are potentially transforming byte-sized (8-bit) memory accesses, so make
15547aaa99cSSanjay Patel   // sure we have all of our type-based constraints in place for this target.
156ddd9575dSSanjay Patel   Type *ScalarTy = Scalar->getType();
15743bdac29SSanjay Patel   uint64_t ScalarSize = ScalarTy->getPrimitiveSizeInBits();
158ddd9575dSSanjay Patel   unsigned MinVectorSize = TTI.getMinVectorRegisterBitWidth();
15947aaa99cSSanjay Patel   if (!ScalarSize || !MinVectorSize || MinVectorSize % ScalarSize != 0 ||
16047aaa99cSSanjay Patel       ScalarSize % 8 != 0)
16143bdac29SSanjay Patel     return false;
16243bdac29SSanjay Patel 
16343bdac29SSanjay Patel   // Check safety of replacing the scalar load with a larger vector load.
164aaaf0ec7SSanjay Patel   // We use minimal alignment (maximum flexibility) because we only care about
165aaaf0ec7SSanjay Patel   // the dereferenceable region. When calculating cost and creating a new op,
166aaaf0ec7SSanjay Patel   // we may use a larger value based on alignment attributes.
1678fb05593SSanjay Patel   unsigned MinVecNumElts = MinVectorSize / ScalarSize;
1688fb05593SSanjay Patel   auto *MinVecTy = VectorType::get(ScalarTy, MinVecNumElts, false);
16947aaa99cSSanjay Patel   unsigned OffsetEltIndex = 0;
17047aaa99cSSanjay Patel   Align Alignment = Load->getAlign();
17147aaa99cSSanjay Patel   if (!isSafeToLoadUnconditionally(SrcPtr, MinVecTy, Align(1), DL, Load, &DT)) {
17247aaa99cSSanjay Patel     // It is not safe to load directly from the pointer, but we can still peek
17347aaa99cSSanjay Patel     // through gep offsets and check if it safe to load from a base address with
17447aaa99cSSanjay Patel     // updated alignment. If it is, we can shuffle the element(s) into place
17547aaa99cSSanjay Patel     // after loading.
17647aaa99cSSanjay Patel     unsigned OffsetBitWidth = DL.getIndexTypeSizeInBits(SrcPtr->getType());
17747aaa99cSSanjay Patel     APInt Offset(OffsetBitWidth, 0);
17847aaa99cSSanjay Patel     SrcPtr = SrcPtr->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
17947aaa99cSSanjay Patel 
18047aaa99cSSanjay Patel     // We want to shuffle the result down from a high element of a vector, so
18147aaa99cSSanjay Patel     // the offset must be positive.
18247aaa99cSSanjay Patel     if (Offset.isNegative())
18347aaa99cSSanjay Patel       return false;
18447aaa99cSSanjay Patel 
18547aaa99cSSanjay Patel     // The offset must be a multiple of the scalar element to shuffle cleanly
18647aaa99cSSanjay Patel     // in the element's size.
18747aaa99cSSanjay Patel     uint64_t ScalarSizeInBytes = ScalarSize / 8;
18847aaa99cSSanjay Patel     if (Offset.urem(ScalarSizeInBytes) != 0)
18947aaa99cSSanjay Patel       return false;
19047aaa99cSSanjay Patel 
19147aaa99cSSanjay Patel     // If we load MinVecNumElts, will our target element still be loaded?
19247aaa99cSSanjay Patel     OffsetEltIndex = Offset.udiv(ScalarSizeInBytes).getZExtValue();
19347aaa99cSSanjay Patel     if (OffsetEltIndex >= MinVecNumElts)
19447aaa99cSSanjay Patel       return false;
19547aaa99cSSanjay Patel 
196aaaf0ec7SSanjay Patel     if (!isSafeToLoadUnconditionally(SrcPtr, MinVecTy, Align(1), DL, Load, &DT))
19743bdac29SSanjay Patel       return false;
19843bdac29SSanjay Patel 
19947aaa99cSSanjay Patel     // Update alignment with offset value. Note that the offset could be negated
20047aaa99cSSanjay Patel     // to more accurately represent "(new) SrcPtr - Offset = (old) SrcPtr", but
20147aaa99cSSanjay Patel     // negation does not change the result of the alignment calculation.
20247aaa99cSSanjay Patel     Alignment = commonAlignment(Alignment, Offset.getZExtValue());
20347aaa99cSSanjay Patel   }
20447aaa99cSSanjay Patel 
205b2ef2640SSanjay Patel   // Original pattern: insertelt undef, load [free casts of] PtrOp, 0
20638ebc1a1SSanjay Patel   // Use the greater of the alignment on the load or its source pointer.
20747aaa99cSSanjay Patel   Alignment = std::max(SrcPtr->getPointerAlignment(DL), Alignment);
208b2ef2640SSanjay Patel   Type *LoadTy = Load->getType();
20936710c38SCaroline Concatto   InstructionCost OldCost =
21036710c38SCaroline Concatto       TTI.getMemoryOpCost(Instruction::Load, LoadTy, Alignment, AS);
2118fb05593SSanjay Patel   APInt DemandedElts = APInt::getOneBitSet(MinVecNumElts, 0);
212b2ef2640SSanjay Patel   OldCost += TTI.getScalarizationOverhead(MinVecTy, DemandedElts,
213b2ef2640SSanjay Patel                                           /* Insert */ true, HasExtract);
21443bdac29SSanjay Patel 
21543bdac29SSanjay Patel   // New pattern: load VecPtr
21636710c38SCaroline Concatto   InstructionCost NewCost =
21736710c38SCaroline Concatto       TTI.getMemoryOpCost(Instruction::Load, MinVecTy, Alignment, AS);
21847aaa99cSSanjay Patel   // Optionally, we are shuffling the loaded vector element(s) into place.
219e2935dcfSDavid Green   // For the mask set everything but element 0 to undef to prevent poison from
220e2935dcfSDavid Green   // propagating from the extra loaded memory. This will also optionally
221e2935dcfSDavid Green   // shrink/grow the vector from the loaded size to the output size.
222e2935dcfSDavid Green   // We assume this operation has no cost in codegen if there was no offset.
223e2935dcfSDavid Green   // Note that we could use freeze to avoid poison problems, but then we might
224e2935dcfSDavid Green   // still need a shuffle to change the vector size.
225e2935dcfSDavid Green   unsigned OutputNumElts = Ty->getNumElements();
226e2935dcfSDavid Green   SmallVector<int, 16> Mask(OutputNumElts, UndefMaskElem);
227e2935dcfSDavid Green   assert(OffsetEltIndex < MinVecNumElts && "Address offset too big");
228e2935dcfSDavid Green   Mask[0] = OffsetEltIndex;
22947aaa99cSSanjay Patel   if (OffsetEltIndex)
230e2935dcfSDavid Green     NewCost += TTI.getShuffleCost(TTI::SK_PermuteSingleSrc, MinVecTy, Mask);
23143bdac29SSanjay Patel 
23243bdac29SSanjay Patel   // We can aggressively convert to the vector form because the backend can
23343bdac29SSanjay Patel   // invert this transform if it does not result in a performance win.
23436710c38SCaroline Concatto   if (OldCost < NewCost || !NewCost.isValid())
23543bdac29SSanjay Patel     return false;
23643bdac29SSanjay Patel 
23743bdac29SSanjay Patel   // It is safe and potentially profitable to load a vector directly:
23843bdac29SSanjay Patel   // inselt undef, load Scalar, 0 --> load VecPtr
23943bdac29SSanjay Patel   IRBuilder<> Builder(Load);
24012b684aeSSanjay Patel   Value *CastedPtr = Builder.CreateBitCast(SrcPtr, MinVecTy->getPointerTo(AS));
2418fb05593SSanjay Patel   Value *VecLd = Builder.CreateAlignedLoad(MinVecTy, CastedPtr, Alignment);
2421e6b240dSSanjay Patel   VecLd = Builder.CreateShuffleVector(VecLd, Mask);
243d399f870SSanjay Patel 
24443bdac29SSanjay Patel   replaceValue(I, *VecLd);
24543bdac29SSanjay Patel   ++NumVecLoad;
24643bdac29SSanjay Patel   return true;
24743bdac29SSanjay Patel }
24843bdac29SSanjay Patel 
2493b95d834SSanjay Patel /// Determine which, if any, of the inputs should be replaced by a shuffle
2503b95d834SSanjay Patel /// followed by extract from a different index.
2513b95d834SSanjay Patel ExtractElementInst *VectorCombine::getShuffleExtract(
2523b95d834SSanjay Patel     ExtractElementInst *Ext0, ExtractElementInst *Ext1,
2533b95d834SSanjay Patel     unsigned PreferredExtractIndex = InvalidIndex) const {
2543b95d834SSanjay Patel   assert(isa<ConstantInt>(Ext0->getIndexOperand()) &&
2553b95d834SSanjay Patel          isa<ConstantInt>(Ext1->getIndexOperand()) &&
2563b95d834SSanjay Patel          "Expected constant extract indexes");
2573b95d834SSanjay Patel 
2583b95d834SSanjay Patel   unsigned Index0 = cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue();
2593b95d834SSanjay Patel   unsigned Index1 = cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue();
2603b95d834SSanjay Patel 
2613b95d834SSanjay Patel   // If the extract indexes are identical, no shuffle is needed.
2623b95d834SSanjay Patel   if (Index0 == Index1)
2633b95d834SSanjay Patel     return nullptr;
2643b95d834SSanjay Patel 
2653b95d834SSanjay Patel   Type *VecTy = Ext0->getVectorOperand()->getType();
2663b95d834SSanjay Patel   assert(VecTy == Ext1->getVectorOperand()->getType() && "Need matching types");
26736710c38SCaroline Concatto   InstructionCost Cost0 =
26836710c38SCaroline Concatto       TTI.getVectorInstrCost(Ext0->getOpcode(), VecTy, Index0);
26936710c38SCaroline Concatto   InstructionCost Cost1 =
27036710c38SCaroline Concatto       TTI.getVectorInstrCost(Ext1->getOpcode(), VecTy, Index1);
27136710c38SCaroline Concatto 
27236710c38SCaroline Concatto   // If both costs are invalid no shuffle is needed
27336710c38SCaroline Concatto   if (!Cost0.isValid() && !Cost1.isValid())
27436710c38SCaroline Concatto     return nullptr;
2753b95d834SSanjay Patel 
2763b95d834SSanjay Patel   // We are extracting from 2 different indexes, so one operand must be shuffled
2773b95d834SSanjay Patel   // before performing a vector operation and/or extract. The more expensive
2783b95d834SSanjay Patel   // extract will be replaced by a shuffle.
2793b95d834SSanjay Patel   if (Cost0 > Cost1)
2803b95d834SSanjay Patel     return Ext0;
2813b95d834SSanjay Patel   if (Cost1 > Cost0)
2823b95d834SSanjay Patel     return Ext1;
2833b95d834SSanjay Patel 
2843b95d834SSanjay Patel   // If the costs are equal and there is a preferred extract index, shuffle the
2853b95d834SSanjay Patel   // opposite operand.
2863b95d834SSanjay Patel   if (PreferredExtractIndex == Index0)
2873b95d834SSanjay Patel     return Ext1;
2883b95d834SSanjay Patel   if (PreferredExtractIndex == Index1)
2893b95d834SSanjay Patel     return Ext0;
2903b95d834SSanjay Patel 
2913b95d834SSanjay Patel   // Otherwise, replace the extract with the higher index.
2923b95d834SSanjay Patel   return Index0 > Index1 ? Ext0 : Ext1;
2933b95d834SSanjay Patel }
2943b95d834SSanjay Patel 
295a69158c1SSanjay Patel /// Compare the relative costs of 2 extracts followed by scalar operation vs.
296a69158c1SSanjay Patel /// vector operation(s) followed by extract. Return true if the existing
297a69158c1SSanjay Patel /// instructions are cheaper than a vector alternative. Otherwise, return false
298a69158c1SSanjay Patel /// and if one of the extracts should be transformed to a shufflevector, set
299a69158c1SSanjay Patel /// \p ConvertToShuffle to that extract instruction.
3006bdd531aSSanjay Patel bool VectorCombine::isExtractExtractCheap(ExtractElementInst *Ext0,
3016bdd531aSSanjay Patel                                           ExtractElementInst *Ext1,
302*0dcd2b40SSimon Pilgrim                                           const Instruction &I,
303216a37bbSSanjay Patel                                           ExtractElementInst *&ConvertToShuffle,
304ce97ce3aSSanjay Patel                                           unsigned PreferredExtractIndex) {
3054fa63fd4SAustin Kerbow   assert(isa<ConstantInt>(Ext0->getOperand(1)) &&
306a69158c1SSanjay Patel          isa<ConstantInt>(Ext1->getOperand(1)) &&
307a69158c1SSanjay Patel          "Expected constant extract indexes");
308*0dcd2b40SSimon Pilgrim   unsigned Opcode = I.getOpcode();
30934e34855SSanjay Patel   Type *ScalarTy = Ext0->getType();
310e3056ae9SSam Parker   auto *VecTy = cast<VectorType>(Ext0->getOperand(0)->getType());
31136710c38SCaroline Concatto   InstructionCost ScalarOpCost, VectorOpCost;
31234e34855SSanjay Patel 
31334e34855SSanjay Patel   // Get cost estimates for scalar and vector versions of the operation.
31434e34855SSanjay Patel   bool IsBinOp = Instruction::isBinaryOp(Opcode);
31534e34855SSanjay Patel   if (IsBinOp) {
31634e34855SSanjay Patel     ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
31734e34855SSanjay Patel     VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
31834e34855SSanjay Patel   } else {
31934e34855SSanjay Patel     assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
32034e34855SSanjay Patel            "Expected a compare");
321*0dcd2b40SSimon Pilgrim     CmpInst::Predicate Pred = cast<CmpInst>(I).getPredicate();
322*0dcd2b40SSimon Pilgrim     ScalarOpCost = TTI.getCmpSelInstrCost(
323*0dcd2b40SSimon Pilgrim         Opcode, ScalarTy, CmpInst::makeCmpResultType(ScalarTy), Pred);
324*0dcd2b40SSimon Pilgrim     VectorOpCost = TTI.getCmpSelInstrCost(
325*0dcd2b40SSimon Pilgrim         Opcode, VecTy, CmpInst::makeCmpResultType(VecTy), Pred);
32634e34855SSanjay Patel   }
32734e34855SSanjay Patel 
328a69158c1SSanjay Patel   // Get cost estimates for the extract elements. These costs will factor into
32934e34855SSanjay Patel   // both sequences.
330a69158c1SSanjay Patel   unsigned Ext0Index = cast<ConstantInt>(Ext0->getOperand(1))->getZExtValue();
331a69158c1SSanjay Patel   unsigned Ext1Index = cast<ConstantInt>(Ext1->getOperand(1))->getZExtValue();
332a69158c1SSanjay Patel 
33336710c38SCaroline Concatto   InstructionCost Extract0Cost =
3346bdd531aSSanjay Patel       TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy, Ext0Index);
33536710c38SCaroline Concatto   InstructionCost Extract1Cost =
3366bdd531aSSanjay Patel       TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy, Ext1Index);
337a69158c1SSanjay Patel 
338a69158c1SSanjay Patel   // A more expensive extract will always be replaced by a splat shuffle.
339a69158c1SSanjay Patel   // For example, if Ext0 is more expensive:
340a69158c1SSanjay Patel   // opcode (extelt V0, Ext0), (ext V1, Ext1) -->
341a69158c1SSanjay Patel   // extelt (opcode (splat V0, Ext0), V1), Ext1
342a69158c1SSanjay Patel   // TODO: Evaluate whether that always results in lowest cost. Alternatively,
343a69158c1SSanjay Patel   //       check the cost of creating a broadcast shuffle and shuffling both
344a69158c1SSanjay Patel   //       operands to element 0.
34536710c38SCaroline Concatto   InstructionCost CheapExtractCost = std::min(Extract0Cost, Extract1Cost);
34634e34855SSanjay Patel 
34734e34855SSanjay Patel   // Extra uses of the extracts mean that we include those costs in the
34834e34855SSanjay Patel   // vector total because those instructions will not be eliminated.
34936710c38SCaroline Concatto   InstructionCost OldCost, NewCost;
350a69158c1SSanjay Patel   if (Ext0->getOperand(0) == Ext1->getOperand(0) && Ext0Index == Ext1Index) {
351a69158c1SSanjay Patel     // Handle a special case. If the 2 extracts are identical, adjust the
35234e34855SSanjay Patel     // formulas to account for that. The extra use charge allows for either the
35334e34855SSanjay Patel     // CSE'd pattern or an unoptimized form with identical values:
35434e34855SSanjay Patel     // opcode (extelt V, C), (extelt V, C) --> extelt (opcode V, V), C
35534e34855SSanjay Patel     bool HasUseTax = Ext0 == Ext1 ? !Ext0->hasNUses(2)
35634e34855SSanjay Patel                                   : !Ext0->hasOneUse() || !Ext1->hasOneUse();
357a69158c1SSanjay Patel     OldCost = CheapExtractCost + ScalarOpCost;
358a69158c1SSanjay Patel     NewCost = VectorOpCost + CheapExtractCost + HasUseTax * CheapExtractCost;
35934e34855SSanjay Patel   } else {
36034e34855SSanjay Patel     // Handle the general case. Each extract is actually a different value:
361a69158c1SSanjay Patel     // opcode (extelt V0, C0), (extelt V1, C1) --> extelt (opcode V0, V1), C
362a69158c1SSanjay Patel     OldCost = Extract0Cost + Extract1Cost + ScalarOpCost;
363a69158c1SSanjay Patel     NewCost = VectorOpCost + CheapExtractCost +
364a69158c1SSanjay Patel               !Ext0->hasOneUse() * Extract0Cost +
365a69158c1SSanjay Patel               !Ext1->hasOneUse() * Extract1Cost;
36634e34855SSanjay Patel   }
367a69158c1SSanjay Patel 
3683b95d834SSanjay Patel   ConvertToShuffle = getShuffleExtract(Ext0, Ext1, PreferredExtractIndex);
3693b95d834SSanjay Patel   if (ConvertToShuffle) {
370a69158c1SSanjay Patel     if (IsBinOp && DisableBinopExtractShuffle)
371a69158c1SSanjay Patel       return true;
372a69158c1SSanjay Patel 
373a69158c1SSanjay Patel     // If we are extracting from 2 different indexes, then one operand must be
374a69158c1SSanjay Patel     // shuffled before performing the vector operation. The shuffle mask is
375a69158c1SSanjay Patel     // undefined except for 1 lane that is being translated to the remaining
376a69158c1SSanjay Patel     // extraction lane. Therefore, it is a splat shuffle. Ex:
377a69158c1SSanjay Patel     // ShufMask = { undef, undef, 0, undef }
378a69158c1SSanjay Patel     // TODO: The cost model has an option for a "broadcast" shuffle
379a69158c1SSanjay Patel     //       (splat-from-element-0), but no option for a more general splat.
380a69158c1SSanjay Patel     NewCost +=
381a69158c1SSanjay Patel         TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, VecTy);
382a69158c1SSanjay Patel   }
383a69158c1SSanjay Patel 
38410ea01d8SSanjay Patel   // Aggressively form a vector op if the cost is equal because the transform
38510ea01d8SSanjay Patel   // may enable further optimization.
38610ea01d8SSanjay Patel   // Codegen can reverse this transform (scalarize) if it was not profitable.
38710ea01d8SSanjay Patel   return OldCost < NewCost;
38834e34855SSanjay Patel }
38934e34855SSanjay Patel 
3909934cc54SSanjay Patel /// Create a shuffle that translates (shifts) 1 element from the input vector
3919934cc54SSanjay Patel /// to a new element location.
3929934cc54SSanjay Patel static Value *createShiftShuffle(Value *Vec, unsigned OldIndex,
3939934cc54SSanjay Patel                                  unsigned NewIndex, IRBuilder<> &Builder) {
3949934cc54SSanjay Patel   // The shuffle mask is undefined except for 1 lane that is being translated
3959934cc54SSanjay Patel   // to the new element index. Example for OldIndex == 2 and NewIndex == 0:
3969934cc54SSanjay Patel   // ShufMask = { 2, undef, undef, undef }
3979934cc54SSanjay Patel   auto *VecTy = cast<FixedVectorType>(Vec->getType());
39854143e2bSSanjay Patel   SmallVector<int, 32> ShufMask(VecTy->getNumElements(), UndefMaskElem);
3999934cc54SSanjay Patel   ShufMask[NewIndex] = OldIndex;
4001e6b240dSSanjay Patel   return Builder.CreateShuffleVector(Vec, ShufMask, "shift");
4019934cc54SSanjay Patel }
4029934cc54SSanjay Patel 
403216a37bbSSanjay Patel /// Given an extract element instruction with constant index operand, shuffle
404216a37bbSSanjay Patel /// the source vector (shift the scalar element) to a NewIndex for extraction.
405216a37bbSSanjay Patel /// Return null if the input can be constant folded, so that we are not creating
406216a37bbSSanjay Patel /// unnecessary instructions.
4079934cc54SSanjay Patel static ExtractElementInst *translateExtract(ExtractElementInst *ExtElt,
4089934cc54SSanjay Patel                                             unsigned NewIndex,
4099934cc54SSanjay Patel                                             IRBuilder<> &Builder) {
410216a37bbSSanjay Patel   // If the extract can be constant-folded, this code is unsimplified. Defer
411216a37bbSSanjay Patel   // to other passes to handle that.
412216a37bbSSanjay Patel   Value *X = ExtElt->getVectorOperand();
413216a37bbSSanjay Patel   Value *C = ExtElt->getIndexOperand();
414de65b356SSanjay Patel   assert(isa<ConstantInt>(C) && "Expected a constant index operand");
415216a37bbSSanjay Patel   if (isa<Constant>(X))
416216a37bbSSanjay Patel     return nullptr;
417216a37bbSSanjay Patel 
4189934cc54SSanjay Patel   Value *Shuf = createShiftShuffle(X, cast<ConstantInt>(C)->getZExtValue(),
4199934cc54SSanjay Patel                                    NewIndex, Builder);
420216a37bbSSanjay Patel   return cast<ExtractElementInst>(Builder.CreateExtractElement(Shuf, NewIndex));
421216a37bbSSanjay Patel }
422216a37bbSSanjay Patel 
423fc445589SSanjay Patel /// Try to reduce extract element costs by converting scalar compares to vector
424fc445589SSanjay Patel /// compares followed by extract.
425e9c79a7aSSanjay Patel /// cmp (ext0 V0, C), (ext1 V1, C)
426de65b356SSanjay Patel void VectorCombine::foldExtExtCmp(ExtractElementInst *Ext0,
427de65b356SSanjay Patel                                   ExtractElementInst *Ext1, Instruction &I) {
428fc445589SSanjay Patel   assert(isa<CmpInst>(&I) && "Expected a compare");
429216a37bbSSanjay Patel   assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() ==
430216a37bbSSanjay Patel              cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() &&
431216a37bbSSanjay Patel          "Expected matching constant extract indexes");
432a17f03bdSSanjay Patel 
433a17f03bdSSanjay Patel   // cmp Pred (extelt V0, C), (extelt V1, C) --> extelt (cmp Pred V0, V1), C
434a17f03bdSSanjay Patel   ++NumVecCmp;
435fc445589SSanjay Patel   CmpInst::Predicate Pred = cast<CmpInst>(&I)->getPredicate();
436216a37bbSSanjay Patel   Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand();
43746a285adSSanjay Patel   Value *VecCmp = Builder.CreateCmp(Pred, V0, V1);
438216a37bbSSanjay Patel   Value *NewExt = Builder.CreateExtractElement(VecCmp, Ext0->getIndexOperand());
43998c2f4eeSSanjay Patel   replaceValue(I, *NewExt);
440a17f03bdSSanjay Patel }
441a17f03bdSSanjay Patel 
44219b62b79SSanjay Patel /// Try to reduce extract element costs by converting scalar binops to vector
44319b62b79SSanjay Patel /// binops followed by extract.
444e9c79a7aSSanjay Patel /// bo (ext0 V0, C), (ext1 V1, C)
445de65b356SSanjay Patel void VectorCombine::foldExtExtBinop(ExtractElementInst *Ext0,
446de65b356SSanjay Patel                                     ExtractElementInst *Ext1, Instruction &I) {
447fc445589SSanjay Patel   assert(isa<BinaryOperator>(&I) && "Expected a binary operator");
448216a37bbSSanjay Patel   assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() ==
449216a37bbSSanjay Patel              cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() &&
450216a37bbSSanjay Patel          "Expected matching constant extract indexes");
45119b62b79SSanjay Patel 
45234e34855SSanjay Patel   // bo (extelt V0, C), (extelt V1, C) --> extelt (bo V0, V1), C
45319b62b79SSanjay Patel   ++NumVecBO;
454216a37bbSSanjay Patel   Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand();
455e9c79a7aSSanjay Patel   Value *VecBO =
45634e34855SSanjay Patel       Builder.CreateBinOp(cast<BinaryOperator>(&I)->getOpcode(), V0, V1);
457e9c79a7aSSanjay Patel 
45819b62b79SSanjay Patel   // All IR flags are safe to back-propagate because any potential poison
45919b62b79SSanjay Patel   // created in unused vector elements is discarded by the extract.
460e9c79a7aSSanjay Patel   if (auto *VecBOInst = dyn_cast<Instruction>(VecBO))
46119b62b79SSanjay Patel     VecBOInst->copyIRFlags(&I);
462e9c79a7aSSanjay Patel 
463216a37bbSSanjay Patel   Value *NewExt = Builder.CreateExtractElement(VecBO, Ext0->getIndexOperand());
46498c2f4eeSSanjay Patel   replaceValue(I, *NewExt);
46519b62b79SSanjay Patel }
46619b62b79SSanjay Patel 
467fc445589SSanjay Patel /// Match an instruction with extracted vector operands.
4686bdd531aSSanjay Patel bool VectorCombine::foldExtractExtract(Instruction &I) {
469e9c79a7aSSanjay Patel   // It is not safe to transform things like div, urem, etc. because we may
470e9c79a7aSSanjay Patel   // create undefined behavior when executing those on unknown vector elements.
471e9c79a7aSSanjay Patel   if (!isSafeToSpeculativelyExecute(&I))
472e9c79a7aSSanjay Patel     return false;
473e9c79a7aSSanjay Patel 
474216a37bbSSanjay Patel   Instruction *I0, *I1;
475fc445589SSanjay Patel   CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
476216a37bbSSanjay Patel   if (!match(&I, m_Cmp(Pred, m_Instruction(I0), m_Instruction(I1))) &&
477216a37bbSSanjay Patel       !match(&I, m_BinOp(m_Instruction(I0), m_Instruction(I1))))
478fc445589SSanjay Patel     return false;
479fc445589SSanjay Patel 
480fc445589SSanjay Patel   Value *V0, *V1;
481fc445589SSanjay Patel   uint64_t C0, C1;
482216a37bbSSanjay Patel   if (!match(I0, m_ExtractElt(m_Value(V0), m_ConstantInt(C0))) ||
483216a37bbSSanjay Patel       !match(I1, m_ExtractElt(m_Value(V1), m_ConstantInt(C1))) ||
484fc445589SSanjay Patel       V0->getType() != V1->getType())
485fc445589SSanjay Patel     return false;
486fc445589SSanjay Patel 
487ce97ce3aSSanjay Patel   // If the scalar value 'I' is going to be re-inserted into a vector, then try
488ce97ce3aSSanjay Patel   // to create an extract to that same element. The extract/insert can be
489ce97ce3aSSanjay Patel   // reduced to a "select shuffle".
490ce97ce3aSSanjay Patel   // TODO: If we add a larger pattern match that starts from an insert, this
491ce97ce3aSSanjay Patel   //       probably becomes unnecessary.
492216a37bbSSanjay Patel   auto *Ext0 = cast<ExtractElementInst>(I0);
493216a37bbSSanjay Patel   auto *Ext1 = cast<ExtractElementInst>(I1);
494a0f96741SSanjay Patel   uint64_t InsertIndex = InvalidIndex;
495ce97ce3aSSanjay Patel   if (I.hasOneUse())
4967eed772aSSanjay Patel     match(I.user_back(),
4977eed772aSSanjay Patel           m_InsertElt(m_Value(), m_Value(), m_ConstantInt(InsertIndex)));
498ce97ce3aSSanjay Patel 
499216a37bbSSanjay Patel   ExtractElementInst *ExtractToChange;
500*0dcd2b40SSimon Pilgrim   if (isExtractExtractCheap(Ext0, Ext1, I, ExtractToChange, InsertIndex))
501fc445589SSanjay Patel     return false;
502e9c79a7aSSanjay Patel 
503216a37bbSSanjay Patel   if (ExtractToChange) {
504216a37bbSSanjay Patel     unsigned CheapExtractIdx = ExtractToChange == Ext0 ? C1 : C0;
505216a37bbSSanjay Patel     ExtractElementInst *NewExtract =
5069934cc54SSanjay Patel         translateExtract(ExtractToChange, CheapExtractIdx, Builder);
507216a37bbSSanjay Patel     if (!NewExtract)
5086d864097SSanjay Patel       return false;
509216a37bbSSanjay Patel     if (ExtractToChange == Ext0)
510216a37bbSSanjay Patel       Ext0 = NewExtract;
511a69158c1SSanjay Patel     else
512216a37bbSSanjay Patel       Ext1 = NewExtract;
513a69158c1SSanjay Patel   }
514e9c79a7aSSanjay Patel 
515e9c79a7aSSanjay Patel   if (Pred != CmpInst::BAD_ICMP_PREDICATE)
516039ff29eSSanjay Patel     foldExtExtCmp(Ext0, Ext1, I);
517e9c79a7aSSanjay Patel   else
518039ff29eSSanjay Patel     foldExtExtBinop(Ext0, Ext1, I);
519e9c79a7aSSanjay Patel 
520300870a9SFlorian Hahn   Worklist.push(Ext0);
521300870a9SFlorian Hahn   Worklist.push(Ext1);
522e9c79a7aSSanjay Patel   return true;
523fc445589SSanjay Patel }
524fc445589SSanjay Patel 
525bef6e67eSSanjay Patel /// If this is a bitcast of a shuffle, try to bitcast the source vector to the
526bef6e67eSSanjay Patel /// destination type followed by shuffle. This can enable further transforms by
527bef6e67eSSanjay Patel /// moving bitcasts or shuffles together.
5286bdd531aSSanjay Patel bool VectorCombine::foldBitcastShuf(Instruction &I) {
529b6050ca1SSanjay Patel   Value *V;
530b6050ca1SSanjay Patel   ArrayRef<int> Mask;
5317eed772aSSanjay Patel   if (!match(&I, m_BitCast(
5327eed772aSSanjay Patel                      m_OneUse(m_Shuffle(m_Value(V), m_Undef(), m_Mask(Mask))))))
533b6050ca1SSanjay Patel     return false;
534b6050ca1SSanjay Patel 
535b4f04d71SHuihui Zhang   // 1) Do not fold bitcast shuffle for scalable type. First, shuffle cost for
536b4f04d71SHuihui Zhang   // scalable type is unknown; Second, we cannot reason if the narrowed shuffle
537b4f04d71SHuihui Zhang   // mask for scalable type is a splat or not.
538b4f04d71SHuihui Zhang   // 2) Disallow non-vector casts and length-changing shuffles.
539bef6e67eSSanjay Patel   // TODO: We could allow any shuffle.
540b4f04d71SHuihui Zhang   auto *DestTy = dyn_cast<FixedVectorType>(I.getType());
541b4f04d71SHuihui Zhang   auto *SrcTy = dyn_cast<FixedVectorType>(V->getType());
542b4f04d71SHuihui Zhang   if (!SrcTy || !DestTy || I.getOperand(0)->getType() != SrcTy)
543b6050ca1SSanjay Patel     return false;
544b6050ca1SSanjay Patel 
545b4f04d71SHuihui Zhang   unsigned DestNumElts = DestTy->getNumElements();
546b4f04d71SHuihui Zhang   unsigned SrcNumElts = SrcTy->getNumElements();
547b6050ca1SSanjay Patel   SmallVector<int, 16> NewMask;
548bef6e67eSSanjay Patel   if (SrcNumElts <= DestNumElts) {
549bef6e67eSSanjay Patel     // The bitcast is from wide to narrow/equal elements. The shuffle mask can
550bef6e67eSSanjay Patel     // always be expanded to the equivalent form choosing narrower elements.
551b6050ca1SSanjay Patel     assert(DestNumElts % SrcNumElts == 0 && "Unexpected shuffle mask");
552b6050ca1SSanjay Patel     unsigned ScaleFactor = DestNumElts / SrcNumElts;
5531318ddbcSSanjay Patel     narrowShuffleMaskElts(ScaleFactor, Mask, NewMask);
554bef6e67eSSanjay Patel   } else {
555bef6e67eSSanjay Patel     // The bitcast is from narrow elements to wide elements. The shuffle mask
556bef6e67eSSanjay Patel     // must choose consecutive elements to allow casting first.
557bef6e67eSSanjay Patel     assert(SrcNumElts % DestNumElts == 0 && "Unexpected shuffle mask");
558bef6e67eSSanjay Patel     unsigned ScaleFactor = SrcNumElts / DestNumElts;
559bef6e67eSSanjay Patel     if (!widenShuffleMaskElts(ScaleFactor, Mask, NewMask))
560bef6e67eSSanjay Patel       return false;
561bef6e67eSSanjay Patel   }
562e2935dcfSDavid Green 
563e2935dcfSDavid Green   // The new shuffle must not cost more than the old shuffle. The bitcast is
564e2935dcfSDavid Green   // moved ahead of the shuffle, so assume that it has the same cost as before.
565e2935dcfSDavid Green   InstructionCost DestCost = TTI.getShuffleCost(
566e2935dcfSDavid Green       TargetTransformInfo::SK_PermuteSingleSrc, DestTy, NewMask);
567e2935dcfSDavid Green   InstructionCost SrcCost =
568e2935dcfSDavid Green       TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, SrcTy, Mask);
569e2935dcfSDavid Green   if (DestCost > SrcCost || !DestCost.isValid())
570e2935dcfSDavid Green     return false;
571e2935dcfSDavid Green 
572bef6e67eSSanjay Patel   // bitcast (shuf V, MaskC) --> shuf (bitcast V), MaskC'
5737aeb41b3SRoman Lebedev   ++NumShufOfBitcast;
574bef6e67eSSanjay Patel   Value *CastV = Builder.CreateBitCast(V, DestTy);
5751e6b240dSSanjay Patel   Value *Shuf = Builder.CreateShuffleVector(CastV, NewMask);
57698c2f4eeSSanjay Patel   replaceValue(I, *Shuf);
577b6050ca1SSanjay Patel   return true;
578b6050ca1SSanjay Patel }
579b6050ca1SSanjay Patel 
580ed67f5e7SSanjay Patel /// Match a vector binop or compare instruction with at least one inserted
581ed67f5e7SSanjay Patel /// scalar operand and convert to scalar binop/cmp followed by insertelement.
5826bdd531aSSanjay Patel bool VectorCombine::scalarizeBinopOrCmp(Instruction &I) {
583ed67f5e7SSanjay Patel   CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
5845dc4e7c2SSimon Pilgrim   Value *Ins0, *Ins1;
585ed67f5e7SSanjay Patel   if (!match(&I, m_BinOp(m_Value(Ins0), m_Value(Ins1))) &&
586ed67f5e7SSanjay Patel       !match(&I, m_Cmp(Pred, m_Value(Ins0), m_Value(Ins1))))
587ed67f5e7SSanjay Patel     return false;
588ed67f5e7SSanjay Patel 
589ed67f5e7SSanjay Patel   // Do not convert the vector condition of a vector select into a scalar
590ed67f5e7SSanjay Patel   // condition. That may cause problems for codegen because of differences in
591ed67f5e7SSanjay Patel   // boolean formats and register-file transfers.
592ed67f5e7SSanjay Patel   // TODO: Can we account for that in the cost model?
593ed67f5e7SSanjay Patel   bool IsCmp = Pred != CmpInst::Predicate::BAD_ICMP_PREDICATE;
594ed67f5e7SSanjay Patel   if (IsCmp)
595ed67f5e7SSanjay Patel     for (User *U : I.users())
596ed67f5e7SSanjay Patel       if (match(U, m_Select(m_Specific(&I), m_Value(), m_Value())))
5970d2a0b44SSanjay Patel         return false;
5980d2a0b44SSanjay Patel 
5995dc4e7c2SSimon Pilgrim   // Match against one or both scalar values being inserted into constant
6005dc4e7c2SSimon Pilgrim   // vectors:
601ed67f5e7SSanjay Patel   // vec_op VecC0, (inselt VecC1, V1, Index)
602ed67f5e7SSanjay Patel   // vec_op (inselt VecC0, V0, Index), VecC1
603ed67f5e7SSanjay Patel   // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index)
6040d2a0b44SSanjay Patel   // TODO: Deal with mismatched index constants and variable indexes?
6055dc4e7c2SSimon Pilgrim   Constant *VecC0 = nullptr, *VecC1 = nullptr;
6065dc4e7c2SSimon Pilgrim   Value *V0 = nullptr, *V1 = nullptr;
6075dc4e7c2SSimon Pilgrim   uint64_t Index0 = 0, Index1 = 0;
6087eed772aSSanjay Patel   if (!match(Ins0, m_InsertElt(m_Constant(VecC0), m_Value(V0),
6095dc4e7c2SSimon Pilgrim                                m_ConstantInt(Index0))) &&
6105dc4e7c2SSimon Pilgrim       !match(Ins0, m_Constant(VecC0)))
6115dc4e7c2SSimon Pilgrim     return false;
6125dc4e7c2SSimon Pilgrim   if (!match(Ins1, m_InsertElt(m_Constant(VecC1), m_Value(V1),
6135dc4e7c2SSimon Pilgrim                                m_ConstantInt(Index1))) &&
6145dc4e7c2SSimon Pilgrim       !match(Ins1, m_Constant(VecC1)))
6150d2a0b44SSanjay Patel     return false;
6160d2a0b44SSanjay Patel 
6175dc4e7c2SSimon Pilgrim   bool IsConst0 = !V0;
6185dc4e7c2SSimon Pilgrim   bool IsConst1 = !V1;
6195dc4e7c2SSimon Pilgrim   if (IsConst0 && IsConst1)
6205dc4e7c2SSimon Pilgrim     return false;
6215dc4e7c2SSimon Pilgrim   if (!IsConst0 && !IsConst1 && Index0 != Index1)
6225dc4e7c2SSimon Pilgrim     return false;
6235dc4e7c2SSimon Pilgrim 
6245dc4e7c2SSimon Pilgrim   // Bail for single insertion if it is a load.
6255dc4e7c2SSimon Pilgrim   // TODO: Handle this once getVectorInstrCost can cost for load/stores.
6265dc4e7c2SSimon Pilgrim   auto *I0 = dyn_cast_or_null<Instruction>(V0);
6275dc4e7c2SSimon Pilgrim   auto *I1 = dyn_cast_or_null<Instruction>(V1);
6285dc4e7c2SSimon Pilgrim   if ((IsConst0 && I1 && I1->mayReadFromMemory()) ||
6295dc4e7c2SSimon Pilgrim       (IsConst1 && I0 && I0->mayReadFromMemory()))
6305dc4e7c2SSimon Pilgrim     return false;
6315dc4e7c2SSimon Pilgrim 
6325dc4e7c2SSimon Pilgrim   uint64_t Index = IsConst0 ? Index1 : Index0;
6335dc4e7c2SSimon Pilgrim   Type *ScalarTy = IsConst0 ? V1->getType() : V0->getType();
6340d2a0b44SSanjay Patel   Type *VecTy = I.getType();
6355dc4e7c2SSimon Pilgrim   assert(VecTy->isVectorTy() &&
6365dc4e7c2SSimon Pilgrim          (IsConst0 || IsConst1 || V0->getType() == V1->getType()) &&
637741e20f3SSanjay Patel          (ScalarTy->isIntegerTy() || ScalarTy->isFloatingPointTy() ||
638741e20f3SSanjay Patel           ScalarTy->isPointerTy()) &&
639741e20f3SSanjay Patel          "Unexpected types for insert element into binop or cmp");
6400d2a0b44SSanjay Patel 
641ed67f5e7SSanjay Patel   unsigned Opcode = I.getOpcode();
64236710c38SCaroline Concatto   InstructionCost ScalarOpCost, VectorOpCost;
643ed67f5e7SSanjay Patel   if (IsCmp) {
644*0dcd2b40SSimon Pilgrim     CmpInst::Predicate Pred = cast<CmpInst>(I).getPredicate();
645*0dcd2b40SSimon Pilgrim     ScalarOpCost = TTI.getCmpSelInstrCost(
646*0dcd2b40SSimon Pilgrim         Opcode, ScalarTy, CmpInst::makeCmpResultType(ScalarTy), Pred);
647*0dcd2b40SSimon Pilgrim     VectorOpCost = TTI.getCmpSelInstrCost(
648*0dcd2b40SSimon Pilgrim         Opcode, VecTy, CmpInst::makeCmpResultType(VecTy), Pred);
649ed67f5e7SSanjay Patel   } else {
650ed67f5e7SSanjay Patel     ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
651ed67f5e7SSanjay Patel     VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
652ed67f5e7SSanjay Patel   }
6530d2a0b44SSanjay Patel 
6540d2a0b44SSanjay Patel   // Get cost estimate for the insert element. This cost will factor into
6550d2a0b44SSanjay Patel   // both sequences.
65636710c38SCaroline Concatto   InstructionCost InsertCost =
6570d2a0b44SSanjay Patel       TTI.getVectorInstrCost(Instruction::InsertElement, VecTy, Index);
65836710c38SCaroline Concatto   InstructionCost OldCost =
65936710c38SCaroline Concatto       (IsConst0 ? 0 : InsertCost) + (IsConst1 ? 0 : InsertCost) + VectorOpCost;
66036710c38SCaroline Concatto   InstructionCost NewCost = ScalarOpCost + InsertCost +
6615dc4e7c2SSimon Pilgrim                             (IsConst0 ? 0 : !Ins0->hasOneUse() * InsertCost) +
6625dc4e7c2SSimon Pilgrim                             (IsConst1 ? 0 : !Ins1->hasOneUse() * InsertCost);
6630d2a0b44SSanjay Patel 
6640d2a0b44SSanjay Patel   // We want to scalarize unless the vector variant actually has lower cost.
66536710c38SCaroline Concatto   if (OldCost < NewCost || !NewCost.isValid())
6660d2a0b44SSanjay Patel     return false;
6670d2a0b44SSanjay Patel 
668ed67f5e7SSanjay Patel   // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index) -->
669ed67f5e7SSanjay Patel   // inselt NewVecC, (scalar_op V0, V1), Index
670ed67f5e7SSanjay Patel   if (IsCmp)
671ed67f5e7SSanjay Patel     ++NumScalarCmp;
672ed67f5e7SSanjay Patel   else
6730d2a0b44SSanjay Patel     ++NumScalarBO;
6745dc4e7c2SSimon Pilgrim 
6755dc4e7c2SSimon Pilgrim   // For constant cases, extract the scalar element, this should constant fold.
6765dc4e7c2SSimon Pilgrim   if (IsConst0)
6775dc4e7c2SSimon Pilgrim     V0 = ConstantExpr::getExtractElement(VecC0, Builder.getInt64(Index));
6785dc4e7c2SSimon Pilgrim   if (IsConst1)
6795dc4e7c2SSimon Pilgrim     V1 = ConstantExpr::getExtractElement(VecC1, Builder.getInt64(Index));
6805dc4e7c2SSimon Pilgrim 
681ed67f5e7SSanjay Patel   Value *Scalar =
68246a285adSSanjay Patel       IsCmp ? Builder.CreateCmp(Pred, V0, V1)
683ed67f5e7SSanjay Patel             : Builder.CreateBinOp((Instruction::BinaryOps)Opcode, V0, V1);
684ed67f5e7SSanjay Patel 
685ed67f5e7SSanjay Patel   Scalar->setName(I.getName() + ".scalar");
6860d2a0b44SSanjay Patel 
6870d2a0b44SSanjay Patel   // All IR flags are safe to back-propagate. There is no potential for extra
6880d2a0b44SSanjay Patel   // poison to be created by the scalar instruction.
6890d2a0b44SSanjay Patel   if (auto *ScalarInst = dyn_cast<Instruction>(Scalar))
6900d2a0b44SSanjay Patel     ScalarInst->copyIRFlags(&I);
6910d2a0b44SSanjay Patel 
6920d2a0b44SSanjay Patel   // Fold the vector constants in the original vectors into a new base vector.
693ed67f5e7SSanjay Patel   Constant *NewVecC = IsCmp ? ConstantExpr::getCompare(Pred, VecC0, VecC1)
694ed67f5e7SSanjay Patel                             : ConstantExpr::get(Opcode, VecC0, VecC1);
6950d2a0b44SSanjay Patel   Value *Insert = Builder.CreateInsertElement(NewVecC, Scalar, Index);
69698c2f4eeSSanjay Patel   replaceValue(I, *Insert);
6970d2a0b44SSanjay Patel   return true;
6980d2a0b44SSanjay Patel }
6990d2a0b44SSanjay Patel 
700b6315aeeSSanjay Patel /// Try to combine a scalar binop + 2 scalar compares of extracted elements of
701b6315aeeSSanjay Patel /// a vector into vector operations followed by extract. Note: The SLP pass
702b6315aeeSSanjay Patel /// may miss this pattern because of implementation problems.
703b6315aeeSSanjay Patel bool VectorCombine::foldExtractedCmps(Instruction &I) {
704b6315aeeSSanjay Patel   // We are looking for a scalar binop of booleans.
705b6315aeeSSanjay Patel   // binop i1 (cmp Pred I0, C0), (cmp Pred I1, C1)
706b6315aeeSSanjay Patel   if (!I.isBinaryOp() || !I.getType()->isIntegerTy(1))
707b6315aeeSSanjay Patel     return false;
708b6315aeeSSanjay Patel 
709b6315aeeSSanjay Patel   // The compare predicates should match, and each compare should have a
710b6315aeeSSanjay Patel   // constant operand.
711b6315aeeSSanjay Patel   // TODO: Relax the one-use constraints.
712b6315aeeSSanjay Patel   Value *B0 = I.getOperand(0), *B1 = I.getOperand(1);
713b6315aeeSSanjay Patel   Instruction *I0, *I1;
714b6315aeeSSanjay Patel   Constant *C0, *C1;
715b6315aeeSSanjay Patel   CmpInst::Predicate P0, P1;
716b6315aeeSSanjay Patel   if (!match(B0, m_OneUse(m_Cmp(P0, m_Instruction(I0), m_Constant(C0)))) ||
717b6315aeeSSanjay Patel       !match(B1, m_OneUse(m_Cmp(P1, m_Instruction(I1), m_Constant(C1)))) ||
718b6315aeeSSanjay Patel       P0 != P1)
719b6315aeeSSanjay Patel     return false;
720b6315aeeSSanjay Patel 
721b6315aeeSSanjay Patel   // The compare operands must be extracts of the same vector with constant
722b6315aeeSSanjay Patel   // extract indexes.
723b6315aeeSSanjay Patel   // TODO: Relax the one-use constraints.
724b6315aeeSSanjay Patel   Value *X;
725b6315aeeSSanjay Patel   uint64_t Index0, Index1;
726b6315aeeSSanjay Patel   if (!match(I0, m_OneUse(m_ExtractElt(m_Value(X), m_ConstantInt(Index0)))) ||
727b6315aeeSSanjay Patel       !match(I1, m_OneUse(m_ExtractElt(m_Specific(X), m_ConstantInt(Index1)))))
728b6315aeeSSanjay Patel     return false;
729b6315aeeSSanjay Patel 
730b6315aeeSSanjay Patel   auto *Ext0 = cast<ExtractElementInst>(I0);
731b6315aeeSSanjay Patel   auto *Ext1 = cast<ExtractElementInst>(I1);
732b6315aeeSSanjay Patel   ExtractElementInst *ConvertToShuf = getShuffleExtract(Ext0, Ext1);
733b6315aeeSSanjay Patel   if (!ConvertToShuf)
734b6315aeeSSanjay Patel     return false;
735b6315aeeSSanjay Patel 
736b6315aeeSSanjay Patel   // The original scalar pattern is:
737b6315aeeSSanjay Patel   // binop i1 (cmp Pred (ext X, Index0), C0), (cmp Pred (ext X, Index1), C1)
738b6315aeeSSanjay Patel   CmpInst::Predicate Pred = P0;
739b6315aeeSSanjay Patel   unsigned CmpOpcode = CmpInst::isFPPredicate(Pred) ? Instruction::FCmp
740b6315aeeSSanjay Patel                                                     : Instruction::ICmp;
741b6315aeeSSanjay Patel   auto *VecTy = dyn_cast<FixedVectorType>(X->getType());
742b6315aeeSSanjay Patel   if (!VecTy)
743b6315aeeSSanjay Patel     return false;
744b6315aeeSSanjay Patel 
74536710c38SCaroline Concatto   InstructionCost OldCost =
74636710c38SCaroline Concatto       TTI.getVectorInstrCost(Ext0->getOpcode(), VecTy, Index0);
747b6315aeeSSanjay Patel   OldCost += TTI.getVectorInstrCost(Ext1->getOpcode(), VecTy, Index1);
748*0dcd2b40SSimon Pilgrim   OldCost +=
749*0dcd2b40SSimon Pilgrim       TTI.getCmpSelInstrCost(CmpOpcode, I0->getType(),
750*0dcd2b40SSimon Pilgrim                              CmpInst::makeCmpResultType(I0->getType()), Pred) *
751*0dcd2b40SSimon Pilgrim       2;
752b6315aeeSSanjay Patel   OldCost += TTI.getArithmeticInstrCost(I.getOpcode(), I.getType());
753b6315aeeSSanjay Patel 
754b6315aeeSSanjay Patel   // The proposed vector pattern is:
755b6315aeeSSanjay Patel   // vcmp = cmp Pred X, VecC
756b6315aeeSSanjay Patel   // ext (binop vNi1 vcmp, (shuffle vcmp, Index1)), Index0
757b6315aeeSSanjay Patel   int CheapIndex = ConvertToShuf == Ext0 ? Index1 : Index0;
758b6315aeeSSanjay Patel   int ExpensiveIndex = ConvertToShuf == Ext0 ? Index0 : Index1;
759b6315aeeSSanjay Patel   auto *CmpTy = cast<FixedVectorType>(CmpInst::makeCmpResultType(X->getType()));
760*0dcd2b40SSimon Pilgrim   InstructionCost NewCost = TTI.getCmpSelInstrCost(
761*0dcd2b40SSimon Pilgrim       CmpOpcode, X->getType(), CmpInst::makeCmpResultType(X->getType()), Pred);
762e2935dcfSDavid Green   SmallVector<int, 32> ShufMask(VecTy->getNumElements(), UndefMaskElem);
763e2935dcfSDavid Green   ShufMask[CheapIndex] = ExpensiveIndex;
764e2935dcfSDavid Green   NewCost += TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, CmpTy,
765e2935dcfSDavid Green                                 ShufMask);
766b6315aeeSSanjay Patel   NewCost += TTI.getArithmeticInstrCost(I.getOpcode(), CmpTy);
767b6315aeeSSanjay Patel   NewCost += TTI.getVectorInstrCost(Ext0->getOpcode(), CmpTy, CheapIndex);
768b6315aeeSSanjay Patel 
769b6315aeeSSanjay Patel   // Aggressively form vector ops if the cost is equal because the transform
770b6315aeeSSanjay Patel   // may enable further optimization.
771b6315aeeSSanjay Patel   // Codegen can reverse this transform (scalarize) if it was not profitable.
77236710c38SCaroline Concatto   if (OldCost < NewCost || !NewCost.isValid())
773b6315aeeSSanjay Patel     return false;
774b6315aeeSSanjay Patel 
775b6315aeeSSanjay Patel   // Create a vector constant from the 2 scalar constants.
776b6315aeeSSanjay Patel   SmallVector<Constant *, 32> CmpC(VecTy->getNumElements(),
777b6315aeeSSanjay Patel                                    UndefValue::get(VecTy->getElementType()));
778b6315aeeSSanjay Patel   CmpC[Index0] = C0;
779b6315aeeSSanjay Patel   CmpC[Index1] = C1;
780b6315aeeSSanjay Patel   Value *VCmp = Builder.CreateCmp(Pred, X, ConstantVector::get(CmpC));
781b6315aeeSSanjay Patel 
782b6315aeeSSanjay Patel   Value *Shuf = createShiftShuffle(VCmp, ExpensiveIndex, CheapIndex, Builder);
783b6315aeeSSanjay Patel   Value *VecLogic = Builder.CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
784b6315aeeSSanjay Patel                                         VCmp, Shuf);
785b6315aeeSSanjay Patel   Value *NewExt = Builder.CreateExtractElement(VecLogic, CheapIndex);
786b6315aeeSSanjay Patel   replaceValue(I, *NewExt);
787b6315aeeSSanjay Patel   ++NumVecCmpBO;
788b6315aeeSSanjay Patel   return true;
789b6315aeeSSanjay Patel }
790b6315aeeSSanjay Patel 
7912db4979cSQiu Chaofan // Check if memory loc modified between two instrs in the same BB
7922db4979cSQiu Chaofan static bool isMemModifiedBetween(BasicBlock::iterator Begin,
7932db4979cSQiu Chaofan                                  BasicBlock::iterator End,
7942db4979cSQiu Chaofan                                  const MemoryLocation &Loc, AAResults &AA) {
7952db4979cSQiu Chaofan   unsigned NumScanned = 0;
7962db4979cSQiu Chaofan   return std::any_of(Begin, End, [&](const Instruction &Instr) {
7972db4979cSQiu Chaofan     return isModSet(AA.getModRefInfo(&Instr, Loc)) ||
7982db4979cSQiu Chaofan            ++NumScanned > MaxInstrsToScan;
7992db4979cSQiu Chaofan   });
8002db4979cSQiu Chaofan }
8012db4979cSQiu Chaofan 
802c24fc37eSFlorian Hahn /// Helper class to indicate whether a vector index can be safely scalarized and
803c24fc37eSFlorian Hahn /// if a freeze needs to be inserted.
804c24fc37eSFlorian Hahn class ScalarizationResult {
805c24fc37eSFlorian Hahn   enum class StatusTy { Unsafe, Safe, SafeWithFreeze };
806c24fc37eSFlorian Hahn 
807c24fc37eSFlorian Hahn   StatusTy Status;
808c24fc37eSFlorian Hahn   Value *ToFreeze;
809c24fc37eSFlorian Hahn 
810c24fc37eSFlorian Hahn   ScalarizationResult(StatusTy Status, Value *ToFreeze = nullptr)
811c24fc37eSFlorian Hahn       : Status(Status), ToFreeze(ToFreeze) {}
812c24fc37eSFlorian Hahn 
813c24fc37eSFlorian Hahn public:
814c24fc37eSFlorian Hahn   ScalarizationResult(const ScalarizationResult &Other) = default;
815c24fc37eSFlorian Hahn   ~ScalarizationResult() {
816c24fc37eSFlorian Hahn     assert(!ToFreeze && "freeze() not called with ToFreeze being set");
817c24fc37eSFlorian Hahn   }
818c24fc37eSFlorian Hahn 
819c24fc37eSFlorian Hahn   static ScalarizationResult unsafe() { return {StatusTy::Unsafe}; }
820c24fc37eSFlorian Hahn   static ScalarizationResult safe() { return {StatusTy::Safe}; }
821c24fc37eSFlorian Hahn   static ScalarizationResult safeWithFreeze(Value *ToFreeze) {
822c24fc37eSFlorian Hahn     return {StatusTy::SafeWithFreeze, ToFreeze};
823c24fc37eSFlorian Hahn   }
824c24fc37eSFlorian Hahn 
825c24fc37eSFlorian Hahn   /// Returns true if the index can be scalarize without requiring a freeze.
826c24fc37eSFlorian Hahn   bool isSafe() const { return Status == StatusTy::Safe; }
827c24fc37eSFlorian Hahn   /// Returns true if the index cannot be scalarized.
828c24fc37eSFlorian Hahn   bool isUnsafe() const { return Status == StatusTy::Unsafe; }
829c24fc37eSFlorian Hahn   /// Returns true if the index can be scalarize, but requires inserting a
830c24fc37eSFlorian Hahn   /// freeze.
831c24fc37eSFlorian Hahn   bool isSafeWithFreeze() const { return Status == StatusTy::SafeWithFreeze; }
832c24fc37eSFlorian Hahn 
833e2f6290eSFlorian Hahn   /// Reset the state of Unsafe and clear ToFreze if set.
834e2f6290eSFlorian Hahn   void discard() {
835e2f6290eSFlorian Hahn     ToFreeze = nullptr;
836e2f6290eSFlorian Hahn     Status = StatusTy::Unsafe;
837e2f6290eSFlorian Hahn   }
838e2f6290eSFlorian Hahn 
839c24fc37eSFlorian Hahn   /// Freeze the ToFreeze and update the use in \p User to use it.
840c24fc37eSFlorian Hahn   void freeze(IRBuilder<> &Builder, Instruction &UserI) {
841c24fc37eSFlorian Hahn     assert(isSafeWithFreeze() &&
842c24fc37eSFlorian Hahn            "should only be used when freezing is required");
843c24fc37eSFlorian Hahn     assert(is_contained(ToFreeze->users(), &UserI) &&
844c24fc37eSFlorian Hahn            "UserI must be a user of ToFreeze");
845c24fc37eSFlorian Hahn     IRBuilder<>::InsertPointGuard Guard(Builder);
846c24fc37eSFlorian Hahn     Builder.SetInsertPoint(cast<Instruction>(&UserI));
847c24fc37eSFlorian Hahn     Value *Frozen =
848c24fc37eSFlorian Hahn         Builder.CreateFreeze(ToFreeze, ToFreeze->getName() + ".frozen");
849c24fc37eSFlorian Hahn     for (Use &U : make_early_inc_range((UserI.operands())))
850c24fc37eSFlorian Hahn       if (U.get() == ToFreeze)
851c24fc37eSFlorian Hahn         U.set(Frozen);
852c24fc37eSFlorian Hahn 
853c24fc37eSFlorian Hahn     ToFreeze = nullptr;
854c24fc37eSFlorian Hahn   }
855c24fc37eSFlorian Hahn };
856c24fc37eSFlorian Hahn 
8574e8c28b6SFlorian Hahn /// Check if it is legal to scalarize a memory access to \p VecTy at index \p
8584e8c28b6SFlorian Hahn /// Idx. \p Idx must access a valid vector element.
859c24fc37eSFlorian Hahn static ScalarizationResult canScalarizeAccess(FixedVectorType *VecTy,
860c24fc37eSFlorian Hahn                                               Value *Idx, Instruction *CtxI,
8615131037eSFlorian Hahn                                               AssumptionCache &AC,
8625131037eSFlorian Hahn                                               const DominatorTree &DT) {
863c24fc37eSFlorian Hahn   if (auto *C = dyn_cast<ConstantInt>(Idx)) {
864c24fc37eSFlorian Hahn     if (C->getValue().ult(VecTy->getNumElements()))
865c24fc37eSFlorian Hahn       return ScalarizationResult::safe();
866c24fc37eSFlorian Hahn     return ScalarizationResult::unsafe();
867c24fc37eSFlorian Hahn   }
868575e2affSFlorian Hahn 
869c24fc37eSFlorian Hahn   unsigned IntWidth = Idx->getType()->getScalarSizeInBits();
870c24fc37eSFlorian Hahn   APInt Zero(IntWidth, 0);
871c24fc37eSFlorian Hahn   APInt MaxElts(IntWidth, VecTy->getNumElements());
872575e2affSFlorian Hahn   ConstantRange ValidIndices(Zero, MaxElts);
873c24fc37eSFlorian Hahn   ConstantRange IdxRange(IntWidth, true);
874c24fc37eSFlorian Hahn 
875c24fc37eSFlorian Hahn   if (isGuaranteedNotToBePoison(Idx, &AC)) {
8765131037eSFlorian Hahn     if (ValidIndices.contains(computeConstantRange(Idx, true, &AC, CtxI, &DT)))
877c24fc37eSFlorian Hahn       return ScalarizationResult::safe();
878c24fc37eSFlorian Hahn     return ScalarizationResult::unsafe();
879c24fc37eSFlorian Hahn   }
880c24fc37eSFlorian Hahn 
881c24fc37eSFlorian Hahn   // If the index may be poison, check if we can insert a freeze before the
882c24fc37eSFlorian Hahn   // range of the index is restricted.
883c24fc37eSFlorian Hahn   Value *IdxBase;
884c24fc37eSFlorian Hahn   ConstantInt *CI;
885c24fc37eSFlorian Hahn   if (match(Idx, m_And(m_Value(IdxBase), m_ConstantInt(CI)))) {
886c24fc37eSFlorian Hahn     IdxRange = IdxRange.binaryAnd(CI->getValue());
887c24fc37eSFlorian Hahn   } else if (match(Idx, m_URem(m_Value(IdxBase), m_ConstantInt(CI)))) {
888c24fc37eSFlorian Hahn     IdxRange = IdxRange.urem(CI->getValue());
889c24fc37eSFlorian Hahn   }
890c24fc37eSFlorian Hahn 
891c24fc37eSFlorian Hahn   if (ValidIndices.contains(IdxRange))
892c24fc37eSFlorian Hahn     return ScalarizationResult::safeWithFreeze(IdxBase);
893c24fc37eSFlorian Hahn   return ScalarizationResult::unsafe();
8944e8c28b6SFlorian Hahn }
8954e8c28b6SFlorian Hahn 
896abc0e012SRoman Lebedev /// The memory operation on a vector of \p ScalarType had alignment of
897abc0e012SRoman Lebedev /// \p VectorAlignment. Compute the maximal, but conservatively correct,
898abc0e012SRoman Lebedev /// alignment that will be valid for the memory operation on a single scalar
899abc0e012SRoman Lebedev /// element of the same type with index \p Idx.
900abc0e012SRoman Lebedev static Align computeAlignmentAfterScalarization(Align VectorAlignment,
901abc0e012SRoman Lebedev                                                 Type *ScalarType, Value *Idx,
902abc0e012SRoman Lebedev                                                 const DataLayout &DL) {
903abc0e012SRoman Lebedev   if (auto *C = dyn_cast<ConstantInt>(Idx))
904abc0e012SRoman Lebedev     return commonAlignment(VectorAlignment,
905abc0e012SRoman Lebedev                            C->getZExtValue() * DL.getTypeStoreSize(ScalarType));
906abc0e012SRoman Lebedev   return commonAlignment(VectorAlignment, DL.getTypeStoreSize(ScalarType));
907abc0e012SRoman Lebedev }
908abc0e012SRoman Lebedev 
9092db4979cSQiu Chaofan // Combine patterns like:
9102db4979cSQiu Chaofan //   %0 = load <4 x i32>, <4 x i32>* %a
9112db4979cSQiu Chaofan //   %1 = insertelement <4 x i32> %0, i32 %b, i32 1
9122db4979cSQiu Chaofan //   store <4 x i32> %1, <4 x i32>* %a
9132db4979cSQiu Chaofan // to:
9142db4979cSQiu Chaofan //   %0 = bitcast <4 x i32>* %a to i32*
9152db4979cSQiu Chaofan //   %1 = getelementptr inbounds i32, i32* %0, i64 0, i64 1
9162db4979cSQiu Chaofan //   store i32 %b, i32* %1
9172db4979cSQiu Chaofan bool VectorCombine::foldSingleElementStore(Instruction &I) {
9182db4979cSQiu Chaofan   StoreInst *SI = dyn_cast<StoreInst>(&I);
9196d2df181SQiu Chaofan   if (!SI || !SI->isSimple() ||
9206d2df181SQiu Chaofan       !isa<FixedVectorType>(SI->getValueOperand()->getType()))
9212db4979cSQiu Chaofan     return false;
9222db4979cSQiu Chaofan 
9232db4979cSQiu Chaofan   // TODO: Combine more complicated patterns (multiple insert) by referencing
9242db4979cSQiu Chaofan   // TargetTransformInfo.
9252db4979cSQiu Chaofan   Instruction *Source;
9266d2df181SQiu Chaofan   Value *NewElement;
927575e2affSFlorian Hahn   Value *Idx;
9282db4979cSQiu Chaofan   if (!match(SI->getValueOperand(),
9292db4979cSQiu Chaofan              m_InsertElt(m_Instruction(Source), m_Value(NewElement),
930575e2affSFlorian Hahn                          m_Value(Idx))))
9312db4979cSQiu Chaofan     return false;
9322db4979cSQiu Chaofan 
9332db4979cSQiu Chaofan   if (auto *Load = dyn_cast<LoadInst>(Source)) {
9346d2df181SQiu Chaofan     auto VecTy = cast<FixedVectorType>(SI->getValueOperand()->getType());
9352db4979cSQiu Chaofan     const DataLayout &DL = I.getModule()->getDataLayout();
9362db4979cSQiu Chaofan     Value *SrcAddr = Load->getPointerOperand()->stripPointerCasts();
9376d2df181SQiu Chaofan     // Don't optimize for atomic/volatile load or store. Ensure memory is not
9386d2df181SQiu Chaofan     // modified between, vector type matches store size, and index is inbounds.
9392db4979cSQiu Chaofan     if (!Load->isSimple() || Load->getParent() != SI->getParent() ||
9402db4979cSQiu Chaofan         !DL.typeSizeEqualsStoreSize(Load->getType()) ||
941c24fc37eSFlorian Hahn         SrcAddr != SI->getPointerOperand()->stripPointerCasts())
942c24fc37eSFlorian Hahn       return false;
943c24fc37eSFlorian Hahn 
9445131037eSFlorian Hahn     auto ScalarizableIdx = canScalarizeAccess(VecTy, Idx, Load, AC, DT);
945c24fc37eSFlorian Hahn     if (ScalarizableIdx.isUnsafe() ||
9462db4979cSQiu Chaofan         isMemModifiedBetween(Load->getIterator(), SI->getIterator(),
9472db4979cSQiu Chaofan                              MemoryLocation::get(SI), AA))
9482db4979cSQiu Chaofan       return false;
9492db4979cSQiu Chaofan 
950c24fc37eSFlorian Hahn     if (ScalarizableIdx.isSafeWithFreeze())
951c24fc37eSFlorian Hahn       ScalarizableIdx.freeze(Builder, *cast<Instruction>(Idx));
952a213f735SNikita Popov     Value *GEP = Builder.CreateInBoundsGEP(
953a213f735SNikita Popov         SI->getValueOperand()->getType(), SI->getPointerOperand(),
954a213f735SNikita Popov         {ConstantInt::get(Idx->getType(), 0), Idx});
9552db4979cSQiu Chaofan     StoreInst *NSI = Builder.CreateStore(NewElement, GEP);
9562db4979cSQiu Chaofan     NSI->copyMetadata(*SI);
957abc0e012SRoman Lebedev     Align ScalarOpAlignment = computeAlignmentAfterScalarization(
958abc0e012SRoman Lebedev         std::max(SI->getAlign(), Load->getAlign()), NewElement->getType(), Idx,
959abc0e012SRoman Lebedev         DL);
960abc0e012SRoman Lebedev     NSI->setAlignment(ScalarOpAlignment);
9612db4979cSQiu Chaofan     replaceValue(I, *NSI);
962300870a9SFlorian Hahn     eraseInstruction(I);
9632db4979cSQiu Chaofan     return true;
9642db4979cSQiu Chaofan   }
9652db4979cSQiu Chaofan 
9662db4979cSQiu Chaofan   return false;
9672db4979cSQiu Chaofan }
9682db4979cSQiu Chaofan 
9694e8c28b6SFlorian Hahn /// Try to scalarize vector loads feeding extractelement instructions.
9704e8c28b6SFlorian Hahn bool VectorCombine::scalarizeLoadExtract(Instruction &I) {
9714e8c28b6SFlorian Hahn   Value *Ptr;
972300870a9SFlorian Hahn   if (!match(&I, m_Load(m_Value(Ptr))))
9734e8c28b6SFlorian Hahn     return false;
9744e8c28b6SFlorian Hahn 
975300870a9SFlorian Hahn   auto *LI = cast<LoadInst>(&I);
9764e8c28b6SFlorian Hahn   const DataLayout &DL = I.getModule()->getDataLayout();
9774e8c28b6SFlorian Hahn   if (LI->isVolatile() || !DL.typeSizeEqualsStoreSize(LI->getType()))
9784e8c28b6SFlorian Hahn     return false;
9794e8c28b6SFlorian Hahn 
9804e8c28b6SFlorian Hahn   auto *FixedVT = dyn_cast<FixedVectorType>(LI->getType());
9814e8c28b6SFlorian Hahn   if (!FixedVT)
9824e8c28b6SFlorian Hahn     return false;
9834e8c28b6SFlorian Hahn 
9844e8c28b6SFlorian Hahn   InstructionCost OriginalCost = TTI.getMemoryOpCost(
9854e8c28b6SFlorian Hahn       Instruction::Load, LI->getType(), Align(LI->getAlignment()),
9864e8c28b6SFlorian Hahn       LI->getPointerAddressSpace());
9874e8c28b6SFlorian Hahn   InstructionCost ScalarizedCost = 0;
9884e8c28b6SFlorian Hahn 
9894e8c28b6SFlorian Hahn   Instruction *LastCheckedInst = LI;
9904e8c28b6SFlorian Hahn   unsigned NumInstChecked = 0;
9914e8c28b6SFlorian Hahn   // Check if all users of the load are extracts with no memory modifications
9924e8c28b6SFlorian Hahn   // between the load and the extract. Compute the cost of both the original
9934e8c28b6SFlorian Hahn   // code and the scalarized version.
9944e8c28b6SFlorian Hahn   for (User *U : LI->users()) {
9954e8c28b6SFlorian Hahn     auto *UI = dyn_cast<ExtractElementInst>(U);
9964e8c28b6SFlorian Hahn     if (!UI || UI->getParent() != LI->getParent())
9974e8c28b6SFlorian Hahn       return false;
9984e8c28b6SFlorian Hahn 
99996ca0349SFlorian Hahn     if (!isGuaranteedNotToBePoison(UI->getOperand(1), &AC, LI, &DT))
100096ca0349SFlorian Hahn       return false;
100196ca0349SFlorian Hahn 
10024e8c28b6SFlorian Hahn     // Check if any instruction between the load and the extract may modify
10034e8c28b6SFlorian Hahn     // memory.
10044e8c28b6SFlorian Hahn     if (LastCheckedInst->comesBefore(UI)) {
10054e8c28b6SFlorian Hahn       for (Instruction &I :
10064e8c28b6SFlorian Hahn            make_range(std::next(LI->getIterator()), UI->getIterator())) {
10074e8c28b6SFlorian Hahn         // Bail out if we reached the check limit or the instruction may write
10084e8c28b6SFlorian Hahn         // to memory.
10094e8c28b6SFlorian Hahn         if (NumInstChecked == MaxInstrsToScan || I.mayWriteToMemory())
10104e8c28b6SFlorian Hahn           return false;
10114e8c28b6SFlorian Hahn         NumInstChecked++;
10124e8c28b6SFlorian Hahn       }
10134e8c28b6SFlorian Hahn     }
10144e8c28b6SFlorian Hahn 
10154e8c28b6SFlorian Hahn     if (!LastCheckedInst)
10164e8c28b6SFlorian Hahn       LastCheckedInst = UI;
10174e8c28b6SFlorian Hahn     else if (LastCheckedInst->comesBefore(UI))
10184e8c28b6SFlorian Hahn       LastCheckedInst = UI;
10194e8c28b6SFlorian Hahn 
10205131037eSFlorian Hahn     auto ScalarIdx = canScalarizeAccess(FixedVT, UI->getOperand(1), &I, AC, DT);
1021c24fc37eSFlorian Hahn     if (!ScalarIdx.isSafe()) {
1022c24fc37eSFlorian Hahn       // TODO: Freeze index if it is safe to do so.
1023e2f6290eSFlorian Hahn       ScalarIdx.discard();
1024007f268cSFlorian Hahn       return false;
1025c24fc37eSFlorian Hahn     }
1026007f268cSFlorian Hahn 
10274e8c28b6SFlorian Hahn     auto *Index = dyn_cast<ConstantInt>(UI->getOperand(1));
10284e8c28b6SFlorian Hahn     OriginalCost +=
10294e8c28b6SFlorian Hahn         TTI.getVectorInstrCost(Instruction::ExtractElement, LI->getType(),
10304e8c28b6SFlorian Hahn                                Index ? Index->getZExtValue() : -1);
10314e8c28b6SFlorian Hahn     ScalarizedCost +=
10324e8c28b6SFlorian Hahn         TTI.getMemoryOpCost(Instruction::Load, FixedVT->getElementType(),
10334e8c28b6SFlorian Hahn                             Align(1), LI->getPointerAddressSpace());
10344e8c28b6SFlorian Hahn     ScalarizedCost += TTI.getAddressComputationCost(FixedVT->getElementType());
10354e8c28b6SFlorian Hahn   }
10364e8c28b6SFlorian Hahn 
10374e8c28b6SFlorian Hahn   if (ScalarizedCost >= OriginalCost)
10384e8c28b6SFlorian Hahn     return false;
10394e8c28b6SFlorian Hahn 
10404e8c28b6SFlorian Hahn   // Replace extracts with narrow scalar loads.
10414e8c28b6SFlorian Hahn   for (User *U : LI->users()) {
10424e8c28b6SFlorian Hahn     auto *EI = cast<ExtractElementInst>(U);
10434e8c28b6SFlorian Hahn     Builder.SetInsertPoint(EI);
1044d4c070d8SFlorian Hahn 
1045d4c070d8SFlorian Hahn     Value *Idx = EI->getOperand(1);
1046d4c070d8SFlorian Hahn     Value *GEP =
1047d4c070d8SFlorian Hahn         Builder.CreateInBoundsGEP(FixedVT, Ptr, {Builder.getInt32(0), Idx});
10484e8c28b6SFlorian Hahn     auto *NewLoad = cast<LoadInst>(Builder.CreateLoad(
10494e8c28b6SFlorian Hahn         FixedVT->getElementType(), GEP, EI->getName() + ".scalar"));
10504e8c28b6SFlorian Hahn 
105120542b47SRoman Lebedev     Align ScalarOpAlignment = computeAlignmentAfterScalarization(
105220542b47SRoman Lebedev         LI->getAlign(), FixedVT->getElementType(), Idx, DL);
105320542b47SRoman Lebedev     NewLoad->setAlignment(ScalarOpAlignment);
105420542b47SRoman Lebedev 
10554e8c28b6SFlorian Hahn     replaceValue(*EI, *NewLoad);
10564e8c28b6SFlorian Hahn   }
10574e8c28b6SFlorian Hahn 
10584e8c28b6SFlorian Hahn   return true;
10594e8c28b6SFlorian Hahn }
10604e8c28b6SFlorian Hahn 
1061a17f03bdSSanjay Patel /// This is the entry point for all transforms. Pass manager differences are
1062a17f03bdSSanjay Patel /// handled in the callers of this function.
10636bdd531aSSanjay Patel bool VectorCombine::run() {
106425c6544fSSanjay Patel   if (DisableVectorCombine)
106525c6544fSSanjay Patel     return false;
106625c6544fSSanjay Patel 
1067cc892fd9SSanjay Patel   // Don't attempt vectorization if the target does not support vectors.
1068cc892fd9SSanjay Patel   if (!TTI.getNumberOfRegisters(TTI.getRegisterClassForType(/*Vector*/ true)))
1069cc892fd9SSanjay Patel     return false;
1070cc892fd9SSanjay Patel 
1071a17f03bdSSanjay Patel   bool MadeChange = false;
1072300870a9SFlorian Hahn   auto FoldInst = [this, &MadeChange](Instruction &I) {
1073de65b356SSanjay Patel     Builder.SetInsertPoint(&I);
107443bdac29SSanjay Patel     MadeChange |= vectorizeLoadInsert(I);
10756bdd531aSSanjay Patel     MadeChange |= foldExtractExtract(I);
10766bdd531aSSanjay Patel     MadeChange |= foldBitcastShuf(I);
10776bdd531aSSanjay Patel     MadeChange |= scalarizeBinopOrCmp(I);
1078b6315aeeSSanjay Patel     MadeChange |= foldExtractedCmps(I);
10794e8c28b6SFlorian Hahn     MadeChange |= scalarizeLoadExtract(I);
10802db4979cSQiu Chaofan     MadeChange |= foldSingleElementStore(I);
1081300870a9SFlorian Hahn   };
1082300870a9SFlorian Hahn   for (BasicBlock &BB : F) {
1083300870a9SFlorian Hahn     // Ignore unreachable basic blocks.
1084300870a9SFlorian Hahn     if (!DT.isReachableFromEntry(&BB))
1085300870a9SFlorian Hahn       continue;
1086300870a9SFlorian Hahn     // Use early increment range so that we can erase instructions in loop.
1087300870a9SFlorian Hahn     for (Instruction &I : make_early_inc_range(BB)) {
1088300870a9SFlorian Hahn       if (isa<DbgInfoIntrinsic>(I))
1089300870a9SFlorian Hahn         continue;
1090300870a9SFlorian Hahn       FoldInst(I);
1091a17f03bdSSanjay Patel     }
1092fc3cc8a4SSanjay Patel   }
1093a17f03bdSSanjay Patel 
1094300870a9SFlorian Hahn   while (!Worklist.isEmpty()) {
1095300870a9SFlorian Hahn     Instruction *I = Worklist.removeOne();
1096300870a9SFlorian Hahn     if (!I)
1097300870a9SFlorian Hahn       continue;
1098300870a9SFlorian Hahn 
1099300870a9SFlorian Hahn     if (isInstructionTriviallyDead(I)) {
1100300870a9SFlorian Hahn       eraseInstruction(*I);
1101300870a9SFlorian Hahn       continue;
1102300870a9SFlorian Hahn     }
1103300870a9SFlorian Hahn 
1104300870a9SFlorian Hahn     FoldInst(*I);
1105300870a9SFlorian Hahn   }
1106a17f03bdSSanjay Patel 
1107a17f03bdSSanjay Patel   return MadeChange;
1108a17f03bdSSanjay Patel }
1109a17f03bdSSanjay Patel 
1110a17f03bdSSanjay Patel // Pass manager boilerplate below here.
1111a17f03bdSSanjay Patel 
1112a17f03bdSSanjay Patel namespace {
1113a17f03bdSSanjay Patel class VectorCombineLegacyPass : public FunctionPass {
1114a17f03bdSSanjay Patel public:
1115a17f03bdSSanjay Patel   static char ID;
1116a17f03bdSSanjay Patel   VectorCombineLegacyPass() : FunctionPass(ID) {
1117a17f03bdSSanjay Patel     initializeVectorCombineLegacyPassPass(*PassRegistry::getPassRegistry());
1118a17f03bdSSanjay Patel   }
1119a17f03bdSSanjay Patel 
1120a17f03bdSSanjay Patel   void getAnalysisUsage(AnalysisUsage &AU) const override {
1121575e2affSFlorian Hahn     AU.addRequired<AssumptionCacheTracker>();
1122a17f03bdSSanjay Patel     AU.addRequired<DominatorTreeWrapperPass>();
1123a17f03bdSSanjay Patel     AU.addRequired<TargetTransformInfoWrapperPass>();
11242db4979cSQiu Chaofan     AU.addRequired<AAResultsWrapperPass>();
1125a17f03bdSSanjay Patel     AU.setPreservesCFG();
1126a17f03bdSSanjay Patel     AU.addPreserved<DominatorTreeWrapperPass>();
1127a17f03bdSSanjay Patel     AU.addPreserved<GlobalsAAWrapperPass>();
1128024098aeSSanjay Patel     AU.addPreserved<AAResultsWrapperPass>();
1129024098aeSSanjay Patel     AU.addPreserved<BasicAAWrapperPass>();
1130a17f03bdSSanjay Patel     FunctionPass::getAnalysisUsage(AU);
1131a17f03bdSSanjay Patel   }
1132a17f03bdSSanjay Patel 
1133a17f03bdSSanjay Patel   bool runOnFunction(Function &F) override {
1134a17f03bdSSanjay Patel     if (skipFunction(F))
1135a17f03bdSSanjay Patel       return false;
1136575e2affSFlorian Hahn     auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1137a17f03bdSSanjay Patel     auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1138a17f03bdSSanjay Patel     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
11392db4979cSQiu Chaofan     auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1140575e2affSFlorian Hahn     VectorCombine Combiner(F, TTI, DT, AA, AC);
11416bdd531aSSanjay Patel     return Combiner.run();
1142a17f03bdSSanjay Patel   }
1143a17f03bdSSanjay Patel };
1144a17f03bdSSanjay Patel } // namespace
1145a17f03bdSSanjay Patel 
1146a17f03bdSSanjay Patel char VectorCombineLegacyPass::ID = 0;
1147a17f03bdSSanjay Patel INITIALIZE_PASS_BEGIN(VectorCombineLegacyPass, "vector-combine",
1148a17f03bdSSanjay Patel                       "Optimize scalar/vector ops", false,
1149a17f03bdSSanjay Patel                       false)
1150575e2affSFlorian Hahn INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1151a17f03bdSSanjay Patel INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1152a17f03bdSSanjay Patel INITIALIZE_PASS_END(VectorCombineLegacyPass, "vector-combine",
1153a17f03bdSSanjay Patel                     "Optimize scalar/vector ops", false, false)
1154a17f03bdSSanjay Patel Pass *llvm::createVectorCombinePass() {
1155a17f03bdSSanjay Patel   return new VectorCombineLegacyPass();
1156a17f03bdSSanjay Patel }
1157a17f03bdSSanjay Patel 
1158a17f03bdSSanjay Patel PreservedAnalyses VectorCombinePass::run(Function &F,
1159a17f03bdSSanjay Patel                                          FunctionAnalysisManager &FAM) {
1160575e2affSFlorian Hahn   auto &AC = FAM.getResult<AssumptionAnalysis>(F);
1161a17f03bdSSanjay Patel   TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(F);
1162a17f03bdSSanjay Patel   DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F);
11632db4979cSQiu Chaofan   AAResults &AA = FAM.getResult<AAManager>(F);
1164575e2affSFlorian Hahn   VectorCombine Combiner(F, TTI, DT, AA, AC);
11656bdd531aSSanjay Patel   if (!Combiner.run())
1166a17f03bdSSanjay Patel     return PreservedAnalyses::all();
1167a17f03bdSSanjay Patel   PreservedAnalyses PA;
1168a17f03bdSSanjay Patel   PA.preserveSet<CFGAnalyses>();
1169a17f03bdSSanjay Patel   return PA;
1170a17f03bdSSanjay Patel }
1171