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/SmallBitVector.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/Analysis/AssumptionCache.h"
19 #include "llvm/Analysis/BasicAliasAnalysis.h"
20 #include "llvm/Analysis/GlobalsModRef.h"
21 #include "llvm/Analysis/Loads.h"
22 #include "llvm/Analysis/TargetTransformInfo.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/Analysis/VectorUtils.h"
25 #include "llvm/IR/Dominators.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/IRBuilder.h"
28 #include "llvm/IR/PatternMatch.h"
29 #include "llvm/InitializePasses.h"
30 #include "llvm/Pass.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Transforms/Utils/Local.h"
33 #include "llvm/Transforms/Vectorize.h"
34 
35 #define DEBUG_TYPE "vector-combine"
36 #include "llvm/Transforms/Utils/InstructionWorklist.h"
37 
38 using namespace llvm;
39 using namespace llvm::PatternMatch;
40 
41 STATISTIC(NumVecLoad, "Number of vector loads formed");
42 STATISTIC(NumVecCmp, "Number of vector compares formed");
43 STATISTIC(NumVecBO, "Number of vector binops formed");
44 STATISTIC(NumVecCmpBO, "Number of vector compare + binop formed");
45 STATISTIC(NumShufOfBitcast, "Number of shuffles moved after bitcast");
46 STATISTIC(NumScalarBO, "Number of scalar binops formed");
47 STATISTIC(NumScalarCmp, "Number of scalar compares formed");
48 
49 static cl::opt<bool> DisableVectorCombine(
50     "disable-vector-combine", cl::init(false), cl::Hidden,
51     cl::desc("Disable all vector combine transforms"));
52 
53 static cl::opt<bool> DisableBinopExtractShuffle(
54     "disable-binop-extract-shuffle", cl::init(false), cl::Hidden,
55     cl::desc("Disable binop extract to shuffle transforms"));
56 
57 static cl::opt<unsigned> MaxInstrsToScan(
58     "vector-combine-max-scan-instrs", cl::init(30), cl::Hidden,
59     cl::desc("Max number of instructions to scan for vector combining."));
60 
61 static const unsigned InvalidIndex = std::numeric_limits<unsigned>::max();
62 
63 namespace {
64 class VectorCombine {
65 public:
66   VectorCombine(Function &F, const TargetTransformInfo &TTI,
67                 const DominatorTree &DT, AAResults &AA, AssumptionCache &AC,
68                 bool ScalarizationOnly)
69       : F(F), Builder(F.getContext()), TTI(TTI), DT(DT), AA(AA), AC(AC),
70         ScalarizationOnly(ScalarizationOnly) {}
71 
72   bool run();
73 
74 private:
75   Function &F;
76   IRBuilder<> Builder;
77   const TargetTransformInfo &TTI;
78   const DominatorTree &DT;
79   AAResults &AA;
80   AssumptionCache &AC;
81 
82   /// If true only perform scalarization combines and do not introduce new
83   /// vector operations.
84   bool ScalarizationOnly;
85 
86   InstructionWorklist Worklist;
87 
88   bool vectorizeLoadInsert(Instruction &I);
89   ExtractElementInst *getShuffleExtract(ExtractElementInst *Ext0,
90                                         ExtractElementInst *Ext1,
91                                         unsigned PreferredExtractIndex) const;
92   bool isExtractExtractCheap(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
93                              const Instruction &I,
94                              ExtractElementInst *&ConvertToShuffle,
95                              unsigned PreferredExtractIndex);
96   void foldExtExtCmp(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
97                      Instruction &I);
98   void foldExtExtBinop(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
99                        Instruction &I);
100   bool foldExtractExtract(Instruction &I);
101   bool foldBitcastShuf(Instruction &I);
102   bool scalarizeBinopOrCmp(Instruction &I);
103   bool foldExtractedCmps(Instruction &I);
104   bool foldSingleElementStore(Instruction &I);
105   bool scalarizeLoadExtract(Instruction &I);
106   bool foldShuffleOfBinops(Instruction &I);
107   bool foldShuffleFromReductions(Instruction &I);
108 
109   void replaceValue(Value &Old, Value &New) {
110     Old.replaceAllUsesWith(&New);
111     if (auto *NewI = dyn_cast<Instruction>(&New)) {
112       New.takeName(&Old);
113       Worklist.pushUsersToWorkList(*NewI);
114       Worklist.pushValue(NewI);
115     }
116     Worklist.pushValue(&Old);
117   }
118 
119   void eraseInstruction(Instruction &I) {
120     for (Value *Op : I.operands())
121       Worklist.pushValue(Op);
122     Worklist.remove(&I);
123     I.eraseFromParent();
124   }
125 };
126 } // namespace
127 
128 bool VectorCombine::vectorizeLoadInsert(Instruction &I) {
129   // Match insert into fixed vector of scalar value.
130   // TODO: Handle non-zero insert index.
131   auto *Ty = dyn_cast<FixedVectorType>(I.getType());
132   Value *Scalar;
133   if (!Ty || !match(&I, m_InsertElt(m_Undef(), m_Value(Scalar), m_ZeroInt())) ||
134       !Scalar->hasOneUse())
135     return false;
136 
137   // Optionally match an extract from another vector.
138   Value *X;
139   bool HasExtract = match(Scalar, m_ExtractElt(m_Value(X), m_ZeroInt()));
140   if (!HasExtract)
141     X = Scalar;
142 
143   // Match source value as load of scalar or vector.
144   // Do not vectorize scalar load (widening) if atomic/volatile or under
145   // asan/hwasan/memtag/tsan. The widened load may load data from dirty regions
146   // or create data races non-existent in the source.
147   auto *Load = dyn_cast<LoadInst>(X);
148   if (!Load || !Load->isSimple() || !Load->hasOneUse() ||
149       Load->getFunction()->hasFnAttribute(Attribute::SanitizeMemTag) ||
150       mustSuppressSpeculation(*Load))
151     return false;
152 
153   const DataLayout &DL = I.getModule()->getDataLayout();
154   Value *SrcPtr = Load->getPointerOperand()->stripPointerCasts();
155   assert(isa<PointerType>(SrcPtr->getType()) && "Expected a pointer type");
156 
157   unsigned AS = Load->getPointerAddressSpace();
158 
159   // We are potentially transforming byte-sized (8-bit) memory accesses, so make
160   // sure we have all of our type-based constraints in place for this target.
161   Type *ScalarTy = Scalar->getType();
162   uint64_t ScalarSize = ScalarTy->getPrimitiveSizeInBits();
163   unsigned MinVectorSize = TTI.getMinVectorRegisterBitWidth();
164   if (!ScalarSize || !MinVectorSize || MinVectorSize % ScalarSize != 0 ||
165       ScalarSize % 8 != 0)
166     return false;
167 
168   // Check safety of replacing the scalar load with a larger vector load.
169   // We use minimal alignment (maximum flexibility) because we only care about
170   // the dereferenceable region. When calculating cost and creating a new op,
171   // we may use a larger value based on alignment attributes.
172   unsigned MinVecNumElts = MinVectorSize / ScalarSize;
173   auto *MinVecTy = VectorType::get(ScalarTy, MinVecNumElts, false);
174   unsigned OffsetEltIndex = 0;
175   Align Alignment = Load->getAlign();
176   if (!isSafeToLoadUnconditionally(SrcPtr, MinVecTy, Align(1), DL, Load, &DT)) {
177     // It is not safe to load directly from the pointer, but we can still peek
178     // through gep offsets and check if it safe to load from a base address with
179     // updated alignment. If it is, we can shuffle the element(s) into place
180     // after loading.
181     unsigned OffsetBitWidth = DL.getIndexTypeSizeInBits(SrcPtr->getType());
182     APInt Offset(OffsetBitWidth, 0);
183     SrcPtr = SrcPtr->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
184 
185     // We want to shuffle the result down from a high element of a vector, so
186     // the offset must be positive.
187     if (Offset.isNegative())
188       return false;
189 
190     // The offset must be a multiple of the scalar element to shuffle cleanly
191     // in the element's size.
192     uint64_t ScalarSizeInBytes = ScalarSize / 8;
193     if (Offset.urem(ScalarSizeInBytes) != 0)
194       return false;
195 
196     // If we load MinVecNumElts, will our target element still be loaded?
197     OffsetEltIndex = Offset.udiv(ScalarSizeInBytes).getZExtValue();
198     if (OffsetEltIndex >= MinVecNumElts)
199       return false;
200 
201     if (!isSafeToLoadUnconditionally(SrcPtr, MinVecTy, Align(1), DL, Load, &DT))
202       return false;
203 
204     // Update alignment with offset value. Note that the offset could be negated
205     // to more accurately represent "(new) SrcPtr - Offset = (old) SrcPtr", but
206     // negation does not change the result of the alignment calculation.
207     Alignment = commonAlignment(Alignment, Offset.getZExtValue());
208   }
209 
210   // Original pattern: insertelt undef, load [free casts of] PtrOp, 0
211   // Use the greater of the alignment on the load or its source pointer.
212   Alignment = std::max(SrcPtr->getPointerAlignment(DL), Alignment);
213   Type *LoadTy = Load->getType();
214   InstructionCost OldCost =
215       TTI.getMemoryOpCost(Instruction::Load, LoadTy, Alignment, AS);
216   APInt DemandedElts = APInt::getOneBitSet(MinVecNumElts, 0);
217   OldCost += TTI.getScalarizationOverhead(MinVecTy, DemandedElts,
218                                           /* Insert */ true, HasExtract);
219 
220   // New pattern: load VecPtr
221   InstructionCost NewCost =
222       TTI.getMemoryOpCost(Instruction::Load, MinVecTy, Alignment, AS);
223   // Optionally, we are shuffling the loaded vector element(s) into place.
224   // For the mask set everything but element 0 to undef to prevent poison from
225   // propagating from the extra loaded memory. This will also optionally
226   // shrink/grow the vector from the loaded size to the output size.
227   // We assume this operation has no cost in codegen if there was no offset.
228   // Note that we could use freeze to avoid poison problems, but then we might
229   // still need a shuffle to change the vector size.
230   unsigned OutputNumElts = Ty->getNumElements();
231   SmallVector<int, 16> Mask(OutputNumElts, UndefMaskElem);
232   assert(OffsetEltIndex < MinVecNumElts && "Address offset too big");
233   Mask[0] = OffsetEltIndex;
234   if (OffsetEltIndex)
235     NewCost += TTI.getShuffleCost(TTI::SK_PermuteSingleSrc, MinVecTy, Mask);
236 
237   // We can aggressively convert to the vector form because the backend can
238   // invert this transform if it does not result in a performance win.
239   if (OldCost < NewCost || !NewCost.isValid())
240     return false;
241 
242   // It is safe and potentially profitable to load a vector directly:
243   // inselt undef, load Scalar, 0 --> load VecPtr
244   IRBuilder<> Builder(Load);
245   Value *CastedPtr = Builder.CreatePointerBitCastOrAddrSpaceCast(
246       SrcPtr, MinVecTy->getPointerTo(AS));
247   Value *VecLd = Builder.CreateAlignedLoad(MinVecTy, CastedPtr, Alignment);
248   VecLd = Builder.CreateShuffleVector(VecLd, Mask);
249 
250   replaceValue(I, *VecLd);
251   ++NumVecLoad;
252   return true;
253 }
254 
255 /// Determine which, if any, of the inputs should be replaced by a shuffle
256 /// followed by extract from a different index.
257 ExtractElementInst *VectorCombine::getShuffleExtract(
258     ExtractElementInst *Ext0, ExtractElementInst *Ext1,
259     unsigned PreferredExtractIndex = InvalidIndex) const {
260   assert(isa<ConstantInt>(Ext0->getIndexOperand()) &&
261          isa<ConstantInt>(Ext1->getIndexOperand()) &&
262          "Expected constant extract indexes");
263 
264   unsigned Index0 = cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue();
265   unsigned Index1 = cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue();
266 
267   // If the extract indexes are identical, no shuffle is needed.
268   if (Index0 == Index1)
269     return nullptr;
270 
271   Type *VecTy = Ext0->getVectorOperand()->getType();
272   assert(VecTy == Ext1->getVectorOperand()->getType() && "Need matching types");
273   InstructionCost Cost0 =
274       TTI.getVectorInstrCost(Ext0->getOpcode(), VecTy, Index0);
275   InstructionCost Cost1 =
276       TTI.getVectorInstrCost(Ext1->getOpcode(), VecTy, Index1);
277 
278   // If both costs are invalid no shuffle is needed
279   if (!Cost0.isValid() && !Cost1.isValid())
280     return nullptr;
281 
282   // We are extracting from 2 different indexes, so one operand must be shuffled
283   // before performing a vector operation and/or extract. The more expensive
284   // extract will be replaced by a shuffle.
285   if (Cost0 > Cost1)
286     return Ext0;
287   if (Cost1 > Cost0)
288     return Ext1;
289 
290   // If the costs are equal and there is a preferred extract index, shuffle the
291   // opposite operand.
292   if (PreferredExtractIndex == Index0)
293     return Ext1;
294   if (PreferredExtractIndex == Index1)
295     return Ext0;
296 
297   // Otherwise, replace the extract with the higher index.
298   return Index0 > Index1 ? Ext0 : Ext1;
299 }
300 
301 /// Compare the relative costs of 2 extracts followed by scalar operation vs.
302 /// vector operation(s) followed by extract. Return true if the existing
303 /// instructions are cheaper than a vector alternative. Otherwise, return false
304 /// and if one of the extracts should be transformed to a shufflevector, set
305 /// \p ConvertToShuffle to that extract instruction.
306 bool VectorCombine::isExtractExtractCheap(ExtractElementInst *Ext0,
307                                           ExtractElementInst *Ext1,
308                                           const Instruction &I,
309                                           ExtractElementInst *&ConvertToShuffle,
310                                           unsigned PreferredExtractIndex) {
311   assert(isa<ConstantInt>(Ext0->getOperand(1)) &&
312          isa<ConstantInt>(Ext1->getOperand(1)) &&
313          "Expected constant extract indexes");
314   unsigned Opcode = I.getOpcode();
315   Type *ScalarTy = Ext0->getType();
316   auto *VecTy = cast<VectorType>(Ext0->getOperand(0)->getType());
317   InstructionCost ScalarOpCost, VectorOpCost;
318 
319   // Get cost estimates for scalar and vector versions of the operation.
320   bool IsBinOp = Instruction::isBinaryOp(Opcode);
321   if (IsBinOp) {
322     ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
323     VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
324   } else {
325     assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
326            "Expected a compare");
327     CmpInst::Predicate Pred = cast<CmpInst>(I).getPredicate();
328     ScalarOpCost = TTI.getCmpSelInstrCost(
329         Opcode, ScalarTy, CmpInst::makeCmpResultType(ScalarTy), Pred);
330     VectorOpCost = TTI.getCmpSelInstrCost(
331         Opcode, VecTy, CmpInst::makeCmpResultType(VecTy), Pred);
332   }
333 
334   // Get cost estimates for the extract elements. These costs will factor into
335   // both sequences.
336   unsigned Ext0Index = cast<ConstantInt>(Ext0->getOperand(1))->getZExtValue();
337   unsigned Ext1Index = cast<ConstantInt>(Ext1->getOperand(1))->getZExtValue();
338 
339   InstructionCost Extract0Cost =
340       TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy, Ext0Index);
341   InstructionCost Extract1Cost =
342       TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy, Ext1Index);
343 
344   // A more expensive extract will always be replaced by a splat shuffle.
345   // For example, if Ext0 is more expensive:
346   // opcode (extelt V0, Ext0), (ext V1, Ext1) -->
347   // extelt (opcode (splat V0, Ext0), V1), Ext1
348   // TODO: Evaluate whether that always results in lowest cost. Alternatively,
349   //       check the cost of creating a broadcast shuffle and shuffling both
350   //       operands to element 0.
351   InstructionCost CheapExtractCost = std::min(Extract0Cost, Extract1Cost);
352 
353   // Extra uses of the extracts mean that we include those costs in the
354   // vector total because those instructions will not be eliminated.
355   InstructionCost OldCost, NewCost;
356   if (Ext0->getOperand(0) == Ext1->getOperand(0) && Ext0Index == Ext1Index) {
357     // Handle a special case. If the 2 extracts are identical, adjust the
358     // formulas to account for that. The extra use charge allows for either the
359     // CSE'd pattern or an unoptimized form with identical values:
360     // opcode (extelt V, C), (extelt V, C) --> extelt (opcode V, V), C
361     bool HasUseTax = Ext0 == Ext1 ? !Ext0->hasNUses(2)
362                                   : !Ext0->hasOneUse() || !Ext1->hasOneUse();
363     OldCost = CheapExtractCost + ScalarOpCost;
364     NewCost = VectorOpCost + CheapExtractCost + HasUseTax * CheapExtractCost;
365   } else {
366     // Handle the general case. Each extract is actually a different value:
367     // opcode (extelt V0, C0), (extelt V1, C1) --> extelt (opcode V0, V1), C
368     OldCost = Extract0Cost + Extract1Cost + ScalarOpCost;
369     NewCost = VectorOpCost + CheapExtractCost +
370               !Ext0->hasOneUse() * Extract0Cost +
371               !Ext1->hasOneUse() * Extract1Cost;
372   }
373 
374   ConvertToShuffle = getShuffleExtract(Ext0, Ext1, PreferredExtractIndex);
375   if (ConvertToShuffle) {
376     if (IsBinOp && DisableBinopExtractShuffle)
377       return true;
378 
379     // If we are extracting from 2 different indexes, then one operand must be
380     // shuffled before performing the vector operation. The shuffle mask is
381     // undefined except for 1 lane that is being translated to the remaining
382     // extraction lane. Therefore, it is a splat shuffle. Ex:
383     // ShufMask = { undef, undef, 0, undef }
384     // TODO: The cost model has an option for a "broadcast" shuffle
385     //       (splat-from-element-0), but no option for a more general splat.
386     NewCost +=
387         TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, VecTy);
388   }
389 
390   // Aggressively form a vector op if the cost is equal because the transform
391   // may enable further optimization.
392   // Codegen can reverse this transform (scalarize) if it was not profitable.
393   return OldCost < NewCost;
394 }
395 
396 /// Create a shuffle that translates (shifts) 1 element from the input vector
397 /// to a new element location.
398 static Value *createShiftShuffle(Value *Vec, unsigned OldIndex,
399                                  unsigned NewIndex, IRBuilder<> &Builder) {
400   // The shuffle mask is undefined except for 1 lane that is being translated
401   // to the new element index. Example for OldIndex == 2 and NewIndex == 0:
402   // ShufMask = { 2, undef, undef, undef }
403   auto *VecTy = cast<FixedVectorType>(Vec->getType());
404   SmallVector<int, 32> ShufMask(VecTy->getNumElements(), UndefMaskElem);
405   ShufMask[NewIndex] = OldIndex;
406   return Builder.CreateShuffleVector(Vec, ShufMask, "shift");
407 }
408 
409 /// Given an extract element instruction with constant index operand, shuffle
410 /// the source vector (shift the scalar element) to a NewIndex for extraction.
411 /// Return null if the input can be constant folded, so that we are not creating
412 /// unnecessary instructions.
413 static ExtractElementInst *translateExtract(ExtractElementInst *ExtElt,
414                                             unsigned NewIndex,
415                                             IRBuilder<> &Builder) {
416   // If the extract can be constant-folded, this code is unsimplified. Defer
417   // to other passes to handle that.
418   Value *X = ExtElt->getVectorOperand();
419   Value *C = ExtElt->getIndexOperand();
420   assert(isa<ConstantInt>(C) && "Expected a constant index operand");
421   if (isa<Constant>(X))
422     return nullptr;
423 
424   Value *Shuf = createShiftShuffle(X, cast<ConstantInt>(C)->getZExtValue(),
425                                    NewIndex, Builder);
426   return cast<ExtractElementInst>(Builder.CreateExtractElement(Shuf, NewIndex));
427 }
428 
429 /// Try to reduce extract element costs by converting scalar compares to vector
430 /// compares followed by extract.
431 /// cmp (ext0 V0, C), (ext1 V1, C)
432 void VectorCombine::foldExtExtCmp(ExtractElementInst *Ext0,
433                                   ExtractElementInst *Ext1, Instruction &I) {
434   assert(isa<CmpInst>(&I) && "Expected a compare");
435   assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() ==
436              cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() &&
437          "Expected matching constant extract indexes");
438 
439   // cmp Pred (extelt V0, C), (extelt V1, C) --> extelt (cmp Pred V0, V1), C
440   ++NumVecCmp;
441   CmpInst::Predicate Pred = cast<CmpInst>(&I)->getPredicate();
442   Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand();
443   Value *VecCmp = Builder.CreateCmp(Pred, V0, V1);
444   Value *NewExt = Builder.CreateExtractElement(VecCmp, Ext0->getIndexOperand());
445   replaceValue(I, *NewExt);
446 }
447 
448 /// Try to reduce extract element costs by converting scalar binops to vector
449 /// binops followed by extract.
450 /// bo (ext0 V0, C), (ext1 V1, C)
451 void VectorCombine::foldExtExtBinop(ExtractElementInst *Ext0,
452                                     ExtractElementInst *Ext1, Instruction &I) {
453   assert(isa<BinaryOperator>(&I) && "Expected a binary operator");
454   assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() ==
455              cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() &&
456          "Expected matching constant extract indexes");
457 
458   // bo (extelt V0, C), (extelt V1, C) --> extelt (bo V0, V1), C
459   ++NumVecBO;
460   Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand();
461   Value *VecBO =
462       Builder.CreateBinOp(cast<BinaryOperator>(&I)->getOpcode(), V0, V1);
463 
464   // All IR flags are safe to back-propagate because any potential poison
465   // created in unused vector elements is discarded by the extract.
466   if (auto *VecBOInst = dyn_cast<Instruction>(VecBO))
467     VecBOInst->copyIRFlags(&I);
468 
469   Value *NewExt = Builder.CreateExtractElement(VecBO, Ext0->getIndexOperand());
470   replaceValue(I, *NewExt);
471 }
472 
473 /// Match an instruction with extracted vector operands.
474 bool VectorCombine::foldExtractExtract(Instruction &I) {
475   // It is not safe to transform things like div, urem, etc. because we may
476   // create undefined behavior when executing those on unknown vector elements.
477   if (!isSafeToSpeculativelyExecute(&I))
478     return false;
479 
480   Instruction *I0, *I1;
481   CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
482   if (!match(&I, m_Cmp(Pred, m_Instruction(I0), m_Instruction(I1))) &&
483       !match(&I, m_BinOp(m_Instruction(I0), m_Instruction(I1))))
484     return false;
485 
486   Value *V0, *V1;
487   uint64_t C0, C1;
488   if (!match(I0, m_ExtractElt(m_Value(V0), m_ConstantInt(C0))) ||
489       !match(I1, m_ExtractElt(m_Value(V1), m_ConstantInt(C1))) ||
490       V0->getType() != V1->getType())
491     return false;
492 
493   // If the scalar value 'I' is going to be re-inserted into a vector, then try
494   // to create an extract to that same element. The extract/insert can be
495   // reduced to a "select shuffle".
496   // TODO: If we add a larger pattern match that starts from an insert, this
497   //       probably becomes unnecessary.
498   auto *Ext0 = cast<ExtractElementInst>(I0);
499   auto *Ext1 = cast<ExtractElementInst>(I1);
500   uint64_t InsertIndex = InvalidIndex;
501   if (I.hasOneUse())
502     match(I.user_back(),
503           m_InsertElt(m_Value(), m_Value(), m_ConstantInt(InsertIndex)));
504 
505   ExtractElementInst *ExtractToChange;
506   if (isExtractExtractCheap(Ext0, Ext1, I, ExtractToChange, InsertIndex))
507     return false;
508 
509   if (ExtractToChange) {
510     unsigned CheapExtractIdx = ExtractToChange == Ext0 ? C1 : C0;
511     ExtractElementInst *NewExtract =
512         translateExtract(ExtractToChange, CheapExtractIdx, Builder);
513     if (!NewExtract)
514       return false;
515     if (ExtractToChange == Ext0)
516       Ext0 = NewExtract;
517     else
518       Ext1 = NewExtract;
519   }
520 
521   if (Pred != CmpInst::BAD_ICMP_PREDICATE)
522     foldExtExtCmp(Ext0, Ext1, I);
523   else
524     foldExtExtBinop(Ext0, Ext1, I);
525 
526   Worklist.push(Ext0);
527   Worklist.push(Ext1);
528   return true;
529 }
530 
531 /// If this is a bitcast of a shuffle, try to bitcast the source vector to the
532 /// destination type followed by shuffle. This can enable further transforms by
533 /// moving bitcasts or shuffles together.
534 bool VectorCombine::foldBitcastShuf(Instruction &I) {
535   Value *V;
536   ArrayRef<int> Mask;
537   if (!match(&I, m_BitCast(
538                      m_OneUse(m_Shuffle(m_Value(V), m_Undef(), m_Mask(Mask))))))
539     return false;
540 
541   // 1) Do not fold bitcast shuffle for scalable type. First, shuffle cost for
542   // scalable type is unknown; Second, we cannot reason if the narrowed shuffle
543   // mask for scalable type is a splat or not.
544   // 2) Disallow non-vector casts and length-changing shuffles.
545   // TODO: We could allow any shuffle.
546   auto *DestTy = dyn_cast<FixedVectorType>(I.getType());
547   auto *SrcTy = dyn_cast<FixedVectorType>(V->getType());
548   if (!SrcTy || !DestTy || I.getOperand(0)->getType() != SrcTy)
549     return false;
550 
551   unsigned DestNumElts = DestTy->getNumElements();
552   unsigned SrcNumElts = SrcTy->getNumElements();
553   SmallVector<int, 16> NewMask;
554   if (SrcNumElts <= DestNumElts) {
555     // The bitcast is from wide to narrow/equal elements. The shuffle mask can
556     // always be expanded to the equivalent form choosing narrower elements.
557     assert(DestNumElts % SrcNumElts == 0 && "Unexpected shuffle mask");
558     unsigned ScaleFactor = DestNumElts / SrcNumElts;
559     narrowShuffleMaskElts(ScaleFactor, Mask, NewMask);
560   } else {
561     // The bitcast is from narrow elements to wide elements. The shuffle mask
562     // must choose consecutive elements to allow casting first.
563     assert(SrcNumElts % DestNumElts == 0 && "Unexpected shuffle mask");
564     unsigned ScaleFactor = SrcNumElts / DestNumElts;
565     if (!widenShuffleMaskElts(ScaleFactor, Mask, NewMask))
566       return false;
567   }
568 
569   // The new shuffle must not cost more than the old shuffle. The bitcast is
570   // moved ahead of the shuffle, so assume that it has the same cost as before.
571   InstructionCost DestCost = TTI.getShuffleCost(
572       TargetTransformInfo::SK_PermuteSingleSrc, DestTy, NewMask);
573   InstructionCost SrcCost =
574       TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, SrcTy, Mask);
575   if (DestCost > SrcCost || !DestCost.isValid())
576     return false;
577 
578   // bitcast (shuf V, MaskC) --> shuf (bitcast V), MaskC'
579   ++NumShufOfBitcast;
580   Value *CastV = Builder.CreateBitCast(V, DestTy);
581   Value *Shuf = Builder.CreateShuffleVector(CastV, NewMask);
582   replaceValue(I, *Shuf);
583   return true;
584 }
585 
586 /// Match a vector binop or compare instruction with at least one inserted
587 /// scalar operand and convert to scalar binop/cmp followed by insertelement.
588 bool VectorCombine::scalarizeBinopOrCmp(Instruction &I) {
589   CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
590   Value *Ins0, *Ins1;
591   if (!match(&I, m_BinOp(m_Value(Ins0), m_Value(Ins1))) &&
592       !match(&I, m_Cmp(Pred, m_Value(Ins0), m_Value(Ins1))))
593     return false;
594 
595   // Do not convert the vector condition of a vector select into a scalar
596   // condition. That may cause problems for codegen because of differences in
597   // boolean formats and register-file transfers.
598   // TODO: Can we account for that in the cost model?
599   bool IsCmp = Pred != CmpInst::Predicate::BAD_ICMP_PREDICATE;
600   if (IsCmp)
601     for (User *U : I.users())
602       if (match(U, m_Select(m_Specific(&I), m_Value(), m_Value())))
603         return false;
604 
605   // Match against one or both scalar values being inserted into constant
606   // vectors:
607   // vec_op VecC0, (inselt VecC1, V1, Index)
608   // vec_op (inselt VecC0, V0, Index), VecC1
609   // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index)
610   // TODO: Deal with mismatched index constants and variable indexes?
611   Constant *VecC0 = nullptr, *VecC1 = nullptr;
612   Value *V0 = nullptr, *V1 = nullptr;
613   uint64_t Index0 = 0, Index1 = 0;
614   if (!match(Ins0, m_InsertElt(m_Constant(VecC0), m_Value(V0),
615                                m_ConstantInt(Index0))) &&
616       !match(Ins0, m_Constant(VecC0)))
617     return false;
618   if (!match(Ins1, m_InsertElt(m_Constant(VecC1), m_Value(V1),
619                                m_ConstantInt(Index1))) &&
620       !match(Ins1, m_Constant(VecC1)))
621     return false;
622 
623   bool IsConst0 = !V0;
624   bool IsConst1 = !V1;
625   if (IsConst0 && IsConst1)
626     return false;
627   if (!IsConst0 && !IsConst1 && Index0 != Index1)
628     return false;
629 
630   // Bail for single insertion if it is a load.
631   // TODO: Handle this once getVectorInstrCost can cost for load/stores.
632   auto *I0 = dyn_cast_or_null<Instruction>(V0);
633   auto *I1 = dyn_cast_or_null<Instruction>(V1);
634   if ((IsConst0 && I1 && I1->mayReadFromMemory()) ||
635       (IsConst1 && I0 && I0->mayReadFromMemory()))
636     return false;
637 
638   uint64_t Index = IsConst0 ? Index1 : Index0;
639   Type *ScalarTy = IsConst0 ? V1->getType() : V0->getType();
640   Type *VecTy = I.getType();
641   assert(VecTy->isVectorTy() &&
642          (IsConst0 || IsConst1 || V0->getType() == V1->getType()) &&
643          (ScalarTy->isIntegerTy() || ScalarTy->isFloatingPointTy() ||
644           ScalarTy->isPointerTy()) &&
645          "Unexpected types for insert element into binop or cmp");
646 
647   unsigned Opcode = I.getOpcode();
648   InstructionCost ScalarOpCost, VectorOpCost;
649   if (IsCmp) {
650     CmpInst::Predicate Pred = cast<CmpInst>(I).getPredicate();
651     ScalarOpCost = TTI.getCmpSelInstrCost(
652         Opcode, ScalarTy, CmpInst::makeCmpResultType(ScalarTy), Pred);
653     VectorOpCost = TTI.getCmpSelInstrCost(
654         Opcode, VecTy, CmpInst::makeCmpResultType(VecTy), Pred);
655   } else {
656     ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
657     VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
658   }
659 
660   // Get cost estimate for the insert element. This cost will factor into
661   // both sequences.
662   InstructionCost InsertCost =
663       TTI.getVectorInstrCost(Instruction::InsertElement, VecTy, Index);
664   InstructionCost OldCost =
665       (IsConst0 ? 0 : InsertCost) + (IsConst1 ? 0 : InsertCost) + VectorOpCost;
666   InstructionCost NewCost = ScalarOpCost + InsertCost +
667                             (IsConst0 ? 0 : !Ins0->hasOneUse() * InsertCost) +
668                             (IsConst1 ? 0 : !Ins1->hasOneUse() * InsertCost);
669 
670   // We want to scalarize unless the vector variant actually has lower cost.
671   if (OldCost < NewCost || !NewCost.isValid())
672     return false;
673 
674   // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index) -->
675   // inselt NewVecC, (scalar_op V0, V1), Index
676   if (IsCmp)
677     ++NumScalarCmp;
678   else
679     ++NumScalarBO;
680 
681   // For constant cases, extract the scalar element, this should constant fold.
682   if (IsConst0)
683     V0 = ConstantExpr::getExtractElement(VecC0, Builder.getInt64(Index));
684   if (IsConst1)
685     V1 = ConstantExpr::getExtractElement(VecC1, Builder.getInt64(Index));
686 
687   Value *Scalar =
688       IsCmp ? Builder.CreateCmp(Pred, V0, V1)
689             : Builder.CreateBinOp((Instruction::BinaryOps)Opcode, V0, V1);
690 
691   Scalar->setName(I.getName() + ".scalar");
692 
693   // All IR flags are safe to back-propagate. There is no potential for extra
694   // poison to be created by the scalar instruction.
695   if (auto *ScalarInst = dyn_cast<Instruction>(Scalar))
696     ScalarInst->copyIRFlags(&I);
697 
698   // Fold the vector constants in the original vectors into a new base vector.
699   Constant *NewVecC = IsCmp ? ConstantExpr::getCompare(Pred, VecC0, VecC1)
700                             : ConstantExpr::get(Opcode, VecC0, VecC1);
701   Value *Insert = Builder.CreateInsertElement(NewVecC, Scalar, Index);
702   replaceValue(I, *Insert);
703   return true;
704 }
705 
706 /// Try to combine a scalar binop + 2 scalar compares of extracted elements of
707 /// a vector into vector operations followed by extract. Note: The SLP pass
708 /// may miss this pattern because of implementation problems.
709 bool VectorCombine::foldExtractedCmps(Instruction &I) {
710   // We are looking for a scalar binop of booleans.
711   // binop i1 (cmp Pred I0, C0), (cmp Pred I1, C1)
712   if (!I.isBinaryOp() || !I.getType()->isIntegerTy(1))
713     return false;
714 
715   // The compare predicates should match, and each compare should have a
716   // constant operand.
717   // TODO: Relax the one-use constraints.
718   Value *B0 = I.getOperand(0), *B1 = I.getOperand(1);
719   Instruction *I0, *I1;
720   Constant *C0, *C1;
721   CmpInst::Predicate P0, P1;
722   if (!match(B0, m_OneUse(m_Cmp(P0, m_Instruction(I0), m_Constant(C0)))) ||
723       !match(B1, m_OneUse(m_Cmp(P1, m_Instruction(I1), m_Constant(C1)))) ||
724       P0 != P1)
725     return false;
726 
727   // The compare operands must be extracts of the same vector with constant
728   // extract indexes.
729   // TODO: Relax the one-use constraints.
730   Value *X;
731   uint64_t Index0, Index1;
732   if (!match(I0, m_OneUse(m_ExtractElt(m_Value(X), m_ConstantInt(Index0)))) ||
733       !match(I1, m_OneUse(m_ExtractElt(m_Specific(X), m_ConstantInt(Index1)))))
734     return false;
735 
736   auto *Ext0 = cast<ExtractElementInst>(I0);
737   auto *Ext1 = cast<ExtractElementInst>(I1);
738   ExtractElementInst *ConvertToShuf = getShuffleExtract(Ext0, Ext1);
739   if (!ConvertToShuf)
740     return false;
741 
742   // The original scalar pattern is:
743   // binop i1 (cmp Pred (ext X, Index0), C0), (cmp Pred (ext X, Index1), C1)
744   CmpInst::Predicate Pred = P0;
745   unsigned CmpOpcode = CmpInst::isFPPredicate(Pred) ? Instruction::FCmp
746                                                     : Instruction::ICmp;
747   auto *VecTy = dyn_cast<FixedVectorType>(X->getType());
748   if (!VecTy)
749     return false;
750 
751   InstructionCost OldCost =
752       TTI.getVectorInstrCost(Ext0->getOpcode(), VecTy, Index0);
753   OldCost += TTI.getVectorInstrCost(Ext1->getOpcode(), VecTy, Index1);
754   OldCost +=
755       TTI.getCmpSelInstrCost(CmpOpcode, I0->getType(),
756                              CmpInst::makeCmpResultType(I0->getType()), Pred) *
757       2;
758   OldCost += TTI.getArithmeticInstrCost(I.getOpcode(), I.getType());
759 
760   // The proposed vector pattern is:
761   // vcmp = cmp Pred X, VecC
762   // ext (binop vNi1 vcmp, (shuffle vcmp, Index1)), Index0
763   int CheapIndex = ConvertToShuf == Ext0 ? Index1 : Index0;
764   int ExpensiveIndex = ConvertToShuf == Ext0 ? Index0 : Index1;
765   auto *CmpTy = cast<FixedVectorType>(CmpInst::makeCmpResultType(X->getType()));
766   InstructionCost NewCost = TTI.getCmpSelInstrCost(
767       CmpOpcode, X->getType(), CmpInst::makeCmpResultType(X->getType()), Pred);
768   SmallVector<int, 32> ShufMask(VecTy->getNumElements(), UndefMaskElem);
769   ShufMask[CheapIndex] = ExpensiveIndex;
770   NewCost += TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, CmpTy,
771                                 ShufMask);
772   NewCost += TTI.getArithmeticInstrCost(I.getOpcode(), CmpTy);
773   NewCost += TTI.getVectorInstrCost(Ext0->getOpcode(), CmpTy, CheapIndex);
774 
775   // Aggressively form vector ops if the cost is equal because the transform
776   // may enable further optimization.
777   // Codegen can reverse this transform (scalarize) if it was not profitable.
778   if (OldCost < NewCost || !NewCost.isValid())
779     return false;
780 
781   // Create a vector constant from the 2 scalar constants.
782   SmallVector<Constant *, 32> CmpC(VecTy->getNumElements(),
783                                    UndefValue::get(VecTy->getElementType()));
784   CmpC[Index0] = C0;
785   CmpC[Index1] = C1;
786   Value *VCmp = Builder.CreateCmp(Pred, X, ConstantVector::get(CmpC));
787 
788   Value *Shuf = createShiftShuffle(VCmp, ExpensiveIndex, CheapIndex, Builder);
789   Value *VecLogic = Builder.CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
790                                         VCmp, Shuf);
791   Value *NewExt = Builder.CreateExtractElement(VecLogic, CheapIndex);
792   replaceValue(I, *NewExt);
793   ++NumVecCmpBO;
794   return true;
795 }
796 
797 // Check if memory loc modified between two instrs in the same BB
798 static bool isMemModifiedBetween(BasicBlock::iterator Begin,
799                                  BasicBlock::iterator End,
800                                  const MemoryLocation &Loc, AAResults &AA) {
801   unsigned NumScanned = 0;
802   return std::any_of(Begin, End, [&](const Instruction &Instr) {
803     return isModSet(AA.getModRefInfo(&Instr, Loc)) ||
804            ++NumScanned > MaxInstrsToScan;
805   });
806 }
807 
808 /// Helper class to indicate whether a vector index can be safely scalarized and
809 /// if a freeze needs to be inserted.
810 class ScalarizationResult {
811   enum class StatusTy { Unsafe, Safe, SafeWithFreeze };
812 
813   StatusTy Status;
814   Value *ToFreeze;
815 
816   ScalarizationResult(StatusTy Status, Value *ToFreeze = nullptr)
817       : Status(Status), ToFreeze(ToFreeze) {}
818 
819 public:
820   ScalarizationResult(const ScalarizationResult &Other) = default;
821   ~ScalarizationResult() {
822     assert(!ToFreeze && "freeze() not called with ToFreeze being set");
823   }
824 
825   static ScalarizationResult unsafe() { return {StatusTy::Unsafe}; }
826   static ScalarizationResult safe() { return {StatusTy::Safe}; }
827   static ScalarizationResult safeWithFreeze(Value *ToFreeze) {
828     return {StatusTy::SafeWithFreeze, ToFreeze};
829   }
830 
831   /// Returns true if the index can be scalarize without requiring a freeze.
832   bool isSafe() const { return Status == StatusTy::Safe; }
833   /// Returns true if the index cannot be scalarized.
834   bool isUnsafe() const { return Status == StatusTy::Unsafe; }
835   /// Returns true if the index can be scalarize, but requires inserting a
836   /// freeze.
837   bool isSafeWithFreeze() const { return Status == StatusTy::SafeWithFreeze; }
838 
839   /// Reset the state of Unsafe and clear ToFreze if set.
840   void discard() {
841     ToFreeze = nullptr;
842     Status = StatusTy::Unsafe;
843   }
844 
845   /// Freeze the ToFreeze and update the use in \p User to use it.
846   void freeze(IRBuilder<> &Builder, Instruction &UserI) {
847     assert(isSafeWithFreeze() &&
848            "should only be used when freezing is required");
849     assert(is_contained(ToFreeze->users(), &UserI) &&
850            "UserI must be a user of ToFreeze");
851     IRBuilder<>::InsertPointGuard Guard(Builder);
852     Builder.SetInsertPoint(cast<Instruction>(&UserI));
853     Value *Frozen =
854         Builder.CreateFreeze(ToFreeze, ToFreeze->getName() + ".frozen");
855     for (Use &U : make_early_inc_range((UserI.operands())))
856       if (U.get() == ToFreeze)
857         U.set(Frozen);
858 
859     ToFreeze = nullptr;
860   }
861 };
862 
863 /// Check if it is legal to scalarize a memory access to \p VecTy at index \p
864 /// Idx. \p Idx must access a valid vector element.
865 static ScalarizationResult canScalarizeAccess(FixedVectorType *VecTy,
866                                               Value *Idx, Instruction *CtxI,
867                                               AssumptionCache &AC,
868                                               const DominatorTree &DT) {
869   if (auto *C = dyn_cast<ConstantInt>(Idx)) {
870     if (C->getValue().ult(VecTy->getNumElements()))
871       return ScalarizationResult::safe();
872     return ScalarizationResult::unsafe();
873   }
874 
875   unsigned IntWidth = Idx->getType()->getScalarSizeInBits();
876   APInt Zero(IntWidth, 0);
877   APInt MaxElts(IntWidth, VecTy->getNumElements());
878   ConstantRange ValidIndices(Zero, MaxElts);
879   ConstantRange IdxRange(IntWidth, true);
880 
881   if (isGuaranteedNotToBePoison(Idx, &AC)) {
882     if (ValidIndices.contains(computeConstantRange(Idx, /* ForSigned */ false,
883                                                    true, &AC, CtxI, &DT)))
884       return ScalarizationResult::safe();
885     return ScalarizationResult::unsafe();
886   }
887 
888   // If the index may be poison, check if we can insert a freeze before the
889   // range of the index is restricted.
890   Value *IdxBase;
891   ConstantInt *CI;
892   if (match(Idx, m_And(m_Value(IdxBase), m_ConstantInt(CI)))) {
893     IdxRange = IdxRange.binaryAnd(CI->getValue());
894   } else if (match(Idx, m_URem(m_Value(IdxBase), m_ConstantInt(CI)))) {
895     IdxRange = IdxRange.urem(CI->getValue());
896   }
897 
898   if (ValidIndices.contains(IdxRange))
899     return ScalarizationResult::safeWithFreeze(IdxBase);
900   return ScalarizationResult::unsafe();
901 }
902 
903 /// The memory operation on a vector of \p ScalarType had alignment of
904 /// \p VectorAlignment. Compute the maximal, but conservatively correct,
905 /// alignment that will be valid for the memory operation on a single scalar
906 /// element of the same type with index \p Idx.
907 static Align computeAlignmentAfterScalarization(Align VectorAlignment,
908                                                 Type *ScalarType, Value *Idx,
909                                                 const DataLayout &DL) {
910   if (auto *C = dyn_cast<ConstantInt>(Idx))
911     return commonAlignment(VectorAlignment,
912                            C->getZExtValue() * DL.getTypeStoreSize(ScalarType));
913   return commonAlignment(VectorAlignment, DL.getTypeStoreSize(ScalarType));
914 }
915 
916 // Combine patterns like:
917 //   %0 = load <4 x i32>, <4 x i32>* %a
918 //   %1 = insertelement <4 x i32> %0, i32 %b, i32 1
919 //   store <4 x i32> %1, <4 x i32>* %a
920 // to:
921 //   %0 = bitcast <4 x i32>* %a to i32*
922 //   %1 = getelementptr inbounds i32, i32* %0, i64 0, i64 1
923 //   store i32 %b, i32* %1
924 bool VectorCombine::foldSingleElementStore(Instruction &I) {
925   StoreInst *SI = dyn_cast<StoreInst>(&I);
926   if (!SI || !SI->isSimple() ||
927       !isa<FixedVectorType>(SI->getValueOperand()->getType()))
928     return false;
929 
930   // TODO: Combine more complicated patterns (multiple insert) by referencing
931   // TargetTransformInfo.
932   Instruction *Source;
933   Value *NewElement;
934   Value *Idx;
935   if (!match(SI->getValueOperand(),
936              m_InsertElt(m_Instruction(Source), m_Value(NewElement),
937                          m_Value(Idx))))
938     return false;
939 
940   if (auto *Load = dyn_cast<LoadInst>(Source)) {
941     auto VecTy = cast<FixedVectorType>(SI->getValueOperand()->getType());
942     const DataLayout &DL = I.getModule()->getDataLayout();
943     Value *SrcAddr = Load->getPointerOperand()->stripPointerCasts();
944     // Don't optimize for atomic/volatile load or store. Ensure memory is not
945     // modified between, vector type matches store size, and index is inbounds.
946     if (!Load->isSimple() || Load->getParent() != SI->getParent() ||
947         !DL.typeSizeEqualsStoreSize(Load->getType()) ||
948         SrcAddr != SI->getPointerOperand()->stripPointerCasts())
949       return false;
950 
951     auto ScalarizableIdx = canScalarizeAccess(VecTy, Idx, Load, AC, DT);
952     if (ScalarizableIdx.isUnsafe() ||
953         isMemModifiedBetween(Load->getIterator(), SI->getIterator(),
954                              MemoryLocation::get(SI), AA))
955       return false;
956 
957     if (ScalarizableIdx.isSafeWithFreeze())
958       ScalarizableIdx.freeze(Builder, *cast<Instruction>(Idx));
959     Value *GEP = Builder.CreateInBoundsGEP(
960         SI->getValueOperand()->getType(), SI->getPointerOperand(),
961         {ConstantInt::get(Idx->getType(), 0), Idx});
962     StoreInst *NSI = Builder.CreateStore(NewElement, GEP);
963     NSI->copyMetadata(*SI);
964     Align ScalarOpAlignment = computeAlignmentAfterScalarization(
965         std::max(SI->getAlign(), Load->getAlign()), NewElement->getType(), Idx,
966         DL);
967     NSI->setAlignment(ScalarOpAlignment);
968     replaceValue(I, *NSI);
969     eraseInstruction(I);
970     return true;
971   }
972 
973   return false;
974 }
975 
976 /// Try to scalarize vector loads feeding extractelement instructions.
977 bool VectorCombine::scalarizeLoadExtract(Instruction &I) {
978   Value *Ptr;
979   if (!match(&I, m_Load(m_Value(Ptr))))
980     return false;
981 
982   auto *LI = cast<LoadInst>(&I);
983   const DataLayout &DL = I.getModule()->getDataLayout();
984   if (LI->isVolatile() || !DL.typeSizeEqualsStoreSize(LI->getType()))
985     return false;
986 
987   auto *FixedVT = dyn_cast<FixedVectorType>(LI->getType());
988   if (!FixedVT)
989     return false;
990 
991   InstructionCost OriginalCost =
992       TTI.getMemoryOpCost(Instruction::Load, LI->getType(), LI->getAlign(),
993                           LI->getPointerAddressSpace());
994   InstructionCost ScalarizedCost = 0;
995 
996   Instruction *LastCheckedInst = LI;
997   unsigned NumInstChecked = 0;
998   // Check if all users of the load are extracts with no memory modifications
999   // between the load and the extract. Compute the cost of both the original
1000   // code and the scalarized version.
1001   for (User *U : LI->users()) {
1002     auto *UI = dyn_cast<ExtractElementInst>(U);
1003     if (!UI || UI->getParent() != LI->getParent())
1004       return false;
1005 
1006     if (!isGuaranteedNotToBePoison(UI->getOperand(1), &AC, LI, &DT))
1007       return false;
1008 
1009     // Check if any instruction between the load and the extract may modify
1010     // memory.
1011     if (LastCheckedInst->comesBefore(UI)) {
1012       for (Instruction &I :
1013            make_range(std::next(LI->getIterator()), UI->getIterator())) {
1014         // Bail out if we reached the check limit or the instruction may write
1015         // to memory.
1016         if (NumInstChecked == MaxInstrsToScan || I.mayWriteToMemory())
1017           return false;
1018         NumInstChecked++;
1019       }
1020       LastCheckedInst = UI;
1021     }
1022 
1023     auto ScalarIdx = canScalarizeAccess(FixedVT, UI->getOperand(1), &I, AC, DT);
1024     if (!ScalarIdx.isSafe()) {
1025       // TODO: Freeze index if it is safe to do so.
1026       ScalarIdx.discard();
1027       return false;
1028     }
1029 
1030     auto *Index = dyn_cast<ConstantInt>(UI->getOperand(1));
1031     OriginalCost +=
1032         TTI.getVectorInstrCost(Instruction::ExtractElement, LI->getType(),
1033                                Index ? Index->getZExtValue() : -1);
1034     ScalarizedCost +=
1035         TTI.getMemoryOpCost(Instruction::Load, FixedVT->getElementType(),
1036                             Align(1), LI->getPointerAddressSpace());
1037     ScalarizedCost += TTI.getAddressComputationCost(FixedVT->getElementType());
1038   }
1039 
1040   if (ScalarizedCost >= OriginalCost)
1041     return false;
1042 
1043   // Replace extracts with narrow scalar loads.
1044   for (User *U : LI->users()) {
1045     auto *EI = cast<ExtractElementInst>(U);
1046     Builder.SetInsertPoint(EI);
1047 
1048     Value *Idx = EI->getOperand(1);
1049     Value *GEP =
1050         Builder.CreateInBoundsGEP(FixedVT, Ptr, {Builder.getInt32(0), Idx});
1051     auto *NewLoad = cast<LoadInst>(Builder.CreateLoad(
1052         FixedVT->getElementType(), GEP, EI->getName() + ".scalar"));
1053 
1054     Align ScalarOpAlignment = computeAlignmentAfterScalarization(
1055         LI->getAlign(), FixedVT->getElementType(), Idx, DL);
1056     NewLoad->setAlignment(ScalarOpAlignment);
1057 
1058     replaceValue(*EI, *NewLoad);
1059   }
1060 
1061   return true;
1062 }
1063 
1064 /// Try to convert "shuffle (binop), (binop)" with a shared binop operand into
1065 /// "binop (shuffle), (shuffle)".
1066 bool VectorCombine::foldShuffleOfBinops(Instruction &I) {
1067   auto *VecTy = dyn_cast<FixedVectorType>(I.getType());
1068   if (!VecTy)
1069     return false;
1070 
1071   BinaryOperator *B0, *B1;
1072   ArrayRef<int> Mask;
1073   if (!match(&I, m_Shuffle(m_OneUse(m_BinOp(B0)), m_OneUse(m_BinOp(B1)),
1074                            m_Mask(Mask))) ||
1075       B0->getOpcode() != B1->getOpcode() || B0->getType() != VecTy)
1076     return false;
1077 
1078   // Try to replace a binop with a shuffle if the shuffle is not costly.
1079   // The new shuffle will choose from a single, common operand, so it may be
1080   // cheaper than the existing two-operand shuffle.
1081   SmallVector<int> UnaryMask = createUnaryMask(Mask, Mask.size());
1082   Instruction::BinaryOps Opcode = B0->getOpcode();
1083   InstructionCost BinopCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
1084   InstructionCost ShufCost = TTI.getShuffleCost(
1085       TargetTransformInfo::SK_PermuteSingleSrc, VecTy, UnaryMask);
1086   if (ShufCost > BinopCost)
1087     return false;
1088 
1089   // If we have something like "add X, Y" and "add Z, X", swap ops to match.
1090   Value *X = B0->getOperand(0), *Y = B0->getOperand(1);
1091   Value *Z = B1->getOperand(0), *W = B1->getOperand(1);
1092   if (BinaryOperator::isCommutative(Opcode) && X != Z && Y != W)
1093     std::swap(X, Y);
1094 
1095   Value *Shuf0, *Shuf1;
1096   if (X == Z) {
1097     // shuf (bo X, Y), (bo X, W) --> bo (shuf X), (shuf Y, W)
1098     Shuf0 = Builder.CreateShuffleVector(X, UnaryMask);
1099     Shuf1 = Builder.CreateShuffleVector(Y, W, Mask);
1100   } else if (Y == W) {
1101     // shuf (bo X, Y), (bo Z, Y) --> bo (shuf X, Z), (shuf Y)
1102     Shuf0 = Builder.CreateShuffleVector(X, Z, Mask);
1103     Shuf1 = Builder.CreateShuffleVector(Y, UnaryMask);
1104   } else {
1105     return false;
1106   }
1107 
1108   Value *NewBO = Builder.CreateBinOp(Opcode, Shuf0, Shuf1);
1109   // Intersect flags from the old binops.
1110   if (auto *NewInst = dyn_cast<Instruction>(NewBO)) {
1111     NewInst->copyIRFlags(B0);
1112     NewInst->andIRFlags(B1);
1113   }
1114   replaceValue(I, *NewBO);
1115   return true;
1116 }
1117 
1118 /// Given a commutative reduction, the order of the input lanes does not alter
1119 /// the results. We can use this to remove certain shuffles feeding the
1120 /// reduction, removing the need to shuffle at all.
1121 bool VectorCombine::foldShuffleFromReductions(Instruction &I) {
1122   auto *II = dyn_cast<IntrinsicInst>(&I);
1123   if (!II)
1124     return false;
1125   switch (II->getIntrinsicID()) {
1126   case Intrinsic::vector_reduce_add:
1127   case Intrinsic::vector_reduce_mul:
1128   case Intrinsic::vector_reduce_and:
1129   case Intrinsic::vector_reduce_or:
1130   case Intrinsic::vector_reduce_xor:
1131   case Intrinsic::vector_reduce_smin:
1132   case Intrinsic::vector_reduce_smax:
1133   case Intrinsic::vector_reduce_umin:
1134   case Intrinsic::vector_reduce_umax:
1135     break;
1136   default:
1137     return false;
1138   }
1139 
1140   // Find all the inputs when looking through operations that do not alter the
1141   // lane order (binops, for example). Currently we look for a single shuffle,
1142   // and can ignore splat values.
1143   std::queue<Value *> Worklist;
1144   SmallPtrSet<Value *, 4> Visited;
1145   ShuffleVectorInst *Shuffle = nullptr;
1146   if (auto *Op = dyn_cast<Instruction>(I.getOperand(0)))
1147     Worklist.push(Op);
1148 
1149   while (!Worklist.empty()) {
1150     Value *CV = Worklist.front();
1151     Worklist.pop();
1152     if (Visited.contains(CV))
1153       continue;
1154 
1155     // Splats don't change the order, so can be safely ignored.
1156     if (isSplatValue(CV))
1157       continue;
1158 
1159     Visited.insert(CV);
1160 
1161     if (auto *CI = dyn_cast<Instruction>(CV)) {
1162       if (CI->isBinaryOp()) {
1163         for (auto *Op : CI->operand_values())
1164           Worklist.push(Op);
1165         continue;
1166       } else if (auto *SV = dyn_cast<ShuffleVectorInst>(CI)) {
1167         if (Shuffle && Shuffle != SV)
1168           return false;
1169         Shuffle = SV;
1170         continue;
1171       }
1172     }
1173 
1174     // Anything else is currently an unknown node.
1175     return false;
1176   }
1177 
1178   if (!Shuffle)
1179     return false;
1180 
1181   // Check all uses of the binary ops and shuffles are also included in the
1182   // lane-invariant operations (Visited should be the list of lanewise
1183   // instructions, including the shuffle that we found).
1184   for (auto *V : Visited)
1185     for (auto *U : V->users())
1186       if (!Visited.contains(U) && U != &I)
1187         return false;
1188 
1189   FixedVectorType *VecType =
1190       dyn_cast<FixedVectorType>(II->getOperand(0)->getType());
1191   if (!VecType)
1192     return false;
1193   FixedVectorType *ShuffleInputType =
1194       dyn_cast<FixedVectorType>(Shuffle->getOperand(0)->getType());
1195   if (!ShuffleInputType)
1196     return false;
1197   int NumInputElts = ShuffleInputType->getNumElements();
1198 
1199   // Find the mask from sorting the lanes into order. This is most likely to
1200   // become a identity or concat mask. Undef elements are pushed to the end.
1201   SmallVector<int> ConcatMask;
1202   Shuffle->getShuffleMask(ConcatMask);
1203   sort(ConcatMask, [](int X, int Y) { return (unsigned)X < (unsigned)Y; });
1204   bool UsesSecondVec =
1205       any_of(ConcatMask, [&](int M) { return M >= NumInputElts; });
1206   InstructionCost OldCost = TTI.getShuffleCost(
1207       UsesSecondVec ? TTI::SK_PermuteTwoSrc : TTI::SK_PermuteSingleSrc, VecType,
1208       Shuffle->getShuffleMask());
1209   InstructionCost NewCost = TTI.getShuffleCost(
1210       UsesSecondVec ? TTI::SK_PermuteTwoSrc : TTI::SK_PermuteSingleSrc, VecType,
1211       ConcatMask);
1212 
1213   LLVM_DEBUG(dbgs() << "Found a reduction feeding from a shuffle: " << *Shuffle
1214                     << "\n");
1215   LLVM_DEBUG(dbgs() << "  OldCost: " << OldCost << " vs NewCost: " << NewCost
1216                     << "\n");
1217   if (NewCost < OldCost) {
1218     Builder.SetInsertPoint(Shuffle);
1219     Value *NewShuffle = Builder.CreateShuffleVector(
1220         Shuffle->getOperand(0), Shuffle->getOperand(1), ConcatMask);
1221     LLVM_DEBUG(dbgs() << "Created new shuffle: " << *NewShuffle << "\n");
1222     replaceValue(*Shuffle, *NewShuffle);
1223   }
1224 
1225   return false;
1226 }
1227 
1228 /// This is the entry point for all transforms. Pass manager differences are
1229 /// handled in the callers of this function.
1230 bool VectorCombine::run() {
1231   if (DisableVectorCombine)
1232     return false;
1233 
1234   // Don't attempt vectorization if the target does not support vectors.
1235   if (!TTI.getNumberOfRegisters(TTI.getRegisterClassForType(/*Vector*/ true)))
1236     return false;
1237 
1238   bool MadeChange = false;
1239   auto FoldInst = [this, &MadeChange](Instruction &I) {
1240     Builder.SetInsertPoint(&I);
1241     if (!ScalarizationOnly) {
1242       MadeChange |= vectorizeLoadInsert(I);
1243       MadeChange |= foldExtractExtract(I);
1244       MadeChange |= foldBitcastShuf(I);
1245       MadeChange |= foldExtractedCmps(I);
1246       MadeChange |= foldShuffleOfBinops(I);
1247       MadeChange |= foldShuffleFromReductions(I);
1248     }
1249     MadeChange |= scalarizeBinopOrCmp(I);
1250     MadeChange |= scalarizeLoadExtract(I);
1251     MadeChange |= foldSingleElementStore(I);
1252   };
1253   for (BasicBlock &BB : F) {
1254     // Ignore unreachable basic blocks.
1255     if (!DT.isReachableFromEntry(&BB))
1256       continue;
1257     // Use early increment range so that we can erase instructions in loop.
1258     for (Instruction &I : make_early_inc_range(BB)) {
1259       if (I.isDebugOrPseudoInst())
1260         continue;
1261       FoldInst(I);
1262     }
1263   }
1264 
1265   while (!Worklist.isEmpty()) {
1266     Instruction *I = Worklist.removeOne();
1267     if (!I)
1268       continue;
1269 
1270     if (isInstructionTriviallyDead(I)) {
1271       eraseInstruction(*I);
1272       continue;
1273     }
1274 
1275     FoldInst(*I);
1276   }
1277 
1278   return MadeChange;
1279 }
1280 
1281 // Pass manager boilerplate below here.
1282 
1283 namespace {
1284 class VectorCombineLegacyPass : public FunctionPass {
1285 public:
1286   static char ID;
1287   VectorCombineLegacyPass() : FunctionPass(ID) {
1288     initializeVectorCombineLegacyPassPass(*PassRegistry::getPassRegistry());
1289   }
1290 
1291   void getAnalysisUsage(AnalysisUsage &AU) const override {
1292     AU.addRequired<AssumptionCacheTracker>();
1293     AU.addRequired<DominatorTreeWrapperPass>();
1294     AU.addRequired<TargetTransformInfoWrapperPass>();
1295     AU.addRequired<AAResultsWrapperPass>();
1296     AU.setPreservesCFG();
1297     AU.addPreserved<DominatorTreeWrapperPass>();
1298     AU.addPreserved<GlobalsAAWrapperPass>();
1299     AU.addPreserved<AAResultsWrapperPass>();
1300     AU.addPreserved<BasicAAWrapperPass>();
1301     FunctionPass::getAnalysisUsage(AU);
1302   }
1303 
1304   bool runOnFunction(Function &F) override {
1305     if (skipFunction(F))
1306       return false;
1307     auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1308     auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1309     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1310     auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1311     VectorCombine Combiner(F, TTI, DT, AA, AC, false);
1312     return Combiner.run();
1313   }
1314 };
1315 } // namespace
1316 
1317 char VectorCombineLegacyPass::ID = 0;
1318 INITIALIZE_PASS_BEGIN(VectorCombineLegacyPass, "vector-combine",
1319                       "Optimize scalar/vector ops", false,
1320                       false)
1321 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1322 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1323 INITIALIZE_PASS_END(VectorCombineLegacyPass, "vector-combine",
1324                     "Optimize scalar/vector ops", false, false)
1325 Pass *llvm::createVectorCombinePass() {
1326   return new VectorCombineLegacyPass();
1327 }
1328 
1329 PreservedAnalyses VectorCombinePass::run(Function &F,
1330                                          FunctionAnalysisManager &FAM) {
1331   auto &AC = FAM.getResult<AssumptionAnalysis>(F);
1332   TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(F);
1333   DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F);
1334   AAResults &AA = FAM.getResult<AAManager>(F);
1335   VectorCombine Combiner(F, TTI, DT, AA, AC, ScalarizationOnly);
1336   if (!Combiner.run())
1337     return PreservedAnalyses::all();
1338   PreservedAnalyses PA;
1339   PA.preserveSet<CFGAnalyses>();
1340   return PA;
1341 }
1342