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   unsigned DestNumElts = DestTy->getNumElements();
441   unsigned SrcNumElts = SrcTy->getNumElements();
442   SmallVector<int, 16> NewMask;
443   if (SrcNumElts <= DestNumElts) {
444     // The bitcast is from wide to narrow/equal elements. The shuffle mask can
445     // always be expanded to the equivalent form choosing narrower elements.
446     assert(DestNumElts % SrcNumElts == 0 && "Unexpected shuffle mask");
447     unsigned ScaleFactor = DestNumElts / SrcNumElts;
448     narrowShuffleMaskElts(ScaleFactor, Mask, NewMask);
449   } else {
450     // The bitcast is from narrow elements to wide elements. The shuffle mask
451     // must choose consecutive elements to allow casting first.
452     assert(SrcNumElts % DestNumElts == 0 && "Unexpected shuffle mask");
453     unsigned ScaleFactor = SrcNumElts / DestNumElts;
454     if (!widenShuffleMaskElts(ScaleFactor, Mask, NewMask))
455       return false;
456   }
457   // bitcast (shuf V, MaskC) --> shuf (bitcast V), MaskC'
458   ++NumShufOfBitcast;
459   Value *CastV = Builder.CreateBitCast(V, DestTy);
460   Value *Shuf =
461       Builder.CreateShuffleVector(CastV, UndefValue::get(DestTy), NewMask);
462   replaceValue(I, *Shuf);
463   return true;
464 }
465 
466 /// Match a vector binop or compare instruction with at least one inserted
467 /// scalar operand and convert to scalar binop/cmp followed by insertelement.
468 bool VectorCombine::scalarizeBinopOrCmp(Instruction &I) {
469   CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
470   Value *Ins0, *Ins1;
471   if (!match(&I, m_BinOp(m_Value(Ins0), m_Value(Ins1))) &&
472       !match(&I, m_Cmp(Pred, m_Value(Ins0), m_Value(Ins1))))
473     return false;
474 
475   // Do not convert the vector condition of a vector select into a scalar
476   // condition. That may cause problems for codegen because of differences in
477   // boolean formats and register-file transfers.
478   // TODO: Can we account for that in the cost model?
479   bool IsCmp = Pred != CmpInst::Predicate::BAD_ICMP_PREDICATE;
480   if (IsCmp)
481     for (User *U : I.users())
482       if (match(U, m_Select(m_Specific(&I), m_Value(), m_Value())))
483         return false;
484 
485   // Match against one or both scalar values being inserted into constant
486   // vectors:
487   // vec_op VecC0, (inselt VecC1, V1, Index)
488   // vec_op (inselt VecC0, V0, Index), VecC1
489   // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index)
490   // TODO: Deal with mismatched index constants and variable indexes?
491   Constant *VecC0 = nullptr, *VecC1 = nullptr;
492   Value *V0 = nullptr, *V1 = nullptr;
493   uint64_t Index0 = 0, Index1 = 0;
494   if (!match(Ins0, m_InsertElt(m_Constant(VecC0), m_Value(V0),
495                                m_ConstantInt(Index0))) &&
496       !match(Ins0, m_Constant(VecC0)))
497     return false;
498   if (!match(Ins1, m_InsertElt(m_Constant(VecC1), m_Value(V1),
499                                m_ConstantInt(Index1))) &&
500       !match(Ins1, m_Constant(VecC1)))
501     return false;
502 
503   bool IsConst0 = !V0;
504   bool IsConst1 = !V1;
505   if (IsConst0 && IsConst1)
506     return false;
507   if (!IsConst0 && !IsConst1 && Index0 != Index1)
508     return false;
509 
510   // Bail for single insertion if it is a load.
511   // TODO: Handle this once getVectorInstrCost can cost for load/stores.
512   auto *I0 = dyn_cast_or_null<Instruction>(V0);
513   auto *I1 = dyn_cast_or_null<Instruction>(V1);
514   if ((IsConst0 && I1 && I1->mayReadFromMemory()) ||
515       (IsConst1 && I0 && I0->mayReadFromMemory()))
516     return false;
517 
518   uint64_t Index = IsConst0 ? Index1 : Index0;
519   Type *ScalarTy = IsConst0 ? V1->getType() : V0->getType();
520   Type *VecTy = I.getType();
521   assert(VecTy->isVectorTy() &&
522          (IsConst0 || IsConst1 || V0->getType() == V1->getType()) &&
523          (ScalarTy->isIntegerTy() || ScalarTy->isFloatingPointTy() ||
524           ScalarTy->isPointerTy()) &&
525          "Unexpected types for insert element into binop or cmp");
526 
527   unsigned Opcode = I.getOpcode();
528   int ScalarOpCost, VectorOpCost;
529   if (IsCmp) {
530     ScalarOpCost = TTI.getCmpSelInstrCost(Opcode, ScalarTy);
531     VectorOpCost = TTI.getCmpSelInstrCost(Opcode, VecTy);
532   } else {
533     ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
534     VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
535   }
536 
537   // Get cost estimate for the insert element. This cost will factor into
538   // both sequences.
539   int InsertCost =
540       TTI.getVectorInstrCost(Instruction::InsertElement, VecTy, Index);
541   int OldCost = (IsConst0 ? 0 : InsertCost) + (IsConst1 ? 0 : InsertCost) +
542                 VectorOpCost;
543   int NewCost = ScalarOpCost + InsertCost +
544                 (IsConst0 ? 0 : !Ins0->hasOneUse() * InsertCost) +
545                 (IsConst1 ? 0 : !Ins1->hasOneUse() * InsertCost);
546 
547   // We want to scalarize unless the vector variant actually has lower cost.
548   if (OldCost < NewCost)
549     return false;
550 
551   // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index) -->
552   // inselt NewVecC, (scalar_op V0, V1), Index
553   if (IsCmp)
554     ++NumScalarCmp;
555   else
556     ++NumScalarBO;
557 
558   // For constant cases, extract the scalar element, this should constant fold.
559   if (IsConst0)
560     V0 = ConstantExpr::getExtractElement(VecC0, Builder.getInt64(Index));
561   if (IsConst1)
562     V1 = ConstantExpr::getExtractElement(VecC1, Builder.getInt64(Index));
563 
564   Value *Scalar =
565       IsCmp ? Builder.CreateCmp(Pred, V0, V1)
566             : Builder.CreateBinOp((Instruction::BinaryOps)Opcode, V0, V1);
567 
568   Scalar->setName(I.getName() + ".scalar");
569 
570   // All IR flags are safe to back-propagate. There is no potential for extra
571   // poison to be created by the scalar instruction.
572   if (auto *ScalarInst = dyn_cast<Instruction>(Scalar))
573     ScalarInst->copyIRFlags(&I);
574 
575   // Fold the vector constants in the original vectors into a new base vector.
576   Constant *NewVecC = IsCmp ? ConstantExpr::getCompare(Pred, VecC0, VecC1)
577                             : ConstantExpr::get(Opcode, VecC0, VecC1);
578   Value *Insert = Builder.CreateInsertElement(NewVecC, Scalar, Index);
579   replaceValue(I, *Insert);
580   return true;
581 }
582 
583 /// Try to combine a scalar binop + 2 scalar compares of extracted elements of
584 /// a vector into vector operations followed by extract. Note: The SLP pass
585 /// may miss this pattern because of implementation problems.
586 bool VectorCombine::foldExtractedCmps(Instruction &I) {
587   // We are looking for a scalar binop of booleans.
588   // binop i1 (cmp Pred I0, C0), (cmp Pred I1, C1)
589   if (!I.isBinaryOp() || !I.getType()->isIntegerTy(1))
590     return false;
591 
592   // The compare predicates should match, and each compare should have a
593   // constant operand.
594   // TODO: Relax the one-use constraints.
595   Value *B0 = I.getOperand(0), *B1 = I.getOperand(1);
596   Instruction *I0, *I1;
597   Constant *C0, *C1;
598   CmpInst::Predicate P0, P1;
599   if (!match(B0, m_OneUse(m_Cmp(P0, m_Instruction(I0), m_Constant(C0)))) ||
600       !match(B1, m_OneUse(m_Cmp(P1, m_Instruction(I1), m_Constant(C1)))) ||
601       P0 != P1)
602     return false;
603 
604   // The compare operands must be extracts of the same vector with constant
605   // extract indexes.
606   // TODO: Relax the one-use constraints.
607   Value *X;
608   uint64_t Index0, Index1;
609   if (!match(I0, m_OneUse(m_ExtractElt(m_Value(X), m_ConstantInt(Index0)))) ||
610       !match(I1, m_OneUse(m_ExtractElt(m_Specific(X), m_ConstantInt(Index1)))))
611     return false;
612 
613   auto *Ext0 = cast<ExtractElementInst>(I0);
614   auto *Ext1 = cast<ExtractElementInst>(I1);
615   ExtractElementInst *ConvertToShuf = getShuffleExtract(Ext0, Ext1);
616   if (!ConvertToShuf)
617     return false;
618 
619   // The original scalar pattern is:
620   // binop i1 (cmp Pred (ext X, Index0), C0), (cmp Pred (ext X, Index1), C1)
621   CmpInst::Predicate Pred = P0;
622   unsigned CmpOpcode = CmpInst::isFPPredicate(Pred) ? Instruction::FCmp
623                                                     : Instruction::ICmp;
624   auto *VecTy = dyn_cast<FixedVectorType>(X->getType());
625   if (!VecTy)
626     return false;
627 
628   int OldCost = TTI.getVectorInstrCost(Ext0->getOpcode(), VecTy, Index0);
629   OldCost += TTI.getVectorInstrCost(Ext1->getOpcode(), VecTy, Index1);
630   OldCost += TTI.getCmpSelInstrCost(CmpOpcode, I0->getType()) * 2;
631   OldCost += TTI.getArithmeticInstrCost(I.getOpcode(), I.getType());
632 
633   // The proposed vector pattern is:
634   // vcmp = cmp Pred X, VecC
635   // ext (binop vNi1 vcmp, (shuffle vcmp, Index1)), Index0
636   int CheapIndex = ConvertToShuf == Ext0 ? Index1 : Index0;
637   int ExpensiveIndex = ConvertToShuf == Ext0 ? Index0 : Index1;
638   auto *CmpTy = cast<FixedVectorType>(CmpInst::makeCmpResultType(X->getType()));
639   int NewCost = TTI.getCmpSelInstrCost(CmpOpcode, X->getType());
640   NewCost +=
641       TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, CmpTy);
642   NewCost += TTI.getArithmeticInstrCost(I.getOpcode(), CmpTy);
643   NewCost += TTI.getVectorInstrCost(Ext0->getOpcode(), CmpTy, CheapIndex);
644 
645   // Aggressively form vector ops if the cost is equal because the transform
646   // may enable further optimization.
647   // Codegen can reverse this transform (scalarize) if it was not profitable.
648   if (OldCost < NewCost)
649     return false;
650 
651   // Create a vector constant from the 2 scalar constants.
652   SmallVector<Constant *, 32> CmpC(VecTy->getNumElements(),
653                                    UndefValue::get(VecTy->getElementType()));
654   CmpC[Index0] = C0;
655   CmpC[Index1] = C1;
656   Value *VCmp = Builder.CreateCmp(Pred, X, ConstantVector::get(CmpC));
657 
658   Value *Shuf = createShiftShuffle(VCmp, ExpensiveIndex, CheapIndex, Builder);
659   Value *VecLogic = Builder.CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
660                                         VCmp, Shuf);
661   Value *NewExt = Builder.CreateExtractElement(VecLogic, CheapIndex);
662   replaceValue(I, *NewExt);
663   ++NumVecCmpBO;
664   return true;
665 }
666 
667 /// This is the entry point for all transforms. Pass manager differences are
668 /// handled in the callers of this function.
669 bool VectorCombine::run() {
670   if (DisableVectorCombine)
671     return false;
672 
673   // Don't attempt vectorization if the target does not support vectors.
674   if (!TTI.getNumberOfRegisters(TTI.getRegisterClassForType(/*Vector*/ true)))
675     return false;
676 
677   bool MadeChange = false;
678   for (BasicBlock &BB : F) {
679     // Ignore unreachable basic blocks.
680     if (!DT.isReachableFromEntry(&BB))
681       continue;
682     // Do not delete instructions under here and invalidate the iterator.
683     // Walk the block forwards to enable simple iterative chains of transforms.
684     // TODO: It could be more efficient to remove dead instructions
685     //       iteratively in this loop rather than waiting until the end.
686     for (Instruction &I : BB) {
687       if (isa<DbgInfoIntrinsic>(I))
688         continue;
689       Builder.SetInsertPoint(&I);
690       MadeChange |= vectorizeLoadInsert(I);
691       MadeChange |= foldExtractExtract(I);
692       MadeChange |= foldBitcastShuf(I);
693       MadeChange |= scalarizeBinopOrCmp(I);
694       MadeChange |= foldExtractedCmps(I);
695     }
696   }
697 
698   // We're done with transforms, so remove dead instructions.
699   if (MadeChange)
700     for (BasicBlock &BB : F)
701       SimplifyInstructionsInBlock(&BB);
702 
703   return MadeChange;
704 }
705 
706 // Pass manager boilerplate below here.
707 
708 namespace {
709 class VectorCombineLegacyPass : public FunctionPass {
710 public:
711   static char ID;
712   VectorCombineLegacyPass() : FunctionPass(ID) {
713     initializeVectorCombineLegacyPassPass(*PassRegistry::getPassRegistry());
714   }
715 
716   void getAnalysisUsage(AnalysisUsage &AU) const override {
717     AU.addRequired<DominatorTreeWrapperPass>();
718     AU.addRequired<TargetTransformInfoWrapperPass>();
719     AU.setPreservesCFG();
720     AU.addPreserved<DominatorTreeWrapperPass>();
721     AU.addPreserved<GlobalsAAWrapperPass>();
722     AU.addPreserved<AAResultsWrapperPass>();
723     AU.addPreserved<BasicAAWrapperPass>();
724     FunctionPass::getAnalysisUsage(AU);
725   }
726 
727   bool runOnFunction(Function &F) override {
728     if (skipFunction(F))
729       return false;
730     auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
731     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
732     VectorCombine Combiner(F, TTI, DT);
733     return Combiner.run();
734   }
735 };
736 } // namespace
737 
738 char VectorCombineLegacyPass::ID = 0;
739 INITIALIZE_PASS_BEGIN(VectorCombineLegacyPass, "vector-combine",
740                       "Optimize scalar/vector ops", false,
741                       false)
742 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
743 INITIALIZE_PASS_END(VectorCombineLegacyPass, "vector-combine",
744                     "Optimize scalar/vector ops", false, false)
745 Pass *llvm::createVectorCombinePass() {
746   return new VectorCombineLegacyPass();
747 }
748 
749 PreservedAnalyses VectorCombinePass::run(Function &F,
750                                          FunctionAnalysisManager &FAM) {
751   TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(F);
752   DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F);
753   VectorCombine Combiner(F, TTI, DT);
754   if (!Combiner.run())
755     return PreservedAnalyses::all();
756   PreservedAnalyses PA;
757   PA.preserveSet<CFGAnalyses>();
758   PA.preserve<GlobalsAA>();
759   PA.preserve<AAManager>();
760   PA.preserve<BasicAA>();
761   return PA;
762 }
763