1 //===----------- VectorUtils.cpp - Vectorizer utility functions -----------===//
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 file defines vectorizer utilities.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/Analysis/VectorUtils.h"
14 #include "llvm/ADT/EquivalenceClasses.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/Analysis/DemandedBits.h"
17 #include "llvm/Analysis/LoopInfo.h"
18 #include "llvm/Analysis/LoopIterator.h"
19 #include "llvm/Analysis/ScalarEvolution.h"
20 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/IRBuilder.h"
25 #include "llvm/IR/PatternMatch.h"
26 #include "llvm/IR/Value.h"
27 #include "llvm/Support/CommandLine.h"
28 
29 #define DEBUG_TYPE "vectorutils"
30 
31 using namespace llvm;
32 using namespace llvm::PatternMatch;
33 
34 /// Maximum factor for an interleaved memory access.
35 static cl::opt<unsigned> MaxInterleaveGroupFactor(
36     "max-interleave-group-factor", cl::Hidden,
37     cl::desc("Maximum factor for an interleaved access group (default = 8)"),
38     cl::init(8));
39 
40 /// Return true if all of the intrinsic's arguments and return type are scalars
41 /// for the scalar form of the intrinsic, and vectors for the vector form of the
42 /// intrinsic (except operands that are marked as always being scalar by
43 /// isVectorIntrinsicWithScalarOpAtArg).
44 bool llvm::isTriviallyVectorizable(Intrinsic::ID ID) {
45   switch (ID) {
46   case Intrinsic::abs:   // Begin integer bit-manipulation.
47   case Intrinsic::bswap:
48   case Intrinsic::bitreverse:
49   case Intrinsic::ctpop:
50   case Intrinsic::ctlz:
51   case Intrinsic::cttz:
52   case Intrinsic::fshl:
53   case Intrinsic::fshr:
54   case Intrinsic::smax:
55   case Intrinsic::smin:
56   case Intrinsic::umax:
57   case Intrinsic::umin:
58   case Intrinsic::sadd_sat:
59   case Intrinsic::ssub_sat:
60   case Intrinsic::uadd_sat:
61   case Intrinsic::usub_sat:
62   case Intrinsic::smul_fix:
63   case Intrinsic::smul_fix_sat:
64   case Intrinsic::umul_fix:
65   case Intrinsic::umul_fix_sat:
66   case Intrinsic::sqrt: // Begin floating-point.
67   case Intrinsic::sin:
68   case Intrinsic::cos:
69   case Intrinsic::exp:
70   case Intrinsic::exp2:
71   case Intrinsic::log:
72   case Intrinsic::log10:
73   case Intrinsic::log2:
74   case Intrinsic::fabs:
75   case Intrinsic::minnum:
76   case Intrinsic::maxnum:
77   case Intrinsic::minimum:
78   case Intrinsic::maximum:
79   case Intrinsic::copysign:
80   case Intrinsic::floor:
81   case Intrinsic::ceil:
82   case Intrinsic::trunc:
83   case Intrinsic::rint:
84   case Intrinsic::nearbyint:
85   case Intrinsic::round:
86   case Intrinsic::roundeven:
87   case Intrinsic::pow:
88   case Intrinsic::fma:
89   case Intrinsic::fmuladd:
90   case Intrinsic::is_fpclass:
91   case Intrinsic::powi:
92   case Intrinsic::canonicalize:
93   case Intrinsic::fptosi_sat:
94   case Intrinsic::fptoui_sat:
95     return true;
96   default:
97     return false;
98   }
99 }
100 
101 /// Identifies if the vector form of the intrinsic has a scalar operand.
102 bool llvm::isVectorIntrinsicWithScalarOpAtArg(Intrinsic::ID ID,
103                                               unsigned ScalarOpdIdx) {
104   switch (ID) {
105   case Intrinsic::abs:
106   case Intrinsic::ctlz:
107   case Intrinsic::cttz:
108   case Intrinsic::is_fpclass:
109   case Intrinsic::powi:
110     return (ScalarOpdIdx == 1);
111   case Intrinsic::smul_fix:
112   case Intrinsic::smul_fix_sat:
113   case Intrinsic::umul_fix:
114   case Intrinsic::umul_fix_sat:
115     return (ScalarOpdIdx == 2);
116   default:
117     return false;
118   }
119 }
120 
121 bool llvm::isVectorIntrinsicWithOverloadTypeAtArg(Intrinsic::ID ID,
122                                                   int OpdIdx) {
123   switch (ID) {
124   case Intrinsic::fptosi_sat:
125   case Intrinsic::fptoui_sat:
126     return OpdIdx == -1 || OpdIdx == 0;
127   case Intrinsic::is_fpclass:
128     return OpdIdx == 0;
129   case Intrinsic::powi:
130     return OpdIdx == -1 || OpdIdx == 1;
131   default:
132     return OpdIdx == -1;
133   }
134 }
135 
136 /// Returns intrinsic ID for call.
137 /// For the input call instruction it finds mapping intrinsic and returns
138 /// its ID, in case it does not found it return not_intrinsic.
139 Intrinsic::ID llvm::getVectorIntrinsicIDForCall(const CallInst *CI,
140                                                 const TargetLibraryInfo *TLI) {
141   Intrinsic::ID ID = getIntrinsicForCallSite(*CI, TLI);
142   if (ID == Intrinsic::not_intrinsic)
143     return Intrinsic::not_intrinsic;
144 
145   if (isTriviallyVectorizable(ID) || ID == Intrinsic::lifetime_start ||
146       ID == Intrinsic::lifetime_end || ID == Intrinsic::assume ||
147       ID == Intrinsic::experimental_noalias_scope_decl ||
148       ID == Intrinsic::sideeffect || ID == Intrinsic::pseudoprobe)
149     return ID;
150   return Intrinsic::not_intrinsic;
151 }
152 
153 /// Given a vector and an element number, see if the scalar value is
154 /// already around as a register, for example if it were inserted then extracted
155 /// from the vector.
156 Value *llvm::findScalarElement(Value *V, unsigned EltNo) {
157   assert(V->getType()->isVectorTy() && "Not looking at a vector?");
158   VectorType *VTy = cast<VectorType>(V->getType());
159   // For fixed-length vector, return undef for out of range access.
160   if (auto *FVTy = dyn_cast<FixedVectorType>(VTy)) {
161     unsigned Width = FVTy->getNumElements();
162     if (EltNo >= Width)
163       return UndefValue::get(FVTy->getElementType());
164   }
165 
166   if (Constant *C = dyn_cast<Constant>(V))
167     return C->getAggregateElement(EltNo);
168 
169   if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
170     // If this is an insert to a variable element, we don't know what it is.
171     if (!isa<ConstantInt>(III->getOperand(2)))
172       return nullptr;
173     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
174 
175     // If this is an insert to the element we are looking for, return the
176     // inserted value.
177     if (EltNo == IIElt)
178       return III->getOperand(1);
179 
180     // Guard against infinite loop on malformed, unreachable IR.
181     if (III == III->getOperand(0))
182       return nullptr;
183 
184     // Otherwise, the insertelement doesn't modify the value, recurse on its
185     // vector input.
186     return findScalarElement(III->getOperand(0), EltNo);
187   }
188 
189   ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V);
190   // Restrict the following transformation to fixed-length vector.
191   if (SVI && isa<FixedVectorType>(SVI->getType())) {
192     unsigned LHSWidth =
193         cast<FixedVectorType>(SVI->getOperand(0)->getType())->getNumElements();
194     int InEl = SVI->getMaskValue(EltNo);
195     if (InEl < 0)
196       return UndefValue::get(VTy->getElementType());
197     if (InEl < (int)LHSWidth)
198       return findScalarElement(SVI->getOperand(0), InEl);
199     return findScalarElement(SVI->getOperand(1), InEl - LHSWidth);
200   }
201 
202   // Extract a value from a vector add operation with a constant zero.
203   // TODO: Use getBinOpIdentity() to generalize this.
204   Value *Val; Constant *C;
205   if (match(V, m_Add(m_Value(Val), m_Constant(C))))
206     if (Constant *Elt = C->getAggregateElement(EltNo))
207       if (Elt->isNullValue())
208         return findScalarElement(Val, EltNo);
209 
210   // If the vector is a splat then we can trivially find the scalar element.
211   if (isa<ScalableVectorType>(VTy))
212     if (Value *Splat = getSplatValue(V))
213       if (EltNo < VTy->getElementCount().getKnownMinValue())
214         return Splat;
215 
216   // Otherwise, we don't know.
217   return nullptr;
218 }
219 
220 int llvm::getSplatIndex(ArrayRef<int> Mask) {
221   int SplatIndex = -1;
222   for (int M : Mask) {
223     // Ignore invalid (undefined) mask elements.
224     if (M < 0)
225       continue;
226 
227     // There can be only 1 non-negative mask element value if this is a splat.
228     if (SplatIndex != -1 && SplatIndex != M)
229       return -1;
230 
231     // Initialize the splat index to the 1st non-negative mask element.
232     SplatIndex = M;
233   }
234   assert((SplatIndex == -1 || SplatIndex >= 0) && "Negative index?");
235   return SplatIndex;
236 }
237 
238 /// Get splat value if the input is a splat vector or return nullptr.
239 /// This function is not fully general. It checks only 2 cases:
240 /// the input value is (1) a splat constant vector or (2) a sequence
241 /// of instructions that broadcasts a scalar at element 0.
242 Value *llvm::getSplatValue(const Value *V) {
243   if (isa<VectorType>(V->getType()))
244     if (auto *C = dyn_cast<Constant>(V))
245       return C->getSplatValue();
246 
247   // shuf (inselt ?, Splat, 0), ?, <0, undef, 0, ...>
248   Value *Splat;
249   if (match(V,
250             m_Shuffle(m_InsertElt(m_Value(), m_Value(Splat), m_ZeroInt()),
251                       m_Value(), m_ZeroMask())))
252     return Splat;
253 
254   return nullptr;
255 }
256 
257 bool llvm::isSplatValue(const Value *V, int Index, unsigned Depth) {
258   assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
259 
260   if (isa<VectorType>(V->getType())) {
261     if (isa<UndefValue>(V))
262       return true;
263     // FIXME: We can allow undefs, but if Index was specified, we may want to
264     //        check that the constant is defined at that index.
265     if (auto *C = dyn_cast<Constant>(V))
266       return C->getSplatValue() != nullptr;
267   }
268 
269   if (auto *Shuf = dyn_cast<ShuffleVectorInst>(V)) {
270     // FIXME: We can safely allow undefs here. If Index was specified, we will
271     //        check that the mask elt is defined at the required index.
272     if (!all_equal(Shuf->getShuffleMask()))
273       return false;
274 
275     // Match any index.
276     if (Index == -1)
277       return true;
278 
279     // Match a specific element. The mask should be defined at and match the
280     // specified index.
281     return Shuf->getMaskValue(Index) == Index;
282   }
283 
284   // The remaining tests are all recursive, so bail out if we hit the limit.
285   if (Depth++ == MaxAnalysisRecursionDepth)
286     return false;
287 
288   // If both operands of a binop are splats, the result is a splat.
289   Value *X, *Y, *Z;
290   if (match(V, m_BinOp(m_Value(X), m_Value(Y))))
291     return isSplatValue(X, Index, Depth) && isSplatValue(Y, Index, Depth);
292 
293   // If all operands of a select are splats, the result is a splat.
294   if (match(V, m_Select(m_Value(X), m_Value(Y), m_Value(Z))))
295     return isSplatValue(X, Index, Depth) && isSplatValue(Y, Index, Depth) &&
296            isSplatValue(Z, Index, Depth);
297 
298   // TODO: Add support for unary ops (fneg), casts, intrinsics (overflow ops).
299 
300   return false;
301 }
302 
303 bool llvm::getShuffleDemandedElts(int SrcWidth, ArrayRef<int> Mask,
304                                   const APInt &DemandedElts, APInt &DemandedLHS,
305                                   APInt &DemandedRHS, bool AllowUndefElts) {
306   DemandedLHS = DemandedRHS = APInt::getZero(SrcWidth);
307 
308   // Early out if we don't demand any elements.
309   if (DemandedElts.isZero())
310     return true;
311 
312   // Simple case of a shuffle with zeroinitializer.
313   if (all_of(Mask, [](int Elt) { return Elt == 0; })) {
314     DemandedLHS.setBit(0);
315     return true;
316   }
317 
318   for (unsigned I = 0, E = Mask.size(); I != E; ++I) {
319     int M = Mask[I];
320     assert((-1 <= M) && (M < (SrcWidth * 2)) &&
321            "Invalid shuffle mask constant");
322 
323     if (!DemandedElts[I] || (AllowUndefElts && (M < 0)))
324       continue;
325 
326     // For undef elements, we don't know anything about the common state of
327     // the shuffle result.
328     if (M < 0)
329       return false;
330 
331     if (M < SrcWidth)
332       DemandedLHS.setBit(M);
333     else
334       DemandedRHS.setBit(M - SrcWidth);
335   }
336 
337   return true;
338 }
339 
340 void llvm::narrowShuffleMaskElts(int Scale, ArrayRef<int> Mask,
341                                  SmallVectorImpl<int> &ScaledMask) {
342   assert(Scale > 0 && "Unexpected scaling factor");
343 
344   // Fast-path: if no scaling, then it is just a copy.
345   if (Scale == 1) {
346     ScaledMask.assign(Mask.begin(), Mask.end());
347     return;
348   }
349 
350   ScaledMask.clear();
351   for (int MaskElt : Mask) {
352     if (MaskElt >= 0) {
353       assert(((uint64_t)Scale * MaskElt + (Scale - 1)) <= INT32_MAX &&
354              "Overflowed 32-bits");
355     }
356     for (int SliceElt = 0; SliceElt != Scale; ++SliceElt)
357       ScaledMask.push_back(MaskElt < 0 ? MaskElt : Scale * MaskElt + SliceElt);
358   }
359 }
360 
361 bool llvm::widenShuffleMaskElts(int Scale, ArrayRef<int> Mask,
362                                 SmallVectorImpl<int> &ScaledMask) {
363   assert(Scale > 0 && "Unexpected scaling factor");
364 
365   // Fast-path: if no scaling, then it is just a copy.
366   if (Scale == 1) {
367     ScaledMask.assign(Mask.begin(), Mask.end());
368     return true;
369   }
370 
371   // We must map the original elements down evenly to a type with less elements.
372   int NumElts = Mask.size();
373   if (NumElts % Scale != 0)
374     return false;
375 
376   ScaledMask.clear();
377   ScaledMask.reserve(NumElts / Scale);
378 
379   // Step through the input mask by splitting into Scale-sized slices.
380   do {
381     ArrayRef<int> MaskSlice = Mask.take_front(Scale);
382     assert((int)MaskSlice.size() == Scale && "Expected Scale-sized slice.");
383 
384     // The first element of the slice determines how we evaluate this slice.
385     int SliceFront = MaskSlice.front();
386     if (SliceFront < 0) {
387       // Negative values (undef or other "sentinel" values) must be equal across
388       // the entire slice.
389       if (!all_equal(MaskSlice))
390         return false;
391       ScaledMask.push_back(SliceFront);
392     } else {
393       // A positive mask element must be cleanly divisible.
394       if (SliceFront % Scale != 0)
395         return false;
396       // Elements of the slice must be consecutive.
397       for (int i = 1; i < Scale; ++i)
398         if (MaskSlice[i] != SliceFront + i)
399           return false;
400       ScaledMask.push_back(SliceFront / Scale);
401     }
402     Mask = Mask.drop_front(Scale);
403   } while (!Mask.empty());
404 
405   assert((int)ScaledMask.size() * Scale == NumElts && "Unexpected scaled mask");
406 
407   // All elements of the original mask can be scaled down to map to the elements
408   // of a mask with wider elements.
409   return true;
410 }
411 
412 void llvm::getShuffleMaskWithWidestElts(ArrayRef<int> Mask,
413                                         SmallVectorImpl<int> &ScaledMask) {
414   std::array<SmallVector<int, 16>, 2> TmpMasks;
415   SmallVectorImpl<int> *Output = &TmpMasks[0], *Tmp = &TmpMasks[1];
416   ArrayRef<int> InputMask = Mask;
417   for (unsigned Scale = 2; Scale <= InputMask.size(); ++Scale) {
418     while (widenShuffleMaskElts(Scale, InputMask, *Output)) {
419       InputMask = *Output;
420       std::swap(Output, Tmp);
421     }
422   }
423   ScaledMask.assign(InputMask.begin(), InputMask.end());
424 }
425 
426 void llvm::processShuffleMasks(
427     ArrayRef<int> Mask, unsigned NumOfSrcRegs, unsigned NumOfDestRegs,
428     unsigned NumOfUsedRegs, function_ref<void()> NoInputAction,
429     function_ref<void(ArrayRef<int>, unsigned, unsigned)> SingleInputAction,
430     function_ref<void(ArrayRef<int>, unsigned, unsigned)> ManyInputsAction) {
431   SmallVector<SmallVector<SmallVector<int>>> Res(NumOfDestRegs);
432   // Try to perform better estimation of the permutation.
433   // 1. Split the source/destination vectors into real registers.
434   // 2. Do the mask analysis to identify which real registers are
435   // permuted.
436   int Sz = Mask.size();
437   unsigned SzDest = Sz / NumOfDestRegs;
438   unsigned SzSrc = Sz / NumOfSrcRegs;
439   for (unsigned I = 0; I < NumOfDestRegs; ++I) {
440     auto &RegMasks = Res[I];
441     RegMasks.assign(NumOfSrcRegs, {});
442     // Check that the values in dest registers are in the one src
443     // register.
444     for (unsigned K = 0; K < SzDest; ++K) {
445       int Idx = I * SzDest + K;
446       if (Idx == Sz)
447         break;
448       if (Mask[Idx] >= Sz || Mask[Idx] == PoisonMaskElem)
449         continue;
450       int SrcRegIdx = Mask[Idx] / SzSrc;
451       // Add a cost of PermuteTwoSrc for each new source register permute,
452       // if we have more than one source registers.
453       if (RegMasks[SrcRegIdx].empty())
454         RegMasks[SrcRegIdx].assign(SzDest, PoisonMaskElem);
455       RegMasks[SrcRegIdx][K] = Mask[Idx] % SzSrc;
456     }
457   }
458   // Process split mask.
459   for (unsigned I = 0; I < NumOfUsedRegs; ++I) {
460     auto &Dest = Res[I];
461     int NumSrcRegs =
462         count_if(Dest, [](ArrayRef<int> Mask) { return !Mask.empty(); });
463     switch (NumSrcRegs) {
464     case 0:
465       // No input vectors were used!
466       NoInputAction();
467       break;
468     case 1: {
469       // Find the only mask with at least single undef mask elem.
470       auto *It =
471           find_if(Dest, [](ArrayRef<int> Mask) { return !Mask.empty(); });
472       unsigned SrcReg = std::distance(Dest.begin(), It);
473       SingleInputAction(*It, SrcReg, I);
474       break;
475     }
476     default: {
477       // The first mask is a permutation of a single register. Since we have >2
478       // input registers to shuffle, we merge the masks for 2 first registers
479       // and generate a shuffle of 2 registers rather than the reordering of the
480       // first register and then shuffle with the second register. Next,
481       // generate the shuffles of the resulting register + the remaining
482       // registers from the list.
483       auto &&CombineMasks = [](MutableArrayRef<int> FirstMask,
484                                ArrayRef<int> SecondMask) {
485         for (int Idx = 0, VF = FirstMask.size(); Idx < VF; ++Idx) {
486           if (SecondMask[Idx] != PoisonMaskElem) {
487             assert(FirstMask[Idx] == PoisonMaskElem &&
488                    "Expected undefined mask element.");
489             FirstMask[Idx] = SecondMask[Idx] + VF;
490           }
491         }
492       };
493       auto &&NormalizeMask = [](MutableArrayRef<int> Mask) {
494         for (int Idx = 0, VF = Mask.size(); Idx < VF; ++Idx) {
495           if (Mask[Idx] != PoisonMaskElem)
496             Mask[Idx] = Idx;
497         }
498       };
499       int SecondIdx;
500       do {
501         int FirstIdx = -1;
502         SecondIdx = -1;
503         MutableArrayRef<int> FirstMask, SecondMask;
504         for (unsigned I = 0; I < NumOfDestRegs; ++I) {
505           SmallVectorImpl<int> &RegMask = Dest[I];
506           if (RegMask.empty())
507             continue;
508 
509           if (FirstIdx == SecondIdx) {
510             FirstIdx = I;
511             FirstMask = RegMask;
512             continue;
513           }
514           SecondIdx = I;
515           SecondMask = RegMask;
516           CombineMasks(FirstMask, SecondMask);
517           ManyInputsAction(FirstMask, FirstIdx, SecondIdx);
518           NormalizeMask(FirstMask);
519           RegMask.clear();
520           SecondMask = FirstMask;
521           SecondIdx = FirstIdx;
522         }
523         if (FirstIdx != SecondIdx && SecondIdx >= 0) {
524           CombineMasks(SecondMask, FirstMask);
525           ManyInputsAction(SecondMask, SecondIdx, FirstIdx);
526           Dest[FirstIdx].clear();
527           NormalizeMask(SecondMask);
528         }
529       } while (SecondIdx >= 0);
530       break;
531     }
532     }
533   }
534 }
535 
536 MapVector<Instruction *, uint64_t>
537 llvm::computeMinimumValueSizes(ArrayRef<BasicBlock *> Blocks, DemandedBits &DB,
538                                const TargetTransformInfo *TTI) {
539 
540   // DemandedBits will give us every value's live-out bits. But we want
541   // to ensure no extra casts would need to be inserted, so every DAG
542   // of connected values must have the same minimum bitwidth.
543   EquivalenceClasses<Value *> ECs;
544   SmallVector<Value *, 16> Worklist;
545   SmallPtrSet<Value *, 4> Roots;
546   SmallPtrSet<Value *, 16> Visited;
547   DenseMap<Value *, uint64_t> DBits;
548   SmallPtrSet<Instruction *, 4> InstructionSet;
549   MapVector<Instruction *, uint64_t> MinBWs;
550 
551   // Determine the roots. We work bottom-up, from truncs or icmps.
552   bool SeenExtFromIllegalType = false;
553   for (auto *BB : Blocks)
554     for (auto &I : *BB) {
555       InstructionSet.insert(&I);
556 
557       if (TTI && (isa<ZExtInst>(&I) || isa<SExtInst>(&I)) &&
558           !TTI->isTypeLegal(I.getOperand(0)->getType()))
559         SeenExtFromIllegalType = true;
560 
561       // Only deal with non-vector integers up to 64-bits wide.
562       if ((isa<TruncInst>(&I) || isa<ICmpInst>(&I)) &&
563           !I.getType()->isVectorTy() &&
564           I.getOperand(0)->getType()->getScalarSizeInBits() <= 64) {
565         // Don't make work for ourselves. If we know the loaded type is legal,
566         // don't add it to the worklist.
567         if (TTI && isa<TruncInst>(&I) && TTI->isTypeLegal(I.getType()))
568           continue;
569 
570         Worklist.push_back(&I);
571         Roots.insert(&I);
572       }
573     }
574   // Early exit.
575   if (Worklist.empty() || (TTI && !SeenExtFromIllegalType))
576     return MinBWs;
577 
578   // Now proceed breadth-first, unioning values together.
579   while (!Worklist.empty()) {
580     Value *Val = Worklist.pop_back_val();
581     Value *Leader = ECs.getOrInsertLeaderValue(Val);
582 
583     if (!Visited.insert(Val).second)
584       continue;
585 
586     // Non-instructions terminate a chain successfully.
587     if (!isa<Instruction>(Val))
588       continue;
589     Instruction *I = cast<Instruction>(Val);
590 
591     // If we encounter a type that is larger than 64 bits, we can't represent
592     // it so bail out.
593     if (DB.getDemandedBits(I).getBitWidth() > 64)
594       return MapVector<Instruction *, uint64_t>();
595 
596     uint64_t V = DB.getDemandedBits(I).getZExtValue();
597     DBits[Leader] |= V;
598     DBits[I] = V;
599 
600     // Casts, loads and instructions outside of our range terminate a chain
601     // successfully.
602     if (isa<SExtInst>(I) || isa<ZExtInst>(I) || isa<LoadInst>(I) ||
603         !InstructionSet.count(I))
604       continue;
605 
606     // Unsafe casts terminate a chain unsuccessfully. We can't do anything
607     // useful with bitcasts, ptrtoints or inttoptrs and it'd be unsafe to
608     // transform anything that relies on them.
609     if (isa<BitCastInst>(I) || isa<PtrToIntInst>(I) || isa<IntToPtrInst>(I) ||
610         !I->getType()->isIntegerTy()) {
611       DBits[Leader] |= ~0ULL;
612       continue;
613     }
614 
615     // We don't modify the types of PHIs. Reductions will already have been
616     // truncated if possible, and inductions' sizes will have been chosen by
617     // indvars.
618     if (isa<PHINode>(I))
619       continue;
620 
621     if (DBits[Leader] == ~0ULL)
622       // All bits demanded, no point continuing.
623       continue;
624 
625     for (Value *O : cast<User>(I)->operands()) {
626       ECs.unionSets(Leader, O);
627       Worklist.push_back(O);
628     }
629   }
630 
631   // Now we've discovered all values, walk them to see if there are
632   // any users we didn't see. If there are, we can't optimize that
633   // chain.
634   for (auto &I : DBits)
635     for (auto *U : I.first->users())
636       if (U->getType()->isIntegerTy() && DBits.count(U) == 0)
637         DBits[ECs.getOrInsertLeaderValue(I.first)] |= ~0ULL;
638 
639   for (auto I = ECs.begin(), E = ECs.end(); I != E; ++I) {
640     uint64_t LeaderDemandedBits = 0;
641     for (Value *M : llvm::make_range(ECs.member_begin(I), ECs.member_end()))
642       LeaderDemandedBits |= DBits[M];
643 
644     uint64_t MinBW = llvm::bit_width(LeaderDemandedBits);
645     // Round up to a power of 2
646     MinBW = llvm::bit_ceil(MinBW);
647 
648     // We don't modify the types of PHIs. Reductions will already have been
649     // truncated if possible, and inductions' sizes will have been chosen by
650     // indvars.
651     // If we are required to shrink a PHI, abandon this entire equivalence class.
652     bool Abort = false;
653     for (Value *M : llvm::make_range(ECs.member_begin(I), ECs.member_end()))
654       if (isa<PHINode>(M) && MinBW < M->getType()->getScalarSizeInBits()) {
655         Abort = true;
656         break;
657       }
658     if (Abort)
659       continue;
660 
661     for (Value *M : llvm::make_range(ECs.member_begin(I), ECs.member_end())) {
662       auto *MI = dyn_cast<Instruction>(M);
663       if (!MI)
664         continue;
665       Type *Ty = M->getType();
666       if (Roots.count(M))
667         Ty = MI->getOperand(0)->getType();
668 
669       if (MinBW >= Ty->getScalarSizeInBits())
670         continue;
671 
672       // If any of M's operands demand more bits than MinBW then M cannot be
673       // performed safely in MinBW.
674       if (any_of(MI->operands(), [&DB, MinBW](Use &U) {
675             auto *CI = dyn_cast<ConstantInt>(U);
676             // For constants shift amounts, check if the shift would result in
677             // poison.
678             if (CI &&
679                 isa<ShlOperator, LShrOperator, AShrOperator>(U.getUser()) &&
680                 U.getOperandNo() == 1)
681               return CI->uge(MinBW);
682             uint64_t BW = bit_width(DB.getDemandedBits(&U).getZExtValue());
683             return bit_ceil(BW) > MinBW;
684           }))
685         continue;
686 
687       MinBWs[MI] = MinBW;
688     }
689   }
690 
691   return MinBWs;
692 }
693 
694 /// Add all access groups in @p AccGroups to @p List.
695 template <typename ListT>
696 static void addToAccessGroupList(ListT &List, MDNode *AccGroups) {
697   // Interpret an access group as a list containing itself.
698   if (AccGroups->getNumOperands() == 0) {
699     assert(isValidAsAccessGroup(AccGroups) && "Node must be an access group");
700     List.insert(AccGroups);
701     return;
702   }
703 
704   for (const auto &AccGroupListOp : AccGroups->operands()) {
705     auto *Item = cast<MDNode>(AccGroupListOp.get());
706     assert(isValidAsAccessGroup(Item) && "List item must be an access group");
707     List.insert(Item);
708   }
709 }
710 
711 MDNode *llvm::uniteAccessGroups(MDNode *AccGroups1, MDNode *AccGroups2) {
712   if (!AccGroups1)
713     return AccGroups2;
714   if (!AccGroups2)
715     return AccGroups1;
716   if (AccGroups1 == AccGroups2)
717     return AccGroups1;
718 
719   SmallSetVector<Metadata *, 4> Union;
720   addToAccessGroupList(Union, AccGroups1);
721   addToAccessGroupList(Union, AccGroups2);
722 
723   if (Union.size() == 0)
724     return nullptr;
725   if (Union.size() == 1)
726     return cast<MDNode>(Union.front());
727 
728   LLVMContext &Ctx = AccGroups1->getContext();
729   return MDNode::get(Ctx, Union.getArrayRef());
730 }
731 
732 MDNode *llvm::intersectAccessGroups(const Instruction *Inst1,
733                                     const Instruction *Inst2) {
734   bool MayAccessMem1 = Inst1->mayReadOrWriteMemory();
735   bool MayAccessMem2 = Inst2->mayReadOrWriteMemory();
736 
737   if (!MayAccessMem1 && !MayAccessMem2)
738     return nullptr;
739   if (!MayAccessMem1)
740     return Inst2->getMetadata(LLVMContext::MD_access_group);
741   if (!MayAccessMem2)
742     return Inst1->getMetadata(LLVMContext::MD_access_group);
743 
744   MDNode *MD1 = Inst1->getMetadata(LLVMContext::MD_access_group);
745   MDNode *MD2 = Inst2->getMetadata(LLVMContext::MD_access_group);
746   if (!MD1 || !MD2)
747     return nullptr;
748   if (MD1 == MD2)
749     return MD1;
750 
751   // Use set for scalable 'contains' check.
752   SmallPtrSet<Metadata *, 4> AccGroupSet2;
753   addToAccessGroupList(AccGroupSet2, MD2);
754 
755   SmallVector<Metadata *, 4> Intersection;
756   if (MD1->getNumOperands() == 0) {
757     assert(isValidAsAccessGroup(MD1) && "Node must be an access group");
758     if (AccGroupSet2.count(MD1))
759       Intersection.push_back(MD1);
760   } else {
761     for (const MDOperand &Node : MD1->operands()) {
762       auto *Item = cast<MDNode>(Node.get());
763       assert(isValidAsAccessGroup(Item) && "List item must be an access group");
764       if (AccGroupSet2.count(Item))
765         Intersection.push_back(Item);
766     }
767   }
768 
769   if (Intersection.size() == 0)
770     return nullptr;
771   if (Intersection.size() == 1)
772     return cast<MDNode>(Intersection.front());
773 
774   LLVMContext &Ctx = Inst1->getContext();
775   return MDNode::get(Ctx, Intersection);
776 }
777 
778 /// \returns \p I after propagating metadata from \p VL.
779 Instruction *llvm::propagateMetadata(Instruction *Inst, ArrayRef<Value *> VL) {
780   if (VL.empty())
781     return Inst;
782   Instruction *I0 = cast<Instruction>(VL[0]);
783   SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
784   I0->getAllMetadataOtherThanDebugLoc(Metadata);
785 
786   for (auto Kind : {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
787                     LLVMContext::MD_noalias, LLVMContext::MD_fpmath,
788                     LLVMContext::MD_nontemporal, LLVMContext::MD_invariant_load,
789                     LLVMContext::MD_access_group}) {
790     MDNode *MD = I0->getMetadata(Kind);
791 
792     for (int J = 1, E = VL.size(); MD && J != E; ++J) {
793       const Instruction *IJ = cast<Instruction>(VL[J]);
794       MDNode *IMD = IJ->getMetadata(Kind);
795       switch (Kind) {
796       case LLVMContext::MD_tbaa:
797         MD = MDNode::getMostGenericTBAA(MD, IMD);
798         break;
799       case LLVMContext::MD_alias_scope:
800         MD = MDNode::getMostGenericAliasScope(MD, IMD);
801         break;
802       case LLVMContext::MD_fpmath:
803         MD = MDNode::getMostGenericFPMath(MD, IMD);
804         break;
805       case LLVMContext::MD_noalias:
806       case LLVMContext::MD_nontemporal:
807       case LLVMContext::MD_invariant_load:
808         MD = MDNode::intersect(MD, IMD);
809         break;
810       case LLVMContext::MD_access_group:
811         MD = intersectAccessGroups(Inst, IJ);
812         break;
813       default:
814         llvm_unreachable("unhandled metadata");
815       }
816     }
817 
818     Inst->setMetadata(Kind, MD);
819   }
820 
821   return Inst;
822 }
823 
824 Constant *
825 llvm::createBitMaskForGaps(IRBuilderBase &Builder, unsigned VF,
826                            const InterleaveGroup<Instruction> &Group) {
827   // All 1's means mask is not needed.
828   if (Group.getNumMembers() == Group.getFactor())
829     return nullptr;
830 
831   // TODO: support reversed access.
832   assert(!Group.isReverse() && "Reversed group not supported.");
833 
834   SmallVector<Constant *, 16> Mask;
835   for (unsigned i = 0; i < VF; i++)
836     for (unsigned j = 0; j < Group.getFactor(); ++j) {
837       unsigned HasMember = Group.getMember(j) ? 1 : 0;
838       Mask.push_back(Builder.getInt1(HasMember));
839     }
840 
841   return ConstantVector::get(Mask);
842 }
843 
844 llvm::SmallVector<int, 16>
845 llvm::createReplicatedMask(unsigned ReplicationFactor, unsigned VF) {
846   SmallVector<int, 16> MaskVec;
847   for (unsigned i = 0; i < VF; i++)
848     for (unsigned j = 0; j < ReplicationFactor; j++)
849       MaskVec.push_back(i);
850 
851   return MaskVec;
852 }
853 
854 llvm::SmallVector<int, 16> llvm::createInterleaveMask(unsigned VF,
855                                                       unsigned NumVecs) {
856   SmallVector<int, 16> Mask;
857   for (unsigned i = 0; i < VF; i++)
858     for (unsigned j = 0; j < NumVecs; j++)
859       Mask.push_back(j * VF + i);
860 
861   return Mask;
862 }
863 
864 llvm::SmallVector<int, 16>
865 llvm::createStrideMask(unsigned Start, unsigned Stride, unsigned VF) {
866   SmallVector<int, 16> Mask;
867   for (unsigned i = 0; i < VF; i++)
868     Mask.push_back(Start + i * Stride);
869 
870   return Mask;
871 }
872 
873 llvm::SmallVector<int, 16> llvm::createSequentialMask(unsigned Start,
874                                                       unsigned NumInts,
875                                                       unsigned NumUndefs) {
876   SmallVector<int, 16> Mask;
877   for (unsigned i = 0; i < NumInts; i++)
878     Mask.push_back(Start + i);
879 
880   for (unsigned i = 0; i < NumUndefs; i++)
881     Mask.push_back(-1);
882 
883   return Mask;
884 }
885 
886 llvm::SmallVector<int, 16> llvm::createUnaryMask(ArrayRef<int> Mask,
887                                                  unsigned NumElts) {
888   // Avoid casts in the loop and make sure we have a reasonable number.
889   int NumEltsSigned = NumElts;
890   assert(NumEltsSigned > 0 && "Expected smaller or non-zero element count");
891 
892   // If the mask chooses an element from operand 1, reduce it to choose from the
893   // corresponding element of operand 0. Undef mask elements are unchanged.
894   SmallVector<int, 16> UnaryMask;
895   for (int MaskElt : Mask) {
896     assert((MaskElt < NumEltsSigned * 2) && "Expected valid shuffle mask");
897     int UnaryElt = MaskElt >= NumEltsSigned ? MaskElt - NumEltsSigned : MaskElt;
898     UnaryMask.push_back(UnaryElt);
899   }
900   return UnaryMask;
901 }
902 
903 /// A helper function for concatenating vectors. This function concatenates two
904 /// vectors having the same element type. If the second vector has fewer
905 /// elements than the first, it is padded with undefs.
906 static Value *concatenateTwoVectors(IRBuilderBase &Builder, Value *V1,
907                                     Value *V2) {
908   VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType());
909   VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType());
910   assert(VecTy1 && VecTy2 &&
911          VecTy1->getScalarType() == VecTy2->getScalarType() &&
912          "Expect two vectors with the same element type");
913 
914   unsigned NumElts1 = cast<FixedVectorType>(VecTy1)->getNumElements();
915   unsigned NumElts2 = cast<FixedVectorType>(VecTy2)->getNumElements();
916   assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements");
917 
918   if (NumElts1 > NumElts2) {
919     // Extend with UNDEFs.
920     V2 = Builder.CreateShuffleVector(
921         V2, createSequentialMask(0, NumElts2, NumElts1 - NumElts2));
922   }
923 
924   return Builder.CreateShuffleVector(
925       V1, V2, createSequentialMask(0, NumElts1 + NumElts2, 0));
926 }
927 
928 Value *llvm::concatenateVectors(IRBuilderBase &Builder,
929                                 ArrayRef<Value *> Vecs) {
930   unsigned NumVecs = Vecs.size();
931   assert(NumVecs > 1 && "Should be at least two vectors");
932 
933   SmallVector<Value *, 8> ResList;
934   ResList.append(Vecs.begin(), Vecs.end());
935   do {
936     SmallVector<Value *, 8> TmpList;
937     for (unsigned i = 0; i < NumVecs - 1; i += 2) {
938       Value *V0 = ResList[i], *V1 = ResList[i + 1];
939       assert((V0->getType() == V1->getType() || i == NumVecs - 2) &&
940              "Only the last vector may have a different type");
941 
942       TmpList.push_back(concatenateTwoVectors(Builder, V0, V1));
943     }
944 
945     // Push the last vector if the total number of vectors is odd.
946     if (NumVecs % 2 != 0)
947       TmpList.push_back(ResList[NumVecs - 1]);
948 
949     ResList = TmpList;
950     NumVecs = ResList.size();
951   } while (NumVecs > 1);
952 
953   return ResList[0];
954 }
955 
956 bool llvm::maskIsAllZeroOrUndef(Value *Mask) {
957   assert(isa<VectorType>(Mask->getType()) &&
958          isa<IntegerType>(Mask->getType()->getScalarType()) &&
959          cast<IntegerType>(Mask->getType()->getScalarType())->getBitWidth() ==
960              1 &&
961          "Mask must be a vector of i1");
962 
963   auto *ConstMask = dyn_cast<Constant>(Mask);
964   if (!ConstMask)
965     return false;
966   if (ConstMask->isNullValue() || isa<UndefValue>(ConstMask))
967     return true;
968   if (isa<ScalableVectorType>(ConstMask->getType()))
969     return false;
970   for (unsigned
971            I = 0,
972            E = cast<FixedVectorType>(ConstMask->getType())->getNumElements();
973        I != E; ++I) {
974     if (auto *MaskElt = ConstMask->getAggregateElement(I))
975       if (MaskElt->isNullValue() || isa<UndefValue>(MaskElt))
976         continue;
977     return false;
978   }
979   return true;
980 }
981 
982 bool llvm::maskIsAllOneOrUndef(Value *Mask) {
983   assert(isa<VectorType>(Mask->getType()) &&
984          isa<IntegerType>(Mask->getType()->getScalarType()) &&
985          cast<IntegerType>(Mask->getType()->getScalarType())->getBitWidth() ==
986              1 &&
987          "Mask must be a vector of i1");
988 
989   auto *ConstMask = dyn_cast<Constant>(Mask);
990   if (!ConstMask)
991     return false;
992   if (ConstMask->isAllOnesValue() || isa<UndefValue>(ConstMask))
993     return true;
994   if (isa<ScalableVectorType>(ConstMask->getType()))
995     return false;
996   for (unsigned
997            I = 0,
998            E = cast<FixedVectorType>(ConstMask->getType())->getNumElements();
999        I != E; ++I) {
1000     if (auto *MaskElt = ConstMask->getAggregateElement(I))
1001       if (MaskElt->isAllOnesValue() || isa<UndefValue>(MaskElt))
1002         continue;
1003     return false;
1004   }
1005   return true;
1006 }
1007 
1008 /// TODO: This is a lot like known bits, but for
1009 /// vectors.  Is there something we can common this with?
1010 APInt llvm::possiblyDemandedEltsInMask(Value *Mask) {
1011   assert(isa<FixedVectorType>(Mask->getType()) &&
1012          isa<IntegerType>(Mask->getType()->getScalarType()) &&
1013          cast<IntegerType>(Mask->getType()->getScalarType())->getBitWidth() ==
1014              1 &&
1015          "Mask must be a fixed width vector of i1");
1016 
1017   const unsigned VWidth =
1018       cast<FixedVectorType>(Mask->getType())->getNumElements();
1019   APInt DemandedElts = APInt::getAllOnes(VWidth);
1020   if (auto *CV = dyn_cast<ConstantVector>(Mask))
1021     for (unsigned i = 0; i < VWidth; i++)
1022       if (CV->getAggregateElement(i)->isNullValue())
1023         DemandedElts.clearBit(i);
1024   return DemandedElts;
1025 }
1026 
1027 bool InterleavedAccessInfo::isStrided(int Stride) {
1028   unsigned Factor = std::abs(Stride);
1029   return Factor >= 2 && Factor <= MaxInterleaveGroupFactor;
1030 }
1031 
1032 void InterleavedAccessInfo::collectConstStrideAccesses(
1033     MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo,
1034     const DenseMap<Value*, const SCEV*> &Strides) {
1035   auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
1036 
1037   // Since it's desired that the load/store instructions be maintained in
1038   // "program order" for the interleaved access analysis, we have to visit the
1039   // blocks in the loop in reverse postorder (i.e., in a topological order).
1040   // Such an ordering will ensure that any load/store that may be executed
1041   // before a second load/store will precede the second load/store in
1042   // AccessStrideInfo.
1043   LoopBlocksDFS DFS(TheLoop);
1044   DFS.perform(LI);
1045   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO()))
1046     for (auto &I : *BB) {
1047       Value *Ptr = getLoadStorePointerOperand(&I);
1048       if (!Ptr)
1049         continue;
1050       Type *ElementTy = getLoadStoreType(&I);
1051 
1052       // Currently, codegen doesn't support cases where the type size doesn't
1053       // match the alloc size. Skip them for now.
1054       uint64_t Size = DL.getTypeAllocSize(ElementTy);
1055       if (Size * 8 != DL.getTypeSizeInBits(ElementTy))
1056         continue;
1057 
1058       // We don't check wrapping here because we don't know yet if Ptr will be
1059       // part of a full group or a group with gaps. Checking wrapping for all
1060       // pointers (even those that end up in groups with no gaps) will be overly
1061       // conservative. For full groups, wrapping should be ok since if we would
1062       // wrap around the address space we would do a memory access at nullptr
1063       // even without the transformation. The wrapping checks are therefore
1064       // deferred until after we've formed the interleaved groups.
1065       int64_t Stride =
1066         getPtrStride(PSE, ElementTy, Ptr, TheLoop, Strides,
1067                      /*Assume=*/true, /*ShouldCheckWrap=*/false).value_or(0);
1068 
1069       const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
1070       AccessStrideInfo[&I] = StrideDescriptor(Stride, Scev, Size,
1071                                               getLoadStoreAlignment(&I));
1072     }
1073 }
1074 
1075 // Analyze interleaved accesses and collect them into interleaved load and
1076 // store groups.
1077 //
1078 // When generating code for an interleaved load group, we effectively hoist all
1079 // loads in the group to the location of the first load in program order. When
1080 // generating code for an interleaved store group, we sink all stores to the
1081 // location of the last store. This code motion can change the order of load
1082 // and store instructions and may break dependences.
1083 //
1084 // The code generation strategy mentioned above ensures that we won't violate
1085 // any write-after-read (WAR) dependences.
1086 //
1087 // E.g., for the WAR dependence:  a = A[i];      // (1)
1088 //                                A[i] = b;      // (2)
1089 //
1090 // The store group of (2) is always inserted at or below (2), and the load
1091 // group of (1) is always inserted at or above (1). Thus, the instructions will
1092 // never be reordered. All other dependences are checked to ensure the
1093 // correctness of the instruction reordering.
1094 //
1095 // The algorithm visits all memory accesses in the loop in bottom-up program
1096 // order. Program order is established by traversing the blocks in the loop in
1097 // reverse postorder when collecting the accesses.
1098 //
1099 // We visit the memory accesses in bottom-up order because it can simplify the
1100 // construction of store groups in the presence of write-after-write (WAW)
1101 // dependences.
1102 //
1103 // E.g., for the WAW dependence:  A[i] = a;      // (1)
1104 //                                A[i] = b;      // (2)
1105 //                                A[i + 1] = c;  // (3)
1106 //
1107 // We will first create a store group with (3) and (2). (1) can't be added to
1108 // this group because it and (2) are dependent. However, (1) can be grouped
1109 // with other accesses that may precede it in program order. Note that a
1110 // bottom-up order does not imply that WAW dependences should not be checked.
1111 void InterleavedAccessInfo::analyzeInterleaving(
1112                                  bool EnablePredicatedInterleavedMemAccesses) {
1113   LLVM_DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
1114   const auto &Strides = LAI->getSymbolicStrides();
1115 
1116   // Holds all accesses with a constant stride.
1117   MapVector<Instruction *, StrideDescriptor> AccessStrideInfo;
1118   collectConstStrideAccesses(AccessStrideInfo, Strides);
1119 
1120   if (AccessStrideInfo.empty())
1121     return;
1122 
1123   // Collect the dependences in the loop.
1124   collectDependences();
1125 
1126   // Holds all interleaved store groups temporarily.
1127   SmallSetVector<InterleaveGroup<Instruction> *, 4> StoreGroups;
1128   // Holds all interleaved load groups temporarily.
1129   SmallSetVector<InterleaveGroup<Instruction> *, 4> LoadGroups;
1130   // Groups added to this set cannot have new members added.
1131   SmallPtrSet<InterleaveGroup<Instruction> *, 4> CompletedLoadGroups;
1132 
1133   // Search in bottom-up program order for pairs of accesses (A and B) that can
1134   // form interleaved load or store groups. In the algorithm below, access A
1135   // precedes access B in program order. We initialize a group for B in the
1136   // outer loop of the algorithm, and then in the inner loop, we attempt to
1137   // insert each A into B's group if:
1138   //
1139   //  1. A and B have the same stride,
1140   //  2. A and B have the same memory object size, and
1141   //  3. A belongs in B's group according to its distance from B.
1142   //
1143   // Special care is taken to ensure group formation will not break any
1144   // dependences.
1145   for (auto BI = AccessStrideInfo.rbegin(), E = AccessStrideInfo.rend();
1146        BI != E; ++BI) {
1147     Instruction *B = BI->first;
1148     StrideDescriptor DesB = BI->second;
1149 
1150     // Initialize a group for B if it has an allowable stride. Even if we don't
1151     // create a group for B, we continue with the bottom-up algorithm to ensure
1152     // we don't break any of B's dependences.
1153     InterleaveGroup<Instruction> *GroupB = nullptr;
1154     if (isStrided(DesB.Stride) &&
1155         (!isPredicated(B->getParent()) || EnablePredicatedInterleavedMemAccesses)) {
1156       GroupB = getInterleaveGroup(B);
1157       if (!GroupB) {
1158         LLVM_DEBUG(dbgs() << "LV: Creating an interleave group with:" << *B
1159                           << '\n');
1160         GroupB = createInterleaveGroup(B, DesB.Stride, DesB.Alignment);
1161       } else if (CompletedLoadGroups.contains(GroupB)) {
1162         // Skip B if no new instructions can be added to its load group.
1163         continue;
1164       }
1165       if (B->mayWriteToMemory())
1166         StoreGroups.insert(GroupB);
1167       else
1168         LoadGroups.insert(GroupB);
1169     }
1170 
1171     for (auto AI = std::next(BI); AI != E; ++AI) {
1172       Instruction *A = AI->first;
1173       StrideDescriptor DesA = AI->second;
1174 
1175       // Our code motion strategy implies that we can't have dependences
1176       // between accesses in an interleaved group and other accesses located
1177       // between the first and last member of the group. Note that this also
1178       // means that a group can't have more than one member at a given offset.
1179       // The accesses in a group can have dependences with other accesses, but
1180       // we must ensure we don't extend the boundaries of the group such that
1181       // we encompass those dependent accesses.
1182       //
1183       // For example, assume we have the sequence of accesses shown below in a
1184       // stride-2 loop:
1185       //
1186       //  (1, 2) is a group | A[i]   = a;  // (1)
1187       //                    | A[i-1] = b;  // (2) |
1188       //                      A[i-3] = c;  // (3)
1189       //                      A[i]   = d;  // (4) | (2, 4) is not a group
1190       //
1191       // Because accesses (2) and (3) are dependent, we can group (2) with (1)
1192       // but not with (4). If we did, the dependent access (3) would be within
1193       // the boundaries of the (2, 4) group.
1194       if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI)) {
1195         // If a dependence exists and A is already in a group, we know that A
1196         // must be a store since A precedes B and WAR dependences are allowed.
1197         // Thus, A would be sunk below B. We release A's group to prevent this
1198         // illegal code motion. A will then be free to form another group with
1199         // instructions that precede it.
1200         if (isInterleaved(A)) {
1201           InterleaveGroup<Instruction> *StoreGroup = getInterleaveGroup(A);
1202 
1203           LLVM_DEBUG(dbgs() << "LV: Invalidated store group due to "
1204                                "dependence between " << *A << " and "<< *B << '\n');
1205 
1206           StoreGroups.remove(StoreGroup);
1207           releaseGroup(StoreGroup);
1208         }
1209         // If B is a load and part of an interleave group, no earlier loads can
1210         // be added to B's interleave group, because this would mean the load B
1211         // would need to be moved across store A. Mark the interleave group as
1212         // complete.
1213         if (GroupB && isa<LoadInst>(B)) {
1214           LLVM_DEBUG(dbgs() << "LV: Marking interleave group for " << *B
1215                             << " as complete.\n");
1216 
1217           CompletedLoadGroups.insert(GroupB);
1218         }
1219 
1220         // If a dependence exists and A is not already in a group (or it was
1221         // and we just released it), B might be hoisted above A (if B is a
1222         // load) or another store might be sunk below A (if B is a store). In
1223         // either case, we can't add additional instructions to B's group. B
1224         // will only form a group with instructions that it precedes.
1225         break;
1226       }
1227 
1228       // At this point, we've checked for illegal code motion. If either A or B
1229       // isn't strided, there's nothing left to do.
1230       if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride))
1231         continue;
1232 
1233       // Ignore A if it's already in a group or isn't the same kind of memory
1234       // operation as B.
1235       // Note that mayReadFromMemory() isn't mutually exclusive to
1236       // mayWriteToMemory in the case of atomic loads. We shouldn't see those
1237       // here, canVectorizeMemory() should have returned false - except for the
1238       // case we asked for optimization remarks.
1239       if (isInterleaved(A) ||
1240           (A->mayReadFromMemory() != B->mayReadFromMemory()) ||
1241           (A->mayWriteToMemory() != B->mayWriteToMemory()))
1242         continue;
1243 
1244       // Check rules 1 and 2. Ignore A if its stride or size is different from
1245       // that of B.
1246       if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size)
1247         continue;
1248 
1249       // Ignore A if the memory object of A and B don't belong to the same
1250       // address space
1251       if (getLoadStoreAddressSpace(A) != getLoadStoreAddressSpace(B))
1252         continue;
1253 
1254       // Calculate the distance from A to B.
1255       const SCEVConstant *DistToB = dyn_cast<SCEVConstant>(
1256           PSE.getSE()->getMinusSCEV(DesA.Scev, DesB.Scev));
1257       if (!DistToB)
1258         continue;
1259       int64_t DistanceToB = DistToB->getAPInt().getSExtValue();
1260 
1261       // Check rule 3. Ignore A if its distance to B is not a multiple of the
1262       // size.
1263       if (DistanceToB % static_cast<int64_t>(DesB.Size))
1264         continue;
1265 
1266       // All members of a predicated interleave-group must have the same predicate,
1267       // and currently must reside in the same BB.
1268       BasicBlock *BlockA = A->getParent();
1269       BasicBlock *BlockB = B->getParent();
1270       if ((isPredicated(BlockA) || isPredicated(BlockB)) &&
1271           (!EnablePredicatedInterleavedMemAccesses || BlockA != BlockB))
1272         continue;
1273 
1274       // The index of A is the index of B plus A's distance to B in multiples
1275       // of the size.
1276       int IndexA =
1277           GroupB->getIndex(B) + DistanceToB / static_cast<int64_t>(DesB.Size);
1278 
1279       // Try to insert A into B's group.
1280       if (GroupB->insertMember(A, IndexA, DesA.Alignment)) {
1281         LLVM_DEBUG(dbgs() << "LV: Inserted:" << *A << '\n'
1282                           << "    into the interleave group with" << *B
1283                           << '\n');
1284         InterleaveGroupMap[A] = GroupB;
1285 
1286         // Set the first load in program order as the insert position.
1287         if (A->mayReadFromMemory())
1288           GroupB->setInsertPos(A);
1289       }
1290     } // Iteration over A accesses.
1291   }   // Iteration over B accesses.
1292 
1293   auto InvalidateGroupIfMemberMayWrap = [&](InterleaveGroup<Instruction> *Group,
1294                                             int Index,
1295                                             std::string FirstOrLast) -> bool {
1296     Instruction *Member = Group->getMember(Index);
1297     assert(Member && "Group member does not exist");
1298     Value *MemberPtr = getLoadStorePointerOperand(Member);
1299     Type *AccessTy = getLoadStoreType(Member);
1300     if (getPtrStride(PSE, AccessTy, MemberPtr, TheLoop, Strides,
1301                      /*Assume=*/false, /*ShouldCheckWrap=*/true).value_or(0))
1302       return false;
1303     LLVM_DEBUG(dbgs() << "LV: Invalidate candidate interleaved group due to "
1304                       << FirstOrLast
1305                       << " group member potentially pointer-wrapping.\n");
1306     releaseGroup(Group);
1307     return true;
1308   };
1309 
1310   // Remove interleaved groups with gaps whose memory
1311   // accesses may wrap around. We have to revisit the getPtrStride analysis,
1312   // this time with ShouldCheckWrap=true, since collectConstStrideAccesses does
1313   // not check wrapping (see documentation there).
1314   // FORNOW we use Assume=false;
1315   // TODO: Change to Assume=true but making sure we don't exceed the threshold
1316   // of runtime SCEV assumptions checks (thereby potentially failing to
1317   // vectorize altogether).
1318   // Additional optional optimizations:
1319   // TODO: If we are peeling the loop and we know that the first pointer doesn't
1320   // wrap then we can deduce that all pointers in the group don't wrap.
1321   // This means that we can forcefully peel the loop in order to only have to
1322   // check the first pointer for no-wrap. When we'll change to use Assume=true
1323   // we'll only need at most one runtime check per interleaved group.
1324   for (auto *Group : LoadGroups) {
1325     // Case 1: A full group. Can Skip the checks; For full groups, if the wide
1326     // load would wrap around the address space we would do a memory access at
1327     // nullptr even without the transformation.
1328     if (Group->getNumMembers() == Group->getFactor())
1329       continue;
1330 
1331     // Case 2: If first and last members of the group don't wrap this implies
1332     // that all the pointers in the group don't wrap.
1333     // So we check only group member 0 (which is always guaranteed to exist),
1334     // and group member Factor - 1; If the latter doesn't exist we rely on
1335     // peeling (if it is a non-reversed accsess -- see Case 3).
1336     if (InvalidateGroupIfMemberMayWrap(Group, 0, std::string("first")))
1337       continue;
1338     if (Group->getMember(Group->getFactor() - 1))
1339       InvalidateGroupIfMemberMayWrap(Group, Group->getFactor() - 1,
1340                                      std::string("last"));
1341     else {
1342       // Case 3: A non-reversed interleaved load group with gaps: We need
1343       // to execute at least one scalar epilogue iteration. This will ensure
1344       // we don't speculatively access memory out-of-bounds. We only need
1345       // to look for a member at index factor - 1, since every group must have
1346       // a member at index zero.
1347       if (Group->isReverse()) {
1348         LLVM_DEBUG(
1349             dbgs() << "LV: Invalidate candidate interleaved group due to "
1350                       "a reverse access with gaps.\n");
1351         releaseGroup(Group);
1352         continue;
1353       }
1354       LLVM_DEBUG(
1355           dbgs() << "LV: Interleaved group requires epilogue iteration.\n");
1356       RequiresScalarEpilogue = true;
1357     }
1358   }
1359 
1360   for (auto *Group : StoreGroups) {
1361     // Case 1: A full group. Can Skip the checks; For full groups, if the wide
1362     // store would wrap around the address space we would do a memory access at
1363     // nullptr even without the transformation.
1364     if (Group->getNumMembers() == Group->getFactor())
1365       continue;
1366 
1367     // Interleave-store-group with gaps is implemented using masked wide store.
1368     // Remove interleaved store groups with gaps if
1369     // masked-interleaved-accesses are not enabled by the target.
1370     if (!EnablePredicatedInterleavedMemAccesses) {
1371       LLVM_DEBUG(
1372           dbgs() << "LV: Invalidate candidate interleaved store group due "
1373                     "to gaps.\n");
1374       releaseGroup(Group);
1375       continue;
1376     }
1377 
1378     // Case 2: If first and last members of the group don't wrap this implies
1379     // that all the pointers in the group don't wrap.
1380     // So we check only group member 0 (which is always guaranteed to exist),
1381     // and the last group member. Case 3 (scalar epilog) is not relevant for
1382     // stores with gaps, which are implemented with masked-store (rather than
1383     // speculative access, as in loads).
1384     if (InvalidateGroupIfMemberMayWrap(Group, 0, std::string("first")))
1385       continue;
1386     for (int Index = Group->getFactor() - 1; Index > 0; Index--)
1387       if (Group->getMember(Index)) {
1388         InvalidateGroupIfMemberMayWrap(Group, Index, std::string("last"));
1389         break;
1390       }
1391   }
1392 }
1393 
1394 void InterleavedAccessInfo::invalidateGroupsRequiringScalarEpilogue() {
1395   // If no group had triggered the requirement to create an epilogue loop,
1396   // there is nothing to do.
1397   if (!requiresScalarEpilogue())
1398     return;
1399 
1400   bool ReleasedGroup = false;
1401   // Release groups requiring scalar epilogues. Note that this also removes them
1402   // from InterleaveGroups.
1403   for (auto *Group : make_early_inc_range(InterleaveGroups)) {
1404     if (!Group->requiresScalarEpilogue())
1405       continue;
1406     LLVM_DEBUG(
1407         dbgs()
1408         << "LV: Invalidate candidate interleaved group due to gaps that "
1409            "require a scalar epilogue (not allowed under optsize) and cannot "
1410            "be masked (not enabled). \n");
1411     releaseGroup(Group);
1412     ReleasedGroup = true;
1413   }
1414   assert(ReleasedGroup && "At least one group must be invalidated, as a "
1415                           "scalar epilogue was required");
1416   (void)ReleasedGroup;
1417   RequiresScalarEpilogue = false;
1418 }
1419 
1420 template <typename InstT>
1421 void InterleaveGroup<InstT>::addMetadata(InstT *NewInst) const {
1422   llvm_unreachable("addMetadata can only be used for Instruction");
1423 }
1424 
1425 namespace llvm {
1426 template <>
1427 void InterleaveGroup<Instruction>::addMetadata(Instruction *NewInst) const {
1428   SmallVector<Value *, 4> VL;
1429   std::transform(Members.begin(), Members.end(), std::back_inserter(VL),
1430                  [](std::pair<int, Instruction *> p) { return p.second; });
1431   propagateMetadata(NewInst, VL);
1432 }
1433 }
1434 
1435 std::string VFABI::mangleTLIVectorName(StringRef VectorName,
1436                                        StringRef ScalarName, unsigned numArgs,
1437                                        ElementCount VF, bool Masked) {
1438   SmallString<256> Buffer;
1439   llvm::raw_svector_ostream Out(Buffer);
1440   Out << "_ZGV" << VFABI::_LLVM_ << (Masked ? "M" : "N");
1441   if (VF.isScalable())
1442     Out << 'x';
1443   else
1444     Out << VF.getFixedValue();
1445   for (unsigned I = 0; I < numArgs; ++I)
1446     Out << "v";
1447   Out << "_" << ScalarName << "(" << VectorName << ")";
1448   return std::string(Out.str());
1449 }
1450 
1451 void VFABI::getVectorVariantNames(
1452     const CallInst &CI, SmallVectorImpl<std::string> &VariantMappings) {
1453   const StringRef S = CI.getFnAttr(VFABI::MappingsAttrName).getValueAsString();
1454   if (S.empty())
1455     return;
1456 
1457   SmallVector<StringRef, 8> ListAttr;
1458   S.split(ListAttr, ",");
1459 
1460   for (const auto &S : SetVector<StringRef>(ListAttr.begin(), ListAttr.end())) {
1461 #ifndef NDEBUG
1462     LLVM_DEBUG(dbgs() << "VFABI: adding mapping '" << S << "'\n");
1463     std::optional<VFInfo> Info =
1464         VFABI::tryDemangleForVFABI(S, *(CI.getModule()));
1465     assert(Info && "Invalid name for a VFABI variant.");
1466     assert(CI.getModule()->getFunction(Info->VectorName) &&
1467            "Vector function is missing.");
1468 #endif
1469     VariantMappings.push_back(std::string(S));
1470   }
1471 }
1472 
1473 bool VFShape::hasValidParameterList() const {
1474   for (unsigned Pos = 0, NumParams = Parameters.size(); Pos < NumParams;
1475        ++Pos) {
1476     assert(Parameters[Pos].ParamPos == Pos && "Broken parameter list.");
1477 
1478     switch (Parameters[Pos].ParamKind) {
1479     default: // Nothing to check.
1480       break;
1481     case VFParamKind::OMP_Linear:
1482     case VFParamKind::OMP_LinearRef:
1483     case VFParamKind::OMP_LinearVal:
1484     case VFParamKind::OMP_LinearUVal:
1485       // Compile time linear steps must be non-zero.
1486       if (Parameters[Pos].LinearStepOrPos == 0)
1487         return false;
1488       break;
1489     case VFParamKind::OMP_LinearPos:
1490     case VFParamKind::OMP_LinearRefPos:
1491     case VFParamKind::OMP_LinearValPos:
1492     case VFParamKind::OMP_LinearUValPos:
1493       // The runtime linear step must be referring to some other
1494       // parameters in the signature.
1495       if (Parameters[Pos].LinearStepOrPos >= int(NumParams))
1496         return false;
1497       // The linear step parameter must be marked as uniform.
1498       if (Parameters[Parameters[Pos].LinearStepOrPos].ParamKind !=
1499           VFParamKind::OMP_Uniform)
1500         return false;
1501       // The linear step parameter can't point at itself.
1502       if (Parameters[Pos].LinearStepOrPos == int(Pos))
1503         return false;
1504       break;
1505     case VFParamKind::GlobalPredicate:
1506       // The global predicate must be the unique. Can be placed anywhere in the
1507       // signature.
1508       for (unsigned NextPos = Pos + 1; NextPos < NumParams; ++NextPos)
1509         if (Parameters[NextPos].ParamKind == VFParamKind::GlobalPredicate)
1510           return false;
1511       break;
1512     }
1513   }
1514   return true;
1515 }
1516