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