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