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