1 //===------- VectorCombine.cpp - Optimize partial vector operations -------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass optimizes scalar/vector interactions using target cost models. The
10 // transforms implemented here may not fit in traditional loop-based or SLP
11 // vectorization passes.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Transforms/Vectorize/VectorCombine.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/Analysis/BasicAliasAnalysis.h"
18 #include "llvm/Analysis/GlobalsModRef.h"
19 #include "llvm/Analysis/Loads.h"
20 #include "llvm/Analysis/TargetTransformInfo.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/Analysis/VectorUtils.h"
23 #include "llvm/IR/Dominators.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/IRBuilder.h"
26 #include "llvm/IR/PatternMatch.h"
27 #include "llvm/InitializePasses.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Transforms/Utils/Local.h"
31 #include "llvm/Transforms/Vectorize.h"
32 
33 using namespace llvm;
34 using namespace llvm::PatternMatch;
35 
36 #define DEBUG_TYPE "vector-combine"
37 STATISTIC(NumVecLoad, "Number of vector loads formed");
38 STATISTIC(NumVecCmp, "Number of vector compares formed");
39 STATISTIC(NumVecBO, "Number of vector binops formed");
40 STATISTIC(NumVecCmpBO, "Number of vector compare + binop formed");
41 STATISTIC(NumShufOfBitcast, "Number of shuffles moved after bitcast");
42 STATISTIC(NumScalarBO, "Number of scalar binops formed");
43 STATISTIC(NumScalarCmp, "Number of scalar compares formed");
44 
45 static cl::opt<bool> DisableVectorCombine(
46     "disable-vector-combine", cl::init(false), cl::Hidden,
47     cl::desc("Disable all vector combine transforms"));
48 
49 static cl::opt<bool> DisableBinopExtractShuffle(
50     "disable-binop-extract-shuffle", cl::init(false), cl::Hidden,
51     cl::desc("Disable binop extract to shuffle transforms"));
52 
53 static const unsigned InvalidIndex = std::numeric_limits<unsigned>::max();
54 
55 namespace {
56 class VectorCombine {
57 public:
58   VectorCombine(Function &F, const TargetTransformInfo &TTI,
59                 const DominatorTree &DT)
60       : F(F), Builder(F.getContext()), TTI(TTI), DT(DT) {}
61 
62   bool run();
63 
64 private:
65   Function &F;
66   IRBuilder<> Builder;
67   const TargetTransformInfo &TTI;
68   const DominatorTree &DT;
69 
70   bool vectorizeLoadInsert(Instruction &I);
71   ExtractElementInst *getShuffleExtract(ExtractElementInst *Ext0,
72                                         ExtractElementInst *Ext1,
73                                         unsigned PreferredExtractIndex) const;
74   bool isExtractExtractCheap(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
75                              unsigned Opcode,
76                              ExtractElementInst *&ConvertToShuffle,
77                              unsigned PreferredExtractIndex);
78   void foldExtExtCmp(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
79                      Instruction &I);
80   void foldExtExtBinop(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
81                        Instruction &I);
82   bool foldExtractExtract(Instruction &I);
83   bool foldBitcastShuf(Instruction &I);
84   bool scalarizeBinopOrCmp(Instruction &I);
85   bool foldExtractedCmps(Instruction &I);
86 };
87 } // namespace
88 
89 static void replaceValue(Value &Old, Value &New) {
90   Old.replaceAllUsesWith(&New);
91   New.takeName(&Old);
92 }
93 
94 bool VectorCombine::vectorizeLoadInsert(Instruction &I) {
95   // Match insert of scalar load.
96   Value *Scalar;
97   if (!match(&I, m_InsertElt(m_Undef(), m_Value(Scalar), m_ZeroInt())))
98     return false;
99   auto *Load = dyn_cast<LoadInst>(Scalar);
100   Type *ScalarTy = Scalar->getType();
101   if (!Load || !Load->isSimple())
102     return false;
103 
104   // TODO: Extend this to match GEP with constant offsets.
105   Value *PtrOp = Load->getPointerOperand()->stripPointerCasts();
106   assert(isa<PointerType>(PtrOp->getType()) && "Expected a pointer type");
107 
108   unsigned VectorSize = TTI.getMinVectorRegisterBitWidth();
109   uint64_t ScalarSize = ScalarTy->getPrimitiveSizeInBits();
110   if (!ScalarSize || !VectorSize || VectorSize % ScalarSize != 0)
111     return false;
112 
113   // Check safety of replacing the scalar load with a larger vector load.
114   unsigned VecNumElts = VectorSize / ScalarSize;
115   auto *VectorTy = VectorType::get(ScalarTy, VecNumElts, false);
116   // TODO: Allow insert/extract subvector if the type does not match.
117   if (VectorTy != I.getType())
118     return false;
119   Align Alignment = Load->getAlign();
120   const DataLayout &DL = I.getModule()->getDataLayout();
121   if (!isSafeToLoadUnconditionally(PtrOp, VectorTy, Alignment, DL, Load, &DT))
122     return false;
123 
124   unsigned AS = Load->getPointerAddressSpace();
125 
126   // Original pattern: insertelt undef, load [free casts of] ScalarPtr, 0
127   int OldCost = TTI.getMemoryOpCost(Instruction::Load, ScalarTy, Alignment, AS);
128   APInt DemandedElts = APInt::getOneBitSet(VecNumElts, 0);
129   OldCost += TTI.getScalarizationOverhead(VectorTy, DemandedElts, true, false);
130 
131   // New pattern: load VecPtr
132   int NewCost = TTI.getMemoryOpCost(Instruction::Load, VectorTy, Alignment, AS);
133 
134   // We can aggressively convert to the vector form because the backend can
135   // invert this transform if it does not result in a performance win.
136   if (OldCost < NewCost)
137     return false;
138 
139   // It is safe and potentially profitable to load a vector directly:
140   // inselt undef, load Scalar, 0 --> load VecPtr
141   IRBuilder<> Builder(Load);
142   Value *CastedPtr = Builder.CreateBitCast(PtrOp, VectorTy->getPointerTo(AS));
143   LoadInst *VecLd = Builder.CreateAlignedLoad(VectorTy, CastedPtr, Alignment);
144   replaceValue(I, *VecLd);
145   ++NumVecLoad;
146   return true;
147 }
148 
149 /// Determine which, if any, of the inputs should be replaced by a shuffle
150 /// followed by extract from a different index.
151 ExtractElementInst *VectorCombine::getShuffleExtract(
152     ExtractElementInst *Ext0, ExtractElementInst *Ext1,
153     unsigned PreferredExtractIndex = InvalidIndex) const {
154   assert(isa<ConstantInt>(Ext0->getIndexOperand()) &&
155          isa<ConstantInt>(Ext1->getIndexOperand()) &&
156          "Expected constant extract indexes");
157 
158   unsigned Index0 = cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue();
159   unsigned Index1 = cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue();
160 
161   // If the extract indexes are identical, no shuffle is needed.
162   if (Index0 == Index1)
163     return nullptr;
164 
165   Type *VecTy = Ext0->getVectorOperand()->getType();
166   assert(VecTy == Ext1->getVectorOperand()->getType() && "Need matching types");
167   int Cost0 = TTI.getVectorInstrCost(Ext0->getOpcode(), VecTy, Index0);
168   int Cost1 = TTI.getVectorInstrCost(Ext1->getOpcode(), VecTy, Index1);
169 
170   // We are extracting from 2 different indexes, so one operand must be shuffled
171   // before performing a vector operation and/or extract. The more expensive
172   // extract will be replaced by a shuffle.
173   if (Cost0 > Cost1)
174     return Ext0;
175   if (Cost1 > Cost0)
176     return Ext1;
177 
178   // If the costs are equal and there is a preferred extract index, shuffle the
179   // opposite operand.
180   if (PreferredExtractIndex == Index0)
181     return Ext1;
182   if (PreferredExtractIndex == Index1)
183     return Ext0;
184 
185   // Otherwise, replace the extract with the higher index.
186   return Index0 > Index1 ? Ext0 : Ext1;
187 }
188 
189 /// Compare the relative costs of 2 extracts followed by scalar operation vs.
190 /// vector operation(s) followed by extract. Return true if the existing
191 /// instructions are cheaper than a vector alternative. Otherwise, return false
192 /// and if one of the extracts should be transformed to a shufflevector, set
193 /// \p ConvertToShuffle to that extract instruction.
194 bool VectorCombine::isExtractExtractCheap(ExtractElementInst *Ext0,
195                                           ExtractElementInst *Ext1,
196                                           unsigned Opcode,
197                                           ExtractElementInst *&ConvertToShuffle,
198                                           unsigned PreferredExtractIndex) {
199   assert(isa<ConstantInt>(Ext0->getOperand(1)) &&
200          isa<ConstantInt>(Ext1->getOperand(1)) &&
201          "Expected constant extract indexes");
202   Type *ScalarTy = Ext0->getType();
203   auto *VecTy = cast<VectorType>(Ext0->getOperand(0)->getType());
204   int ScalarOpCost, VectorOpCost;
205 
206   // Get cost estimates for scalar and vector versions of the operation.
207   bool IsBinOp = Instruction::isBinaryOp(Opcode);
208   if (IsBinOp) {
209     ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
210     VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
211   } else {
212     assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
213            "Expected a compare");
214     ScalarOpCost = TTI.getCmpSelInstrCost(Opcode, ScalarTy,
215                                           CmpInst::makeCmpResultType(ScalarTy));
216     VectorOpCost = TTI.getCmpSelInstrCost(Opcode, VecTy,
217                                           CmpInst::makeCmpResultType(VecTy));
218   }
219 
220   // Get cost estimates for the extract elements. These costs will factor into
221   // both sequences.
222   unsigned Ext0Index = cast<ConstantInt>(Ext0->getOperand(1))->getZExtValue();
223   unsigned Ext1Index = cast<ConstantInt>(Ext1->getOperand(1))->getZExtValue();
224 
225   int Extract0Cost =
226       TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy, Ext0Index);
227   int Extract1Cost =
228       TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy, Ext1Index);
229 
230   // A more expensive extract will always be replaced by a splat shuffle.
231   // For example, if Ext0 is more expensive:
232   // opcode (extelt V0, Ext0), (ext V1, Ext1) -->
233   // extelt (opcode (splat V0, Ext0), V1), Ext1
234   // TODO: Evaluate whether that always results in lowest cost. Alternatively,
235   //       check the cost of creating a broadcast shuffle and shuffling both
236   //       operands to element 0.
237   int CheapExtractCost = std::min(Extract0Cost, Extract1Cost);
238 
239   // Extra uses of the extracts mean that we include those costs in the
240   // vector total because those instructions will not be eliminated.
241   int OldCost, NewCost;
242   if (Ext0->getOperand(0) == Ext1->getOperand(0) && Ext0Index == Ext1Index) {
243     // Handle a special case. If the 2 extracts are identical, adjust the
244     // formulas to account for that. The extra use charge allows for either the
245     // CSE'd pattern or an unoptimized form with identical values:
246     // opcode (extelt V, C), (extelt V, C) --> extelt (opcode V, V), C
247     bool HasUseTax = Ext0 == Ext1 ? !Ext0->hasNUses(2)
248                                   : !Ext0->hasOneUse() || !Ext1->hasOneUse();
249     OldCost = CheapExtractCost + ScalarOpCost;
250     NewCost = VectorOpCost + CheapExtractCost + HasUseTax * CheapExtractCost;
251   } else {
252     // Handle the general case. Each extract is actually a different value:
253     // opcode (extelt V0, C0), (extelt V1, C1) --> extelt (opcode V0, V1), C
254     OldCost = Extract0Cost + Extract1Cost + ScalarOpCost;
255     NewCost = VectorOpCost + CheapExtractCost +
256               !Ext0->hasOneUse() * Extract0Cost +
257               !Ext1->hasOneUse() * Extract1Cost;
258   }
259 
260   ConvertToShuffle = getShuffleExtract(Ext0, Ext1, PreferredExtractIndex);
261   if (ConvertToShuffle) {
262     if (IsBinOp && DisableBinopExtractShuffle)
263       return true;
264 
265     // If we are extracting from 2 different indexes, then one operand must be
266     // shuffled before performing the vector operation. The shuffle mask is
267     // undefined except for 1 lane that is being translated to the remaining
268     // extraction lane. Therefore, it is a splat shuffle. Ex:
269     // ShufMask = { undef, undef, 0, undef }
270     // TODO: The cost model has an option for a "broadcast" shuffle
271     //       (splat-from-element-0), but no option for a more general splat.
272     NewCost +=
273         TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, VecTy);
274   }
275 
276   // Aggressively form a vector op if the cost is equal because the transform
277   // may enable further optimization.
278   // Codegen can reverse this transform (scalarize) if it was not profitable.
279   return OldCost < NewCost;
280 }
281 
282 /// Create a shuffle that translates (shifts) 1 element from the input vector
283 /// to a new element location.
284 static Value *createShiftShuffle(Value *Vec, unsigned OldIndex,
285                                  unsigned NewIndex, IRBuilder<> &Builder) {
286   // The shuffle mask is undefined except for 1 lane that is being translated
287   // to the new element index. Example for OldIndex == 2 and NewIndex == 0:
288   // ShufMask = { 2, undef, undef, undef }
289   auto *VecTy = cast<FixedVectorType>(Vec->getType());
290   SmallVector<int, 32> ShufMask(VecTy->getNumElements(), UndefMaskElem);
291   ShufMask[NewIndex] = OldIndex;
292   Value *Undef = UndefValue::get(VecTy);
293   return Builder.CreateShuffleVector(Vec, Undef, ShufMask, "shift");
294 }
295 
296 /// Given an extract element instruction with constant index operand, shuffle
297 /// the source vector (shift the scalar element) to a NewIndex for extraction.
298 /// Return null if the input can be constant folded, so that we are not creating
299 /// unnecessary instructions.
300 static ExtractElementInst *translateExtract(ExtractElementInst *ExtElt,
301                                             unsigned NewIndex,
302                                             IRBuilder<> &Builder) {
303   // If the extract can be constant-folded, this code is unsimplified. Defer
304   // to other passes to handle that.
305   Value *X = ExtElt->getVectorOperand();
306   Value *C = ExtElt->getIndexOperand();
307   assert(isa<ConstantInt>(C) && "Expected a constant index operand");
308   if (isa<Constant>(X))
309     return nullptr;
310 
311   Value *Shuf = createShiftShuffle(X, cast<ConstantInt>(C)->getZExtValue(),
312                                    NewIndex, Builder);
313   return cast<ExtractElementInst>(Builder.CreateExtractElement(Shuf, NewIndex));
314 }
315 
316 /// Try to reduce extract element costs by converting scalar compares to vector
317 /// compares followed by extract.
318 /// cmp (ext0 V0, C), (ext1 V1, C)
319 void VectorCombine::foldExtExtCmp(ExtractElementInst *Ext0,
320                                   ExtractElementInst *Ext1, Instruction &I) {
321   assert(isa<CmpInst>(&I) && "Expected a compare");
322   assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() ==
323              cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() &&
324          "Expected matching constant extract indexes");
325 
326   // cmp Pred (extelt V0, C), (extelt V1, C) --> extelt (cmp Pred V0, V1), C
327   ++NumVecCmp;
328   CmpInst::Predicate Pred = cast<CmpInst>(&I)->getPredicate();
329   Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand();
330   Value *VecCmp = Builder.CreateCmp(Pred, V0, V1);
331   Value *NewExt = Builder.CreateExtractElement(VecCmp, Ext0->getIndexOperand());
332   replaceValue(I, *NewExt);
333 }
334 
335 /// Try to reduce extract element costs by converting scalar binops to vector
336 /// binops followed by extract.
337 /// bo (ext0 V0, C), (ext1 V1, C)
338 void VectorCombine::foldExtExtBinop(ExtractElementInst *Ext0,
339                                     ExtractElementInst *Ext1, Instruction &I) {
340   assert(isa<BinaryOperator>(&I) && "Expected a binary operator");
341   assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() ==
342              cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() &&
343          "Expected matching constant extract indexes");
344 
345   // bo (extelt V0, C), (extelt V1, C) --> extelt (bo V0, V1), C
346   ++NumVecBO;
347   Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand();
348   Value *VecBO =
349       Builder.CreateBinOp(cast<BinaryOperator>(&I)->getOpcode(), V0, V1);
350 
351   // All IR flags are safe to back-propagate because any potential poison
352   // created in unused vector elements is discarded by the extract.
353   if (auto *VecBOInst = dyn_cast<Instruction>(VecBO))
354     VecBOInst->copyIRFlags(&I);
355 
356   Value *NewExt = Builder.CreateExtractElement(VecBO, Ext0->getIndexOperand());
357   replaceValue(I, *NewExt);
358 }
359 
360 /// Match an instruction with extracted vector operands.
361 bool VectorCombine::foldExtractExtract(Instruction &I) {
362   // It is not safe to transform things like div, urem, etc. because we may
363   // create undefined behavior when executing those on unknown vector elements.
364   if (!isSafeToSpeculativelyExecute(&I))
365     return false;
366 
367   Instruction *I0, *I1;
368   CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
369   if (!match(&I, m_Cmp(Pred, m_Instruction(I0), m_Instruction(I1))) &&
370       !match(&I, m_BinOp(m_Instruction(I0), m_Instruction(I1))))
371     return false;
372 
373   Value *V0, *V1;
374   uint64_t C0, C1;
375   if (!match(I0, m_ExtractElt(m_Value(V0), m_ConstantInt(C0))) ||
376       !match(I1, m_ExtractElt(m_Value(V1), m_ConstantInt(C1))) ||
377       V0->getType() != V1->getType())
378     return false;
379 
380   // If the scalar value 'I' is going to be re-inserted into a vector, then try
381   // to create an extract to that same element. The extract/insert can be
382   // reduced to a "select shuffle".
383   // TODO: If we add a larger pattern match that starts from an insert, this
384   //       probably becomes unnecessary.
385   auto *Ext0 = cast<ExtractElementInst>(I0);
386   auto *Ext1 = cast<ExtractElementInst>(I1);
387   uint64_t InsertIndex = InvalidIndex;
388   if (I.hasOneUse())
389     match(I.user_back(),
390           m_InsertElt(m_Value(), m_Value(), m_ConstantInt(InsertIndex)));
391 
392   ExtractElementInst *ExtractToChange;
393   if (isExtractExtractCheap(Ext0, Ext1, I.getOpcode(), ExtractToChange,
394                             InsertIndex))
395     return false;
396 
397   if (ExtractToChange) {
398     unsigned CheapExtractIdx = ExtractToChange == Ext0 ? C1 : C0;
399     ExtractElementInst *NewExtract =
400         translateExtract(ExtractToChange, CheapExtractIdx, Builder);
401     if (!NewExtract)
402       return false;
403     if (ExtractToChange == Ext0)
404       Ext0 = NewExtract;
405     else
406       Ext1 = NewExtract;
407   }
408 
409   if (Pred != CmpInst::BAD_ICMP_PREDICATE)
410     foldExtExtCmp(Ext0, Ext1, I);
411   else
412     foldExtExtBinop(Ext0, Ext1, I);
413 
414   return true;
415 }
416 
417 /// If this is a bitcast of a shuffle, try to bitcast the source vector to the
418 /// destination type followed by shuffle. This can enable further transforms by
419 /// moving bitcasts or shuffles together.
420 bool VectorCombine::foldBitcastShuf(Instruction &I) {
421   Value *V;
422   ArrayRef<int> Mask;
423   if (!match(&I, m_BitCast(
424                      m_OneUse(m_Shuffle(m_Value(V), m_Undef(), m_Mask(Mask))))))
425     return false;
426 
427   // Disallow non-vector casts and length-changing shuffles.
428   // TODO: We could allow any shuffle.
429   auto *DestTy = dyn_cast<VectorType>(I.getType());
430   auto *SrcTy = cast<VectorType>(V->getType());
431   if (!DestTy || I.getOperand(0)->getType() != SrcTy)
432     return false;
433 
434   // The new shuffle must not cost more than the old shuffle. The bitcast is
435   // moved ahead of the shuffle, so assume that it has the same cost as before.
436   if (TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, DestTy) >
437       TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, SrcTy))
438     return false;
439 
440   // FIXME: it should be possible to implement the computation of the widened
441   // shuffle mask in terms of ElementCount to work with scalable shuffles.
442   unsigned DestNumElts = cast<FixedVectorType>(DestTy)->getNumElements();
443   unsigned SrcNumElts = cast<FixedVectorType>(SrcTy)->getNumElements();
444   SmallVector<int, 16> NewMask;
445   if (SrcNumElts <= DestNumElts) {
446     // The bitcast is from wide to narrow/equal elements. The shuffle mask can
447     // always be expanded to the equivalent form choosing narrower elements.
448     assert(DestNumElts % SrcNumElts == 0 && "Unexpected shuffle mask");
449     unsigned ScaleFactor = DestNumElts / SrcNumElts;
450     narrowShuffleMaskElts(ScaleFactor, Mask, NewMask);
451   } else {
452     // The bitcast is from narrow elements to wide elements. The shuffle mask
453     // must choose consecutive elements to allow casting first.
454     assert(SrcNumElts % DestNumElts == 0 && "Unexpected shuffle mask");
455     unsigned ScaleFactor = SrcNumElts / DestNumElts;
456     if (!widenShuffleMaskElts(ScaleFactor, Mask, NewMask))
457       return false;
458   }
459   // bitcast (shuf V, MaskC) --> shuf (bitcast V), MaskC'
460   ++NumShufOfBitcast;
461   Value *CastV = Builder.CreateBitCast(V, DestTy);
462   Value *Shuf =
463       Builder.CreateShuffleVector(CastV, UndefValue::get(DestTy), NewMask);
464   replaceValue(I, *Shuf);
465   return true;
466 }
467 
468 /// Match a vector binop or compare instruction with at least one inserted
469 /// scalar operand and convert to scalar binop/cmp followed by insertelement.
470 bool VectorCombine::scalarizeBinopOrCmp(Instruction &I) {
471   CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
472   Value *Ins0, *Ins1;
473   if (!match(&I, m_BinOp(m_Value(Ins0), m_Value(Ins1))) &&
474       !match(&I, m_Cmp(Pred, m_Value(Ins0), m_Value(Ins1))))
475     return false;
476 
477   // Do not convert the vector condition of a vector select into a scalar
478   // condition. That may cause problems for codegen because of differences in
479   // boolean formats and register-file transfers.
480   // TODO: Can we account for that in the cost model?
481   bool IsCmp = Pred != CmpInst::Predicate::BAD_ICMP_PREDICATE;
482   if (IsCmp)
483     for (User *U : I.users())
484       if (match(U, m_Select(m_Specific(&I), m_Value(), m_Value())))
485         return false;
486 
487   // Match against one or both scalar values being inserted into constant
488   // vectors:
489   // vec_op VecC0, (inselt VecC1, V1, Index)
490   // vec_op (inselt VecC0, V0, Index), VecC1
491   // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index)
492   // TODO: Deal with mismatched index constants and variable indexes?
493   Constant *VecC0 = nullptr, *VecC1 = nullptr;
494   Value *V0 = nullptr, *V1 = nullptr;
495   uint64_t Index0 = 0, Index1 = 0;
496   if (!match(Ins0, m_InsertElt(m_Constant(VecC0), m_Value(V0),
497                                m_ConstantInt(Index0))) &&
498       !match(Ins0, m_Constant(VecC0)))
499     return false;
500   if (!match(Ins1, m_InsertElt(m_Constant(VecC1), m_Value(V1),
501                                m_ConstantInt(Index1))) &&
502       !match(Ins1, m_Constant(VecC1)))
503     return false;
504 
505   bool IsConst0 = !V0;
506   bool IsConst1 = !V1;
507   if (IsConst0 && IsConst1)
508     return false;
509   if (!IsConst0 && !IsConst1 && Index0 != Index1)
510     return false;
511 
512   // Bail for single insertion if it is a load.
513   // TODO: Handle this once getVectorInstrCost can cost for load/stores.
514   auto *I0 = dyn_cast_or_null<Instruction>(V0);
515   auto *I1 = dyn_cast_or_null<Instruction>(V1);
516   if ((IsConst0 && I1 && I1->mayReadFromMemory()) ||
517       (IsConst1 && I0 && I0->mayReadFromMemory()))
518     return false;
519 
520   uint64_t Index = IsConst0 ? Index1 : Index0;
521   Type *ScalarTy = IsConst0 ? V1->getType() : V0->getType();
522   Type *VecTy = I.getType();
523   assert(VecTy->isVectorTy() &&
524          (IsConst0 || IsConst1 || V0->getType() == V1->getType()) &&
525          (ScalarTy->isIntegerTy() || ScalarTy->isFloatingPointTy() ||
526           ScalarTy->isPointerTy()) &&
527          "Unexpected types for insert element into binop or cmp");
528 
529   unsigned Opcode = I.getOpcode();
530   int ScalarOpCost, VectorOpCost;
531   if (IsCmp) {
532     ScalarOpCost = TTI.getCmpSelInstrCost(Opcode, ScalarTy);
533     VectorOpCost = TTI.getCmpSelInstrCost(Opcode, VecTy);
534   } else {
535     ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
536     VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
537   }
538 
539   // Get cost estimate for the insert element. This cost will factor into
540   // both sequences.
541   int InsertCost =
542       TTI.getVectorInstrCost(Instruction::InsertElement, VecTy, Index);
543   int OldCost = (IsConst0 ? 0 : InsertCost) + (IsConst1 ? 0 : InsertCost) +
544                 VectorOpCost;
545   int NewCost = ScalarOpCost + InsertCost +
546                 (IsConst0 ? 0 : !Ins0->hasOneUse() * InsertCost) +
547                 (IsConst1 ? 0 : !Ins1->hasOneUse() * InsertCost);
548 
549   // We want to scalarize unless the vector variant actually has lower cost.
550   if (OldCost < NewCost)
551     return false;
552 
553   // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index) -->
554   // inselt NewVecC, (scalar_op V0, V1), Index
555   if (IsCmp)
556     ++NumScalarCmp;
557   else
558     ++NumScalarBO;
559 
560   // For constant cases, extract the scalar element, this should constant fold.
561   if (IsConst0)
562     V0 = ConstantExpr::getExtractElement(VecC0, Builder.getInt64(Index));
563   if (IsConst1)
564     V1 = ConstantExpr::getExtractElement(VecC1, Builder.getInt64(Index));
565 
566   Value *Scalar =
567       IsCmp ? Builder.CreateCmp(Pred, V0, V1)
568             : Builder.CreateBinOp((Instruction::BinaryOps)Opcode, V0, V1);
569 
570   Scalar->setName(I.getName() + ".scalar");
571 
572   // All IR flags are safe to back-propagate. There is no potential for extra
573   // poison to be created by the scalar instruction.
574   if (auto *ScalarInst = dyn_cast<Instruction>(Scalar))
575     ScalarInst->copyIRFlags(&I);
576 
577   // Fold the vector constants in the original vectors into a new base vector.
578   Constant *NewVecC = IsCmp ? ConstantExpr::getCompare(Pred, VecC0, VecC1)
579                             : ConstantExpr::get(Opcode, VecC0, VecC1);
580   Value *Insert = Builder.CreateInsertElement(NewVecC, Scalar, Index);
581   replaceValue(I, *Insert);
582   return true;
583 }
584 
585 /// Try to combine a scalar binop + 2 scalar compares of extracted elements of
586 /// a vector into vector operations followed by extract. Note: The SLP pass
587 /// may miss this pattern because of implementation problems.
588 bool VectorCombine::foldExtractedCmps(Instruction &I) {
589   // We are looking for a scalar binop of booleans.
590   // binop i1 (cmp Pred I0, C0), (cmp Pred I1, C1)
591   if (!I.isBinaryOp() || !I.getType()->isIntegerTy(1))
592     return false;
593 
594   // The compare predicates should match, and each compare should have a
595   // constant operand.
596   // TODO: Relax the one-use constraints.
597   Value *B0 = I.getOperand(0), *B1 = I.getOperand(1);
598   Instruction *I0, *I1;
599   Constant *C0, *C1;
600   CmpInst::Predicate P0, P1;
601   if (!match(B0, m_OneUse(m_Cmp(P0, m_Instruction(I0), m_Constant(C0)))) ||
602       !match(B1, m_OneUse(m_Cmp(P1, m_Instruction(I1), m_Constant(C1)))) ||
603       P0 != P1)
604     return false;
605 
606   // The compare operands must be extracts of the same vector with constant
607   // extract indexes.
608   // TODO: Relax the one-use constraints.
609   Value *X;
610   uint64_t Index0, Index1;
611   if (!match(I0, m_OneUse(m_ExtractElt(m_Value(X), m_ConstantInt(Index0)))) ||
612       !match(I1, m_OneUse(m_ExtractElt(m_Specific(X), m_ConstantInt(Index1)))))
613     return false;
614 
615   auto *Ext0 = cast<ExtractElementInst>(I0);
616   auto *Ext1 = cast<ExtractElementInst>(I1);
617   ExtractElementInst *ConvertToShuf = getShuffleExtract(Ext0, Ext1);
618   if (!ConvertToShuf)
619     return false;
620 
621   // The original scalar pattern is:
622   // binop i1 (cmp Pred (ext X, Index0), C0), (cmp Pred (ext X, Index1), C1)
623   CmpInst::Predicate Pred = P0;
624   unsigned CmpOpcode = CmpInst::isFPPredicate(Pred) ? Instruction::FCmp
625                                                     : Instruction::ICmp;
626   auto *VecTy = dyn_cast<FixedVectorType>(X->getType());
627   if (!VecTy)
628     return false;
629 
630   int OldCost = TTI.getVectorInstrCost(Ext0->getOpcode(), VecTy, Index0);
631   OldCost += TTI.getVectorInstrCost(Ext1->getOpcode(), VecTy, Index1);
632   OldCost += TTI.getCmpSelInstrCost(CmpOpcode, I0->getType()) * 2;
633   OldCost += TTI.getArithmeticInstrCost(I.getOpcode(), I.getType());
634 
635   // The proposed vector pattern is:
636   // vcmp = cmp Pred X, VecC
637   // ext (binop vNi1 vcmp, (shuffle vcmp, Index1)), Index0
638   int CheapIndex = ConvertToShuf == Ext0 ? Index1 : Index0;
639   int ExpensiveIndex = ConvertToShuf == Ext0 ? Index0 : Index1;
640   auto *CmpTy = cast<FixedVectorType>(CmpInst::makeCmpResultType(X->getType()));
641   int NewCost = TTI.getCmpSelInstrCost(CmpOpcode, X->getType());
642   NewCost +=
643       TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, CmpTy);
644   NewCost += TTI.getArithmeticInstrCost(I.getOpcode(), CmpTy);
645   NewCost += TTI.getVectorInstrCost(Ext0->getOpcode(), CmpTy, CheapIndex);
646 
647   // Aggressively form vector ops if the cost is equal because the transform
648   // may enable further optimization.
649   // Codegen can reverse this transform (scalarize) if it was not profitable.
650   if (OldCost < NewCost)
651     return false;
652 
653   // Create a vector constant from the 2 scalar constants.
654   SmallVector<Constant *, 32> CmpC(VecTy->getNumElements(),
655                                    UndefValue::get(VecTy->getElementType()));
656   CmpC[Index0] = C0;
657   CmpC[Index1] = C1;
658   Value *VCmp = Builder.CreateCmp(Pred, X, ConstantVector::get(CmpC));
659 
660   Value *Shuf = createShiftShuffle(VCmp, ExpensiveIndex, CheapIndex, Builder);
661   Value *VecLogic = Builder.CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
662                                         VCmp, Shuf);
663   Value *NewExt = Builder.CreateExtractElement(VecLogic, CheapIndex);
664   replaceValue(I, *NewExt);
665   ++NumVecCmpBO;
666   return true;
667 }
668 
669 /// This is the entry point for all transforms. Pass manager differences are
670 /// handled in the callers of this function.
671 bool VectorCombine::run() {
672   if (DisableVectorCombine)
673     return false;
674 
675   // Don't attempt vectorization if the target does not support vectors.
676   if (!TTI.getNumberOfRegisters(TTI.getRegisterClassForType(/*Vector*/ true)))
677     return false;
678 
679   bool MadeChange = false;
680   for (BasicBlock &BB : F) {
681     // Ignore unreachable basic blocks.
682     if (!DT.isReachableFromEntry(&BB))
683       continue;
684     // Do not delete instructions under here and invalidate the iterator.
685     // Walk the block forwards to enable simple iterative chains of transforms.
686     // TODO: It could be more efficient to remove dead instructions
687     //       iteratively in this loop rather than waiting until the end.
688     for (Instruction &I : BB) {
689       if (isa<DbgInfoIntrinsic>(I))
690         continue;
691       Builder.SetInsertPoint(&I);
692       MadeChange |= vectorizeLoadInsert(I);
693       MadeChange |= foldExtractExtract(I);
694       MadeChange |= foldBitcastShuf(I);
695       MadeChange |= scalarizeBinopOrCmp(I);
696       MadeChange |= foldExtractedCmps(I);
697     }
698   }
699 
700   // We're done with transforms, so remove dead instructions.
701   if (MadeChange)
702     for (BasicBlock &BB : F)
703       SimplifyInstructionsInBlock(&BB);
704 
705   return MadeChange;
706 }
707 
708 // Pass manager boilerplate below here.
709 
710 namespace {
711 class VectorCombineLegacyPass : public FunctionPass {
712 public:
713   static char ID;
714   VectorCombineLegacyPass() : FunctionPass(ID) {
715     initializeVectorCombineLegacyPassPass(*PassRegistry::getPassRegistry());
716   }
717 
718   void getAnalysisUsage(AnalysisUsage &AU) const override {
719     AU.addRequired<DominatorTreeWrapperPass>();
720     AU.addRequired<TargetTransformInfoWrapperPass>();
721     AU.setPreservesCFG();
722     AU.addPreserved<DominatorTreeWrapperPass>();
723     AU.addPreserved<GlobalsAAWrapperPass>();
724     AU.addPreserved<AAResultsWrapperPass>();
725     AU.addPreserved<BasicAAWrapperPass>();
726     FunctionPass::getAnalysisUsage(AU);
727   }
728 
729   bool runOnFunction(Function &F) override {
730     if (skipFunction(F))
731       return false;
732     auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
733     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
734     VectorCombine Combiner(F, TTI, DT);
735     return Combiner.run();
736   }
737 };
738 } // namespace
739 
740 char VectorCombineLegacyPass::ID = 0;
741 INITIALIZE_PASS_BEGIN(VectorCombineLegacyPass, "vector-combine",
742                       "Optimize scalar/vector ops", false,
743                       false)
744 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
745 INITIALIZE_PASS_END(VectorCombineLegacyPass, "vector-combine",
746                     "Optimize scalar/vector ops", false, false)
747 Pass *llvm::createVectorCombinePass() {
748   return new VectorCombineLegacyPass();
749 }
750 
751 PreservedAnalyses VectorCombinePass::run(Function &F,
752                                          FunctionAnalysisManager &FAM) {
753   TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(F);
754   DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F);
755   VectorCombine Combiner(F, TTI, DT);
756   if (!Combiner.run())
757     return PreservedAnalyses::all();
758   PreservedAnalyses PA;
759   PA.preserveSet<CFGAnalyses>();
760   PA.preserve<GlobalsAA>();
761   PA.preserve<AAManager>();
762   PA.preserve<BasicAA>();
763   return PA;
764 }
765