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