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