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