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 const llvm::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   auto *ConstMask = dyn_cast<Constant>(Mask);
867   if (!ConstMask)
868     return false;
869   if (ConstMask->isNullValue() || isa<UndefValue>(ConstMask))
870     return true;
871   for (unsigned
872            I = 0,
873            E = cast<FixedVectorType>(ConstMask->getType())->getNumElements();
874        I != E; ++I) {
875     if (auto *MaskElt = ConstMask->getAggregateElement(I))
876       if (MaskElt->isNullValue() || isa<UndefValue>(MaskElt))
877         continue;
878     return false;
879   }
880   return true;
881 }
882 
883 
884 bool llvm::maskIsAllOneOrUndef(Value *Mask) {
885   auto *ConstMask = dyn_cast<Constant>(Mask);
886   if (!ConstMask)
887     return false;
888   if (ConstMask->isAllOnesValue() || isa<UndefValue>(ConstMask))
889     return true;
890   for (unsigned
891            I = 0,
892            E = cast<FixedVectorType>(ConstMask->getType())->getNumElements();
893        I != E; ++I) {
894     if (auto *MaskElt = ConstMask->getAggregateElement(I))
895       if (MaskElt->isAllOnesValue() || isa<UndefValue>(MaskElt))
896         continue;
897     return false;
898   }
899   return true;
900 }
901 
902 /// TODO: This is a lot like known bits, but for
903 /// vectors.  Is there something we can common this with?
904 APInt llvm::possiblyDemandedEltsInMask(Value *Mask) {
905 
906   const unsigned VWidth =
907       cast<FixedVectorType>(Mask->getType())->getNumElements();
908   APInt DemandedElts = APInt::getAllOnesValue(VWidth);
909   if (auto *CV = dyn_cast<ConstantVector>(Mask))
910     for (unsigned i = 0; i < VWidth; i++)
911       if (CV->getAggregateElement(i)->isNullValue())
912         DemandedElts.clearBit(i);
913   return DemandedElts;
914 }
915 
916 bool InterleavedAccessInfo::isStrided(int Stride) {
917   unsigned Factor = std::abs(Stride);
918   return Factor >= 2 && Factor <= MaxInterleaveGroupFactor;
919 }
920 
921 void InterleavedAccessInfo::collectConstStrideAccesses(
922     MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo,
923     const ValueToValueMap &Strides) {
924   auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
925 
926   // Since it's desired that the load/store instructions be maintained in
927   // "program order" for the interleaved access analysis, we have to visit the
928   // blocks in the loop in reverse postorder (i.e., in a topological order).
929   // Such an ordering will ensure that any load/store that may be executed
930   // before a second load/store will precede the second load/store in
931   // AccessStrideInfo.
932   LoopBlocksDFS DFS(TheLoop);
933   DFS.perform(LI);
934   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO()))
935     for (auto &I : *BB) {
936       auto *LI = dyn_cast<LoadInst>(&I);
937       auto *SI = dyn_cast<StoreInst>(&I);
938       if (!LI && !SI)
939         continue;
940 
941       Value *Ptr = getLoadStorePointerOperand(&I);
942       // We don't check wrapping here because we don't know yet if Ptr will be
943       // part of a full group or a group with gaps. Checking wrapping for all
944       // pointers (even those that end up in groups with no gaps) will be overly
945       // conservative. For full groups, wrapping should be ok since if we would
946       // wrap around the address space we would do a memory access at nullptr
947       // even without the transformation. The wrapping checks are therefore
948       // deferred until after we've formed the interleaved groups.
949       int64_t Stride = getPtrStride(PSE, Ptr, TheLoop, Strides,
950                                     /*Assume=*/true, /*ShouldCheckWrap=*/false);
951 
952       const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
953       PointerType *PtrTy = cast<PointerType>(Ptr->getType());
954       uint64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
955       AccessStrideInfo[&I] = StrideDescriptor(Stride, Scev, Size,
956                                               getLoadStoreAlignment(&I));
957     }
958 }
959 
960 // Analyze interleaved accesses and collect them into interleaved load and
961 // store groups.
962 //
963 // When generating code for an interleaved load group, we effectively hoist all
964 // loads in the group to the location of the first load in program order. When
965 // generating code for an interleaved store group, we sink all stores to the
966 // location of the last store. This code motion can change the order of load
967 // and store instructions and may break dependences.
968 //
969 // The code generation strategy mentioned above ensures that we won't violate
970 // any write-after-read (WAR) dependences.
971 //
972 // E.g., for the WAR dependence:  a = A[i];      // (1)
973 //                                A[i] = b;      // (2)
974 //
975 // The store group of (2) is always inserted at or below (2), and the load
976 // group of (1) is always inserted at or above (1). Thus, the instructions will
977 // never be reordered. All other dependences are checked to ensure the
978 // correctness of the instruction reordering.
979 //
980 // The algorithm visits all memory accesses in the loop in bottom-up program
981 // order. Program order is established by traversing the blocks in the loop in
982 // reverse postorder when collecting the accesses.
983 //
984 // We visit the memory accesses in bottom-up order because it can simplify the
985 // construction of store groups in the presence of write-after-write (WAW)
986 // dependences.
987 //
988 // E.g., for the WAW dependence:  A[i] = a;      // (1)
989 //                                A[i] = b;      // (2)
990 //                                A[i + 1] = c;  // (3)
991 //
992 // We will first create a store group with (3) and (2). (1) can't be added to
993 // this group because it and (2) are dependent. However, (1) can be grouped
994 // with other accesses that may precede it in program order. Note that a
995 // bottom-up order does not imply that WAW dependences should not be checked.
996 void InterleavedAccessInfo::analyzeInterleaving(
997                                  bool EnablePredicatedInterleavedMemAccesses) {
998   LLVM_DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
999   const ValueToValueMap &Strides = LAI->getSymbolicStrides();
1000 
1001   // Holds all accesses with a constant stride.
1002   MapVector<Instruction *, StrideDescriptor> AccessStrideInfo;
1003   collectConstStrideAccesses(AccessStrideInfo, Strides);
1004 
1005   if (AccessStrideInfo.empty())
1006     return;
1007 
1008   // Collect the dependences in the loop.
1009   collectDependences();
1010 
1011   // Holds all interleaved store groups temporarily.
1012   SmallSetVector<InterleaveGroup<Instruction> *, 4> StoreGroups;
1013   // Holds all interleaved load groups temporarily.
1014   SmallSetVector<InterleaveGroup<Instruction> *, 4> LoadGroups;
1015 
1016   // Search in bottom-up program order for pairs of accesses (A and B) that can
1017   // form interleaved load or store groups. In the algorithm below, access A
1018   // precedes access B in program order. We initialize a group for B in the
1019   // outer loop of the algorithm, and then in the inner loop, we attempt to
1020   // insert each A into B's group if:
1021   //
1022   //  1. A and B have the same stride,
1023   //  2. A and B have the same memory object size, and
1024   //  3. A belongs in B's group according to its distance from B.
1025   //
1026   // Special care is taken to ensure group formation will not break any
1027   // dependences.
1028   for (auto BI = AccessStrideInfo.rbegin(), E = AccessStrideInfo.rend();
1029        BI != E; ++BI) {
1030     Instruction *B = BI->first;
1031     StrideDescriptor DesB = BI->second;
1032 
1033     // Initialize a group for B if it has an allowable stride. Even if we don't
1034     // create a group for B, we continue with the bottom-up algorithm to ensure
1035     // we don't break any of B's dependences.
1036     InterleaveGroup<Instruction> *Group = nullptr;
1037     if (isStrided(DesB.Stride) &&
1038         (!isPredicated(B->getParent()) || EnablePredicatedInterleavedMemAccesses)) {
1039       Group = getInterleaveGroup(B);
1040       if (!Group) {
1041         LLVM_DEBUG(dbgs() << "LV: Creating an interleave group with:" << *B
1042                           << '\n');
1043         Group = createInterleaveGroup(B, DesB.Stride, DesB.Alignment);
1044       }
1045       if (B->mayWriteToMemory())
1046         StoreGroups.insert(Group);
1047       else
1048         LoadGroups.insert(Group);
1049     }
1050 
1051     for (auto AI = std::next(BI); AI != E; ++AI) {
1052       Instruction *A = AI->first;
1053       StrideDescriptor DesA = AI->second;
1054 
1055       // Our code motion strategy implies that we can't have dependences
1056       // between accesses in an interleaved group and other accesses located
1057       // between the first and last member of the group. Note that this also
1058       // means that a group can't have more than one member at a given offset.
1059       // The accesses in a group can have dependences with other accesses, but
1060       // we must ensure we don't extend the boundaries of the group such that
1061       // we encompass those dependent accesses.
1062       //
1063       // For example, assume we have the sequence of accesses shown below in a
1064       // stride-2 loop:
1065       //
1066       //  (1, 2) is a group | A[i]   = a;  // (1)
1067       //                    | A[i-1] = b;  // (2) |
1068       //                      A[i-3] = c;  // (3)
1069       //                      A[i]   = d;  // (4) | (2, 4) is not a group
1070       //
1071       // Because accesses (2) and (3) are dependent, we can group (2) with (1)
1072       // but not with (4). If we did, the dependent access (3) would be within
1073       // the boundaries of the (2, 4) group.
1074       if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI)) {
1075         // If a dependence exists and A is already in a group, we know that A
1076         // must be a store since A precedes B and WAR dependences are allowed.
1077         // Thus, A would be sunk below B. We release A's group to prevent this
1078         // illegal code motion. A will then be free to form another group with
1079         // instructions that precede it.
1080         if (isInterleaved(A)) {
1081           InterleaveGroup<Instruction> *StoreGroup = getInterleaveGroup(A);
1082 
1083           LLVM_DEBUG(dbgs() << "LV: Invalidated store group due to "
1084                                "dependence between " << *A << " and "<< *B << '\n');
1085 
1086           StoreGroups.remove(StoreGroup);
1087           releaseGroup(StoreGroup);
1088         }
1089 
1090         // If a dependence exists and A is not already in a group (or it was
1091         // and we just released it), B might be hoisted above A (if B is a
1092         // load) or another store might be sunk below A (if B is a store). In
1093         // either case, we can't add additional instructions to B's group. B
1094         // will only form a group with instructions that it precedes.
1095         break;
1096       }
1097 
1098       // At this point, we've checked for illegal code motion. If either A or B
1099       // isn't strided, there's nothing left to do.
1100       if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride))
1101         continue;
1102 
1103       // Ignore A if it's already in a group or isn't the same kind of memory
1104       // operation as B.
1105       // Note that mayReadFromMemory() isn't mutually exclusive to
1106       // mayWriteToMemory in the case of atomic loads. We shouldn't see those
1107       // here, canVectorizeMemory() should have returned false - except for the
1108       // case we asked for optimization remarks.
1109       if (isInterleaved(A) ||
1110           (A->mayReadFromMemory() != B->mayReadFromMemory()) ||
1111           (A->mayWriteToMemory() != B->mayWriteToMemory()))
1112         continue;
1113 
1114       // Check rules 1 and 2. Ignore A if its stride or size is different from
1115       // that of B.
1116       if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size)
1117         continue;
1118 
1119       // Ignore A if the memory object of A and B don't belong to the same
1120       // address space
1121       if (getLoadStoreAddressSpace(A) != getLoadStoreAddressSpace(B))
1122         continue;
1123 
1124       // Calculate the distance from A to B.
1125       const SCEVConstant *DistToB = dyn_cast<SCEVConstant>(
1126           PSE.getSE()->getMinusSCEV(DesA.Scev, DesB.Scev));
1127       if (!DistToB)
1128         continue;
1129       int64_t DistanceToB = DistToB->getAPInt().getSExtValue();
1130 
1131       // Check rule 3. Ignore A if its distance to B is not a multiple of the
1132       // size.
1133       if (DistanceToB % static_cast<int64_t>(DesB.Size))
1134         continue;
1135 
1136       // All members of a predicated interleave-group must have the same predicate,
1137       // and currently must reside in the same BB.
1138       BasicBlock *BlockA = A->getParent();
1139       BasicBlock *BlockB = B->getParent();
1140       if ((isPredicated(BlockA) || isPredicated(BlockB)) &&
1141           (!EnablePredicatedInterleavedMemAccesses || BlockA != BlockB))
1142         continue;
1143 
1144       // The index of A is the index of B plus A's distance to B in multiples
1145       // of the size.
1146       int IndexA =
1147           Group->getIndex(B) + DistanceToB / static_cast<int64_t>(DesB.Size);
1148 
1149       // Try to insert A into B's group.
1150       if (Group->insertMember(A, IndexA, DesA.Alignment)) {
1151         LLVM_DEBUG(dbgs() << "LV: Inserted:" << *A << '\n'
1152                           << "    into the interleave group with" << *B
1153                           << '\n');
1154         InterleaveGroupMap[A] = Group;
1155 
1156         // Set the first load in program order as the insert position.
1157         if (A->mayReadFromMemory())
1158           Group->setInsertPos(A);
1159       }
1160     } // Iteration over A accesses.
1161   }   // Iteration over B accesses.
1162 
1163   // Remove interleaved store groups with gaps.
1164   for (auto *Group : StoreGroups)
1165     if (Group->getNumMembers() != Group->getFactor()) {
1166       LLVM_DEBUG(
1167           dbgs() << "LV: Invalidate candidate interleaved store group due "
1168                     "to gaps.\n");
1169       releaseGroup(Group);
1170     }
1171   // Remove interleaved groups with gaps (currently only loads) whose memory
1172   // accesses may wrap around. We have to revisit the getPtrStride analysis,
1173   // this time with ShouldCheckWrap=true, since collectConstStrideAccesses does
1174   // not check wrapping (see documentation there).
1175   // FORNOW we use Assume=false;
1176   // TODO: Change to Assume=true but making sure we don't exceed the threshold
1177   // of runtime SCEV assumptions checks (thereby potentially failing to
1178   // vectorize altogether).
1179   // Additional optional optimizations:
1180   // TODO: If we are peeling the loop and we know that the first pointer doesn't
1181   // wrap then we can deduce that all pointers in the group don't wrap.
1182   // This means that we can forcefully peel the loop in order to only have to
1183   // check the first pointer for no-wrap. When we'll change to use Assume=true
1184   // we'll only need at most one runtime check per interleaved group.
1185   for (auto *Group : LoadGroups) {
1186     // Case 1: A full group. Can Skip the checks; For full groups, if the wide
1187     // load would wrap around the address space we would do a memory access at
1188     // nullptr even without the transformation.
1189     if (Group->getNumMembers() == Group->getFactor())
1190       continue;
1191 
1192     // Case 2: If first and last members of the group don't wrap this implies
1193     // that all the pointers in the group don't wrap.
1194     // So we check only group member 0 (which is always guaranteed to exist),
1195     // and group member Factor - 1; If the latter doesn't exist we rely on
1196     // peeling (if it is a non-reversed accsess -- see Case 3).
1197     Value *FirstMemberPtr = getLoadStorePointerOperand(Group->getMember(0));
1198     if (!getPtrStride(PSE, FirstMemberPtr, TheLoop, Strides, /*Assume=*/false,
1199                       /*ShouldCheckWrap=*/true)) {
1200       LLVM_DEBUG(
1201           dbgs() << "LV: Invalidate candidate interleaved group due to "
1202                     "first group member potentially pointer-wrapping.\n");
1203       releaseGroup(Group);
1204       continue;
1205     }
1206     Instruction *LastMember = Group->getMember(Group->getFactor() - 1);
1207     if (LastMember) {
1208       Value *LastMemberPtr = getLoadStorePointerOperand(LastMember);
1209       if (!getPtrStride(PSE, LastMemberPtr, TheLoop, Strides, /*Assume=*/false,
1210                         /*ShouldCheckWrap=*/true)) {
1211         LLVM_DEBUG(
1212             dbgs() << "LV: Invalidate candidate interleaved group due to "
1213                       "last group member potentially pointer-wrapping.\n");
1214         releaseGroup(Group);
1215       }
1216     } else {
1217       // Case 3: A non-reversed interleaved load group with gaps: We need
1218       // to execute at least one scalar epilogue iteration. This will ensure
1219       // we don't speculatively access memory out-of-bounds. We only need
1220       // to look for a member at index factor - 1, since every group must have
1221       // a member at index zero.
1222       if (Group->isReverse()) {
1223         LLVM_DEBUG(
1224             dbgs() << "LV: Invalidate candidate interleaved group due to "
1225                       "a reverse access with gaps.\n");
1226         releaseGroup(Group);
1227         continue;
1228       }
1229       LLVM_DEBUG(
1230           dbgs() << "LV: Interleaved group requires epilogue iteration.\n");
1231       RequiresScalarEpilogue = true;
1232     }
1233   }
1234 }
1235 
1236 void InterleavedAccessInfo::invalidateGroupsRequiringScalarEpilogue() {
1237   // If no group had triggered the requirement to create an epilogue loop,
1238   // there is nothing to do.
1239   if (!requiresScalarEpilogue())
1240     return;
1241 
1242   bool ReleasedGroup = false;
1243   // Release groups requiring scalar epilogues. Note that this also removes them
1244   // from InterleaveGroups.
1245   for (auto *Group : make_early_inc_range(InterleaveGroups)) {
1246     if (!Group->requiresScalarEpilogue())
1247       continue;
1248     LLVM_DEBUG(
1249         dbgs()
1250         << "LV: Invalidate candidate interleaved group due to gaps that "
1251            "require a scalar epilogue (not allowed under optsize) and cannot "
1252            "be masked (not enabled). \n");
1253     releaseGroup(Group);
1254     ReleasedGroup = true;
1255   }
1256   assert(ReleasedGroup && "At least one group must be invalidated, as a "
1257                           "scalar epilogue was required");
1258   (void)ReleasedGroup;
1259   RequiresScalarEpilogue = false;
1260 }
1261 
1262 template <typename InstT>
1263 void InterleaveGroup<InstT>::addMetadata(InstT *NewInst) const {
1264   llvm_unreachable("addMetadata can only be used for Instruction");
1265 }
1266 
1267 namespace llvm {
1268 template <>
1269 void InterleaveGroup<Instruction>::addMetadata(Instruction *NewInst) const {
1270   SmallVector<Value *, 4> VL;
1271   std::transform(Members.begin(), Members.end(), std::back_inserter(VL),
1272                  [](std::pair<int, Instruction *> p) { return p.second; });
1273   propagateMetadata(NewInst, VL);
1274 }
1275 }
1276 
1277 std::string VFABI::mangleTLIVectorName(StringRef VectorName,
1278                                        StringRef ScalarName, unsigned numArgs,
1279                                        unsigned VF) {
1280   SmallString<256> Buffer;
1281   llvm::raw_svector_ostream Out(Buffer);
1282   Out << "_ZGV" << VFABI::_LLVM_ << "N" << VF;
1283   for (unsigned I = 0; I < numArgs; ++I)
1284     Out << "v";
1285   Out << "_" << ScalarName << "(" << VectorName << ")";
1286   return std::string(Out.str());
1287 }
1288 
1289 void VFABI::getVectorVariantNames(
1290     const CallInst &CI, SmallVectorImpl<std::string> &VariantMappings) {
1291   const StringRef S =
1292       CI.getAttribute(AttributeList::FunctionIndex, VFABI::MappingsAttrName)
1293           .getValueAsString();
1294   if (S.empty())
1295     return;
1296 
1297   SmallVector<StringRef, 8> ListAttr;
1298   S.split(ListAttr, ",");
1299 
1300   for (auto &S : SetVector<StringRef>(ListAttr.begin(), ListAttr.end())) {
1301 #ifndef NDEBUG
1302     LLVM_DEBUG(dbgs() << "VFABI: adding mapping '" << S << "'\n");
1303     Optional<VFInfo> Info = VFABI::tryDemangleForVFABI(S, *(CI.getModule()));
1304     assert(Info.hasValue() && "Invalid name for a VFABI variant.");
1305     assert(CI.getModule()->getFunction(Info.getValue().VectorName) &&
1306            "Vector function is missing.");
1307 #endif
1308     VariantMappings.push_back(std::string(S));
1309   }
1310 }
1311 
1312 bool VFShape::hasValidParameterList() const {
1313   for (unsigned Pos = 0, NumParams = Parameters.size(); Pos < NumParams;
1314        ++Pos) {
1315     assert(Parameters[Pos].ParamPos == Pos && "Broken parameter list.");
1316 
1317     switch (Parameters[Pos].ParamKind) {
1318     default: // Nothing to check.
1319       break;
1320     case VFParamKind::OMP_Linear:
1321     case VFParamKind::OMP_LinearRef:
1322     case VFParamKind::OMP_LinearVal:
1323     case VFParamKind::OMP_LinearUVal:
1324       // Compile time linear steps must be non-zero.
1325       if (Parameters[Pos].LinearStepOrPos == 0)
1326         return false;
1327       break;
1328     case VFParamKind::OMP_LinearPos:
1329     case VFParamKind::OMP_LinearRefPos:
1330     case VFParamKind::OMP_LinearValPos:
1331     case VFParamKind::OMP_LinearUValPos:
1332       // The runtime linear step must be referring to some other
1333       // parameters in the signature.
1334       if (Parameters[Pos].LinearStepOrPos >= int(NumParams))
1335         return false;
1336       // The linear step parameter must be marked as uniform.
1337       if (Parameters[Parameters[Pos].LinearStepOrPos].ParamKind !=
1338           VFParamKind::OMP_Uniform)
1339         return false;
1340       // The linear step parameter can't point at itself.
1341       if (Parameters[Pos].LinearStepOrPos == int(Pos))
1342         return false;
1343       break;
1344     case VFParamKind::GlobalPredicate:
1345       // The global predicate must be the unique. Can be placed anywhere in the
1346       // signature.
1347       for (unsigned NextPos = Pos + 1; NextPos < NumParams; ++NextPos)
1348         if (Parameters[NextPos].ParamKind == VFParamKind::GlobalPredicate)
1349           return false;
1350       break;
1351     }
1352   }
1353   return true;
1354 }
1355