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