LLVM 24.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
23#include "llvm/IR/Constants.h"
25#include "llvm/IR/IRBuilder.h"
28#include "llvm/IR/Value.h"
30
31#define DEBUG_TYPE "vectorutils"
32
33using namespace llvm;
34using namespace llvm::PatternMatch;
35
36/// Maximum factor for an interleaved memory access.
38 "max-interleave-group-factor", cl::Hidden,
39 cl::desc("Maximum factor for an interleaved access group (default = 8)"),
40 cl::init(8));
41
42/// Return true if all of the intrinsic's arguments and return type are scalars
43/// for the scalar form of the intrinsic, and vectors for the vector form of the
44/// intrinsic (except operands that are marked as always being scalar by
45/// isVectorIntrinsicWithScalarOpAtArg).
47 switch (ID) {
48 case Intrinsic::abs: // Begin integer bit-manipulation.
49 case Intrinsic::bswap:
50 case Intrinsic::bitreverse:
51 case Intrinsic::ctpop:
52 case Intrinsic::ctlz:
53 case Intrinsic::cttz:
54 case Intrinsic::fshl:
55 case Intrinsic::fshr:
56 case Intrinsic::smax:
57 case Intrinsic::smin:
58 case Intrinsic::umax:
59 case Intrinsic::umin:
60 case Intrinsic::sadd_sat:
61 case Intrinsic::ssub_sat:
62 case Intrinsic::uadd_sat:
63 case Intrinsic::usub_sat:
64 case Intrinsic::smul_fix:
65 case Intrinsic::smul_fix_sat:
66 case Intrinsic::umul_fix:
67 case Intrinsic::umul_fix_sat:
68 case Intrinsic::uadd_with_overflow:
69 case Intrinsic::sadd_with_overflow:
70 case Intrinsic::usub_with_overflow:
71 case Intrinsic::ssub_with_overflow:
72 case Intrinsic::umul_with_overflow:
73 case Intrinsic::smul_with_overflow:
74 case Intrinsic::sqrt: // Begin floating-point.
75 case Intrinsic::asin:
76 case Intrinsic::acos:
77 case Intrinsic::atan:
78 case Intrinsic::atan2:
79 case Intrinsic::sin:
80 case Intrinsic::cos:
81 case Intrinsic::sincos:
82 case Intrinsic::sincospi:
83 case Intrinsic::tan:
84 case Intrinsic::sinh:
85 case Intrinsic::cosh:
86 case Intrinsic::tanh:
87 case Intrinsic::exp:
88 case Intrinsic::exp10:
89 case Intrinsic::exp2:
90 case Intrinsic::frexp:
91 case Intrinsic::ldexp:
92 case Intrinsic::log:
93 case Intrinsic::log10:
94 case Intrinsic::log2:
95 case Intrinsic::fabs:
96 case Intrinsic::minnum:
97 case Intrinsic::maxnum:
98 case Intrinsic::minimum:
99 case Intrinsic::maximum:
100 case Intrinsic::minimumnum:
101 case Intrinsic::maximumnum:
102 case Intrinsic::modf:
103 case Intrinsic::copysign:
104 case Intrinsic::floor:
105 case Intrinsic::ceil:
106 case Intrinsic::trunc:
107 case Intrinsic::rint:
108 case Intrinsic::nearbyint:
109 case Intrinsic::round:
110 case Intrinsic::roundeven:
111 case Intrinsic::pow:
112 case Intrinsic::fma:
113 case Intrinsic::fmuladd:
114 case Intrinsic::is_fpclass:
115 case Intrinsic::powi:
116 case Intrinsic::canonicalize:
117 case Intrinsic::fptosi_sat:
118 case Intrinsic::fptoui_sat:
119 case Intrinsic::lround:
120 case Intrinsic::llround:
121 case Intrinsic::lrint:
122 case Intrinsic::llrint:
123 case Intrinsic::ucmp:
124 case Intrinsic::scmp:
125 case Intrinsic::clmul:
126 case Intrinsic::smulh:
127 case Intrinsic::umulh:
128 return true;
129 default:
130 return false;
131 }
132}
133
136 return true;
137
139}
140
141/// Identifies if the vector form of the intrinsic has a scalar operand.
143 unsigned ScalarOpdIdx,
144 const TargetTransformInfo *TTI) {
145
147 return TTI->isTargetIntrinsicWithScalarOpAtArg(ID, ScalarOpdIdx);
148
149 // Vector predication intrinsics have the EVL as the last operand.
150 if (VPIntrinsic::getVectorLengthParamPos(ID) == ScalarOpdIdx)
151 return true;
152
153 switch (ID) {
154 case Intrinsic::abs:
155 case Intrinsic::ctlz:
156 case Intrinsic::cttz:
157 case Intrinsic::is_fpclass:
158 case Intrinsic::powi:
159 case Intrinsic::vector_extract:
160 return (ScalarOpdIdx == 1);
161 case Intrinsic::smul_fix:
162 case Intrinsic::smul_fix_sat:
163 case Intrinsic::umul_fix:
164 case Intrinsic::umul_fix_sat:
165 case Intrinsic::vector_splice_left:
166 case Intrinsic::vector_splice_right:
167 return (ScalarOpdIdx == 2);
168 case Intrinsic::experimental_vp_splice:
169 return ScalarOpdIdx == 2 || ScalarOpdIdx == 4;
170 case Intrinsic::experimental_vp_strided_load:
171 return ScalarOpdIdx == 0 || ScalarOpdIdx == 1;
172 case Intrinsic::experimental_vp_strided_store:
173 return ScalarOpdIdx == 1 || ScalarOpdIdx == 2;
174 case Intrinsic::loop_dependence_war_mask:
175 return true;
176 default:
177 return false;
178 }
179}
180
182 Intrinsic::ID ID, int OpdIdx, const TargetTransformInfo *TTI) {
183 assert(ID != Intrinsic::not_intrinsic && "Not an intrinsic!");
184
186 return TTI->isTargetIntrinsicWithOverloadTypeAtArg(ID, OpdIdx);
187
188 switch (ID) {
189 case Intrinsic::fptosi_sat:
190 case Intrinsic::fptoui_sat:
191 case Intrinsic::lround:
192 case Intrinsic::llround:
193 case Intrinsic::lrint:
194 case Intrinsic::llrint:
195 case Intrinsic::ucmp:
196 case Intrinsic::scmp:
197 case Intrinsic::vector_extract:
198 case Intrinsic::loop_dependence_war_mask:
199 return OpdIdx == -1 || OpdIdx == 0;
200 case Intrinsic::modf:
201 case Intrinsic::sincos:
202 case Intrinsic::sincospi:
203 case Intrinsic::is_fpclass:
204 return OpdIdx == 0;
205 case Intrinsic::powi:
206 case Intrinsic::ldexp:
207 return OpdIdx == -1 || OpdIdx == 1;
208 case Intrinsic::experimental_vp_strided_load:
209 return OpdIdx == -1 || OpdIdx == 0 || OpdIdx == 1;
210 case Intrinsic::experimental_vp_strided_store:
211 return OpdIdx == 0 || OpdIdx == 1 || OpdIdx == 2;
212 default:
213 return OpdIdx == -1;
214 }
215}
216
218 Intrinsic::ID ID, int RetIdx, const TargetTransformInfo *TTI) {
219
221 return TTI->isTargetIntrinsicWithStructReturnOverloadAtField(ID, RetIdx);
222
223 switch (ID) {
224 case Intrinsic::frexp:
225 return RetIdx == 0 || RetIdx == 1;
226 default:
227 return RetIdx == 0;
228 }
229}
230
231/// Returns intrinsic ID for call.
232/// For the input call instruction it finds mapping intrinsic and returns
233/// its ID, in case it does not found it return not_intrinsic.
235 const TargetLibraryInfo *TLI) {
237 if (ID == Intrinsic::not_intrinsic)
239
240 if (isTriviallyVectorizable(ID) || ID == Intrinsic::lifetime_start ||
241 ID == Intrinsic::lifetime_end || ID == Intrinsic::assume ||
242 ID == Intrinsic::experimental_noalias_scope_decl ||
243 ID == Intrinsic::sideeffect || ID == Intrinsic::pseudoprobe)
244 return ID;
246}
247
249 switch (ID) {
250 case Intrinsic::vector_interleave2:
251 return 2;
252 case Intrinsic::vector_interleave3:
253 return 3;
254 case Intrinsic::vector_interleave4:
255 return 4;
256 case Intrinsic::vector_interleave5:
257 return 5;
258 case Intrinsic::vector_interleave6:
259 return 6;
260 case Intrinsic::vector_interleave7:
261 return 7;
262 case Intrinsic::vector_interleave8:
263 return 8;
264 default:
265 return 0;
266 }
267}
268
270 switch (ID) {
271 case Intrinsic::vector_deinterleave2:
272 return 2;
273 case Intrinsic::vector_deinterleave3:
274 return 3;
275 case Intrinsic::vector_deinterleave4:
276 return 4;
277 case Intrinsic::vector_deinterleave5:
278 return 5;
279 case Intrinsic::vector_deinterleave6:
280 return 6;
281 case Intrinsic::vector_deinterleave7:
282 return 7;
283 case Intrinsic::vector_deinterleave8:
284 return 8;
285 default:
286 return 0;
287 }
288}
289
291 [[maybe_unused]] unsigned Factor =
293 ArrayRef<Type *> DISubtypes = DI->getType()->subtypes();
294 assert(Factor && Factor == DISubtypes.size() &&
295 "unexpected deinterleave factor or result type");
296 return cast<VectorType>(DISubtypes[0]);
297}
298
299/// Given a vector and an element number, see if the scalar value is
300/// already around as a register, for example if it were inserted then extracted
301/// from the vector.
302Value *llvm::findScalarElement(Value *V, unsigned EltNo) {
303 assert(V->getType()->isVectorTy() && "Not looking at a vector?");
304 VectorType *VTy = cast<VectorType>(V->getType());
305 // For fixed-length vector, return poison for out of range access.
306 if (auto *FVTy = dyn_cast<FixedVectorType>(VTy)) {
307 unsigned Width = FVTy->getNumElements();
308 if (EltNo >= Width)
309 return PoisonValue::get(FVTy->getElementType());
310 }
311
312 if (Constant *C = dyn_cast<Constant>(V))
313 return C->getAggregateElement(EltNo);
314
316 // If this is an insert to a variable element, we don't know what it is.
317 uint64_t IIElt;
318 if (!match(III->getOperand(2), m_ConstantInt(IIElt)))
319 return nullptr;
320
321 // If this is an insert to the element we are looking for, return the
322 // inserted value.
323 if (EltNo == IIElt)
324 return III->getOperand(1);
325
326 // Guard against infinite loop on malformed, unreachable IR.
327 if (III == III->getOperand(0))
328 return nullptr;
329
330 // Otherwise, the insertelement doesn't modify the value, recurse on its
331 // vector input.
332 return findScalarElement(III->getOperand(0), EltNo);
333 }
334
336 // Restrict the following transformation to fixed-length vector.
337 if (SVI && isa<FixedVectorType>(SVI->getType())) {
338 unsigned LHSWidth =
339 cast<FixedVectorType>(SVI->getOperand(0)->getType())->getNumElements();
340 int InEl = SVI->getMaskValue(EltNo);
341 if (InEl < 0)
342 return PoisonValue::get(VTy->getElementType());
343 if (InEl < (int)LHSWidth)
344 return findScalarElement(SVI->getOperand(0), InEl);
345 return findScalarElement(SVI->getOperand(1), InEl - LHSWidth);
346 }
347
348 // Extract a value from a vector add operation with a constant zero.
349 // TODO: Use getBinOpIdentity() to generalize this.
350 Value *Val; Constant *C;
351 if (match(V, m_Add(m_Value(Val), m_Constant(C))))
352 if (Constant *Elt = C->getAggregateElement(EltNo))
353 if (Elt->isNullValue())
354 return findScalarElement(Val, EltNo);
355
356 // If the vector is a splat then we can trivially find the scalar element.
358 if (Value *Splat = getSplatValue(V))
359 if (EltNo < VTy->getElementCount().getKnownMinValue())
360 return Splat;
361
362 // Otherwise, we don't know.
363 return nullptr;
364}
365
367 int SplatIndex = -1;
368 for (int M : Mask) {
369 // Ignore invalid (undefined) mask elements.
370 if (M < 0)
371 continue;
372
373 // There can be only 1 non-negative mask element value if this is a splat.
374 if (SplatIndex != -1 && SplatIndex != M)
375 return -1;
376
377 // Initialize the splat index to the 1st non-negative mask element.
378 SplatIndex = M;
379 }
380 assert((SplatIndex == -1 || SplatIndex >= 0) && "Negative index?");
381 return SplatIndex;
382}
383
384/// Get splat value if the input is a splat vector or return nullptr.
385/// This function is not fully general. It checks only 2 cases:
386/// the input value is (1) a splat constant vector or (2) a sequence
387/// of instructions that broadcasts a scalar at element 0.
389 if (isa<VectorType>(V->getType()))
390 if (auto *C = dyn_cast<Constant>(V))
391 return C->getSplatValue();
392
393 // shuf (inselt ?, Splat, 0), ?, <0, undef, 0, ...>
394 Value *Splat;
395 if (match(V,
397 m_Value(), m_ZeroMask())))
398 return Splat;
399
400 return nullptr;
401}
402
403bool llvm::isSplatValue(const Value *V, int Index, unsigned Depth) {
404 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
405
406 if (isa<VectorType>(V->getType())) {
407 if (isa<UndefValue>(V))
408 return true;
409 // FIXME: We can allow undefs, but if Index was specified, we may want to
410 // check that the constant is defined at that index.
411 if (auto *C = dyn_cast<Constant>(V))
412 return C->getSplatValue() != nullptr;
413 }
414
415 if (auto *Shuf = dyn_cast<ShuffleVectorInst>(V)) {
416 // FIXME: We can safely allow undefs here. If Index was specified, we will
417 // check that the mask elt is defined at the required index.
418 if (!all_equal(Shuf->getShuffleMask()))
419 return false;
420
421 // Match any index.
422 if (Index == -1)
423 return true;
424
425 // Match a specific element. The mask should be defined at and match the
426 // specified index.
427 return Shuf->getMaskValue(Index) == Index;
428 }
429
430 // The remaining tests are all recursive, so bail out if we hit the limit.
432 return false;
433
434 // If both operands of a binop are splats, the result is a splat.
435 Value *X, *Y, *Z;
436 if (match(V, m_BinOp(m_Value(X), m_Value(Y))))
437 return isSplatValue(X, Index, Depth) && isSplatValue(Y, Index, Depth);
438
439 // If all operands of a select are splats, the result is a splat.
440 if (match(V, m_Select(m_Value(X), m_Value(Y), m_Value(Z))))
441 return isSplatValue(X, Index, Depth) && isSplatValue(Y, Index, Depth) &&
442 isSplatValue(Z, Index, Depth);
443
444 // TODO: Add support for unary ops (fneg), casts, intrinsics (overflow ops).
445
446 return false;
447}
448
450 const APInt &DemandedElts, APInt &DemandedLHS,
451 APInt &DemandedRHS, bool AllowUndefElts) {
452 DemandedLHS = DemandedRHS = APInt::getZero(SrcWidth);
453
454 // Early out if we don't demand any elements.
455 if (DemandedElts.isZero())
456 return true;
457
458 // Simple case of a shuffle with zeroinitializer.
459 if (all_of(Mask, equal_to(0))) {
460 DemandedLHS.setBit(0);
461 return true;
462 }
463
464 for (unsigned I = 0, E = Mask.size(); I != E; ++I) {
465 int M = Mask[I];
466 assert((-1 <= M) && (M < (SrcWidth * 2)) &&
467 "Invalid shuffle mask constant");
468
469 if (!DemandedElts[I] || (AllowUndefElts && (M < 0)))
470 continue;
471
472 // For undef elements, we don't know anything about the common state of
473 // the shuffle result.
474 if (M < 0)
475 return false;
476
477 if (M < SrcWidth)
478 DemandedLHS.setBit(M);
479 else
480 DemandedRHS.setBit(M - SrcWidth);
481 }
482
483 return true;
484}
485
487 std::array<std::pair<int, int>, 2> &SrcInfo) {
488 const int SignalValue = NumElts * 2;
489 SrcInfo[0] = {-1, SignalValue};
490 SrcInfo[1] = {-1, SignalValue};
491 for (auto [i, M] : enumerate(Mask)) {
492 if (M < 0)
493 continue;
494 int Src = M >= NumElts;
495 int Diff = (int)i - (M % NumElts);
496 bool Match = false;
497 for (int j = 0; j < 2; j++) {
498 auto &[SrcE, DiffE] = SrcInfo[j];
499 if (SrcE == -1) {
500 assert(DiffE == SignalValue);
501 SrcE = Src;
502 DiffE = Diff;
503 }
504 if (SrcE == Src && DiffE == Diff) {
505 Match = true;
506 break;
507 }
508 }
509 if (!Match)
510 return false;
511 }
512 // Avoid all undef masks
513 return SrcInfo[0].first != -1;
514}
515
517 SmallVectorImpl<int> &ScaledMask) {
518 assert(Scale > 0 && "Unexpected scaling factor");
519
520 // Fast-path: if no scaling, then it is just a copy.
521 if (Scale == 1) {
522 ScaledMask.assign(Mask.begin(), Mask.end());
523 return;
524 }
525
526 ScaledMask.clear();
527 for (int MaskElt : Mask) {
528 if (MaskElt >= 0) {
529 assert(((uint64_t)Scale * MaskElt + (Scale - 1)) <= INT32_MAX &&
530 "Overflowed 32-bits");
531 }
532 for (int SliceElt = 0; SliceElt != Scale; ++SliceElt)
533 ScaledMask.push_back(MaskElt < 0 ? MaskElt : Scale * MaskElt + SliceElt);
534 }
535}
536
538 SmallVectorImpl<int> &ScaledMask) {
539 assert(Scale > 0 && "Unexpected scaling factor");
540
541 // Fast-path: if no scaling, then it is just a copy.
542 if (Scale == 1) {
543 ScaledMask.assign(Mask.begin(), Mask.end());
544 return true;
545 }
546
547 // We must map the original elements down evenly to a type with less elements.
548 int NumElts = Mask.size();
549 if (NumElts % Scale != 0)
550 return false;
551
552 ScaledMask.clear();
553 ScaledMask.reserve(NumElts / Scale);
554
555 // Step through the input mask by splitting into Scale-sized slices.
556 do {
557 ArrayRef<int> MaskSlice = Mask.take_front(Scale);
558 assert((int)MaskSlice.size() == Scale && "Expected Scale-sized slice.");
559
560 // The first element of the slice determines how we evaluate this slice.
561 int SliceFront = MaskSlice.front();
562 if (SliceFront < 0) {
563 // Negative values (undef or other "sentinel" values) must be equal across
564 // the entire slice.
565 if (!all_equal(MaskSlice))
566 return false;
567 ScaledMask.push_back(SliceFront);
568 } else {
569 // A positive mask element must be cleanly divisible.
570 if (SliceFront % Scale != 0)
571 return false;
572 // Elements of the slice must be consecutive.
573 for (int i = 1; i < Scale; ++i)
574 if (MaskSlice[i] != SliceFront + i)
575 return false;
576 ScaledMask.push_back(SliceFront / Scale);
577 }
578 Mask = Mask.drop_front(Scale);
579 } while (!Mask.empty());
580
581 assert((int)ScaledMask.size() * Scale == NumElts && "Unexpected scaled mask");
582
583 // All elements of the original mask can be scaled down to map to the elements
584 // of a mask with wider elements.
585 return true;
586}
587
589 SmallVectorImpl<int> &NewMask) {
590 unsigned NumElts = M.size();
591 if (NumElts % 2 != 0)
592 return false;
593
594 NewMask.clear();
595 for (unsigned i = 0; i < NumElts; i += 2) {
596 int M0 = M[i];
597 int M1 = M[i + 1];
598
599 // If both elements are undef, new mask is undef too.
600 if (M0 == -1 && M1 == -1) {
601 NewMask.push_back(-1);
602 continue;
603 }
604
605 if (M0 == -1 && M1 != -1 && (M1 % 2) == 1) {
606 NewMask.push_back(M1 / 2);
607 continue;
608 }
609
610 if (M0 != -1 && (M0 % 2) == 0 && ((M0 + 1) == M1 || M1 == -1)) {
611 NewMask.push_back(M0 / 2);
612 continue;
613 }
614
615 NewMask.clear();
616 return false;
617 }
618
619 assert(NewMask.size() == NumElts / 2 && "Incorrect size for mask!");
620 return true;
621}
622
623bool llvm::scaleShuffleMaskElts(unsigned NumDstElts, ArrayRef<int> Mask,
624 SmallVectorImpl<int> &ScaledMask) {
625 unsigned NumSrcElts = Mask.size();
626 assert(NumSrcElts > 0 && NumDstElts > 0 && "Unexpected scaling factor");
627
628 // Fast-path: if no scaling, then it is just a copy.
629 if (NumSrcElts == NumDstElts) {
630 ScaledMask.assign(Mask.begin(), Mask.end());
631 return true;
632 }
633
634 // Ensure we can find a whole scale factor.
635 assert(((NumSrcElts % NumDstElts) == 0 || (NumDstElts % NumSrcElts) == 0) &&
636 "Unexpected scaling factor");
637
638 if (NumSrcElts > NumDstElts) {
639 int Scale = NumSrcElts / NumDstElts;
640 return widenShuffleMaskElts(Scale, Mask, ScaledMask);
641 }
642
643 int Scale = NumDstElts / NumSrcElts;
644 narrowShuffleMaskElts(Scale, Mask, ScaledMask);
645 return true;
646}
647
649 SmallVectorImpl<int> &ScaledMask) {
650 std::array<SmallVector<int, 16>, 2> TmpMasks;
651 SmallVectorImpl<int> *Output = &TmpMasks[0], *Tmp = &TmpMasks[1];
652 ArrayRef<int> InputMask = Mask;
653 for (unsigned Scale = 2; Scale <= InputMask.size(); ++Scale) {
654 while (widenShuffleMaskElts(Scale, InputMask, *Output)) {
655 InputMask = *Output;
656 std::swap(Output, Tmp);
657 }
658 }
659 ScaledMask.assign(InputMask.begin(), InputMask.end());
660}
661
663 ArrayRef<int> Mask, unsigned NumOfSrcRegs, unsigned NumOfDestRegs,
664 unsigned NumOfUsedRegs, function_ref<void()> NoInputAction,
665 function_ref<void(ArrayRef<int>, unsigned, unsigned)> SingleInputAction,
666 function_ref<void(ArrayRef<int>, unsigned, unsigned, bool)>
667 ManyInputsAction) {
668 SmallVector<SmallVector<SmallVector<int>>> Res(NumOfDestRegs);
669 // Try to perform better estimation of the permutation.
670 // 1. Split the source/destination vectors into real registers.
671 // 2. Do the mask analysis to identify which real registers are
672 // permuted.
673 int Sz = Mask.size();
674 unsigned SzDest = Sz / NumOfDestRegs;
675 unsigned SzSrc = Sz / NumOfSrcRegs;
676 for (unsigned I = 0; I < NumOfDestRegs; ++I) {
677 auto &RegMasks = Res[I];
678 RegMasks.assign(2 * NumOfSrcRegs, {});
679 // Check that the values in dest registers are in the one src
680 // register.
681 for (unsigned K = 0; K < SzDest; ++K) {
682 int Idx = I * SzDest + K;
683 if (Idx == Sz)
684 break;
685 if (Mask[Idx] >= 2 * Sz || Mask[Idx] == PoisonMaskElem)
686 continue;
687 int MaskIdx = Mask[Idx] % Sz;
688 int SrcRegIdx = MaskIdx / SzSrc + (Mask[Idx] >= Sz ? NumOfSrcRegs : 0);
689 // Add a cost of PermuteTwoSrc for each new source register permute,
690 // if we have more than one source registers.
691 if (RegMasks[SrcRegIdx].empty())
692 RegMasks[SrcRegIdx].assign(SzDest, PoisonMaskElem);
693 RegMasks[SrcRegIdx][K] = MaskIdx % SzSrc;
694 }
695 }
696 // Process split mask.
697 for (unsigned I : seq<unsigned>(NumOfUsedRegs)) {
698 auto &Dest = Res[I];
699 int NumSrcRegs =
700 count_if(Dest, [](ArrayRef<int> Mask) { return !Mask.empty(); });
701 switch (NumSrcRegs) {
702 case 0:
703 // No input vectors were used!
704 NoInputAction();
705 break;
706 case 1: {
707 // Find the only mask with at least single undef mask elem.
708 auto *It =
709 find_if(Dest, [](ArrayRef<int> Mask) { return !Mask.empty(); });
710 unsigned SrcReg = std::distance(Dest.begin(), It);
711 SingleInputAction(*It, SrcReg, I);
712 break;
713 }
714 default: {
715 // The first mask is a permutation of a single register. Since we have >2
716 // input registers to shuffle, we merge the masks for 2 first registers
717 // and generate a shuffle of 2 registers rather than the reordering of the
718 // first register and then shuffle with the second register. Next,
719 // generate the shuffles of the resulting register + the remaining
720 // registers from the list.
721 auto &&CombineMasks = [](MutableArrayRef<int> FirstMask,
722 ArrayRef<int> SecondMask) {
723 for (int Idx = 0, VF = FirstMask.size(); Idx < VF; ++Idx) {
724 if (SecondMask[Idx] != PoisonMaskElem) {
725 assert(FirstMask[Idx] == PoisonMaskElem &&
726 "Expected undefined mask element.");
727 FirstMask[Idx] = SecondMask[Idx] + VF;
728 }
729 }
730 };
731 auto &&NormalizeMask = [](MutableArrayRef<int> Mask) {
732 for (int Idx = 0, VF = Mask.size(); Idx < VF; ++Idx) {
733 if (Mask[Idx] != PoisonMaskElem)
734 Mask[Idx] = Idx;
735 }
736 };
737 int SecondIdx;
738 bool NewReg = true;
739 do {
740 int FirstIdx = -1;
741 SecondIdx = -1;
742 MutableArrayRef<int> FirstMask, SecondMask;
743 for (unsigned I : seq<unsigned>(2 * NumOfSrcRegs)) {
744 SmallVectorImpl<int> &RegMask = Dest[I];
745 if (RegMask.empty())
746 continue;
747
748 if (FirstIdx == SecondIdx) {
749 FirstIdx = I;
750 FirstMask = RegMask;
751 continue;
752 }
753 SecondIdx = I;
754 SecondMask = RegMask;
755 CombineMasks(FirstMask, SecondMask);
756 ManyInputsAction(FirstMask, FirstIdx, SecondIdx, NewReg);
757 NewReg = false;
758 NormalizeMask(FirstMask);
759 RegMask.clear();
760 SecondMask = FirstMask;
761 SecondIdx = FirstIdx;
762 }
763 if (FirstIdx != SecondIdx && SecondIdx >= 0) {
764 CombineMasks(SecondMask, FirstMask);
765 ManyInputsAction(SecondMask, SecondIdx, FirstIdx, NewReg);
766 NewReg = false;
767 Dest[FirstIdx].clear();
768 NormalizeMask(SecondMask);
769 }
770 } while (SecondIdx >= 0);
771 break;
772 }
773 }
774 }
775}
776
777void llvm::getHorizDemandedEltsForFirstOperand(unsigned VectorBitWidth,
778 const APInt &DemandedElts,
779 APInt &DemandedLHS,
780 APInt &DemandedRHS) {
781 assert(VectorBitWidth >= 128 && "Vectors smaller than 128 bit not supported");
782 int NumLanes = VectorBitWidth / 128;
783 int NumElts = DemandedElts.getBitWidth();
784 int NumEltsPerLane = NumElts / NumLanes;
785 int HalfEltsPerLane = NumEltsPerLane / 2;
786
787 DemandedLHS = APInt::getZero(NumElts);
788 DemandedRHS = APInt::getZero(NumElts);
789
790 // Map DemandedElts to the horizontal operands.
791 for (int Idx = 0; Idx != NumElts; ++Idx) {
792 if (!DemandedElts[Idx])
793 continue;
794 int LaneIdx = (Idx / NumEltsPerLane) * NumEltsPerLane;
795 int LocalIdx = Idx % NumEltsPerLane;
796 if (LocalIdx < HalfEltsPerLane) {
797 DemandedLHS.setBit(LaneIdx + 2 * LocalIdx);
798 } else {
799 LocalIdx -= HalfEltsPerLane;
800 DemandedRHS.setBit(LaneIdx + 2 * LocalIdx);
801 }
802 }
803}
804
807 const TargetTransformInfo *TTI) {
808
809 // DemandedBits will give us every value's live-out bits. But we want
810 // to ensure no extra casts would need to be inserted, so every DAG
811 // of connected values must have the same minimum bitwidth.
817 SmallPtrSet<Instruction *, 4> InstructionSet;
819
820 // Determine the roots. We work bottom-up, from truncs or icmps.
821 bool SeenExtFromIllegalType = false;
822 for (auto *BB : Blocks)
823 for (auto &I : *BB) {
824 InstructionSet.insert(&I);
825
826 if (TTI && (isa<ZExtInst>(&I) || isa<SExtInst>(&I)) &&
827 !TTI->isTypeLegal(I.getOperand(0)->getType()))
828 SeenExtFromIllegalType = true;
829
830 // Only deal with non-vector integers up to 64-bits wide.
831 if ((isa<TruncInst>(&I) || isa<ICmpInst>(&I)) &&
832 !I.getType()->isVectorTy() &&
833 I.getOperand(0)->getType()->getScalarSizeInBits() <= 64) {
834 // Don't make work for ourselves. If we know the loaded type is legal,
835 // don't add it to the worklist.
836 if (TTI && isa<TruncInst>(&I) && TTI->isTypeLegal(I.getType()))
837 continue;
838
839 Worklist.push_back(&I);
840 Roots.insert(&I);
841 }
842 }
843 // Early exit.
844 if (Worklist.empty() || (TTI && !SeenExtFromIllegalType))
845 return MinBWs;
846
847 // Now proceed breadth-first, unioning values together.
848 while (!Worklist.empty()) {
849 Instruction *I = Worklist.pop_back_val();
850 Value *Leader = ECs.getOrInsertLeaderValue(I);
851
852 if (!Visited.insert(I).second)
853 continue;
854
855 // If we encounter a type that is larger than 64 bits, we can't represent
856 // it so bail out.
857 if (DB.getDemandedBits(I).getBitWidth() > 64)
859
860 uint64_t V = DB.getDemandedBits(I).getZExtValue();
861 DBits[Leader] |= V;
862 DBits[I] = V;
863
864 // Casts, loads and instructions outside of our range terminate a chain
865 // successfully.
867 !InstructionSet.count(I))
868 continue;
869
870 // Unsafe casts terminate a chain unsuccessfully. We can't do anything
871 // useful with bitcasts, ptrtoints or inttoptrs and it'd be unsafe to
872 // transform anything that relies on them.
874 !I->getType()->isIntegerTy()) {
875 DBits[Leader] |= ~0ULL;
876 continue;
877 }
878
879 // We don't modify the types of PHIs. Reductions will already have been
880 // truncated if possible, and inductions' sizes will have been chosen by
881 // indvars.
882 if (isa<PHINode>(I))
883 continue;
884
885 // Don't modify the types of operands of a call, as doing that would cause a
886 // signature mismatch.
887 if (isa<CallBase>(I))
888 continue;
889
890 if (DBits[Leader] == ~0ULL)
891 // All bits demanded, no point continuing.
892 continue;
893
894 for (Value *O : I->operands()) {
895 ECs.unionSets(Leader, O);
896 if (auto *OI = dyn_cast<Instruction>(O))
897 Worklist.push_back(OI);
898 }
899 }
900
901 // Now we've discovered all values, walk them to see if there are
902 // any users we didn't see. If there are, we can't optimize that
903 // chain.
904 for (auto &I : DBits)
905 for (auto *U : I.first->users())
906 if (U->getType()->isIntegerTy() && DBits.count(U) == 0)
907 DBits[ECs.getOrInsertLeaderValue(I.first)] |= ~0ULL;
908
909 for (const auto &E : ECs) {
910 if (!E->isLeader())
911 continue;
912 uint64_t LeaderDemandedBits = 0;
913 for (Value *M : ECs.members(*E))
914 LeaderDemandedBits |= DBits[M];
915
916 uint64_t MinBW = llvm::bit_width(LeaderDemandedBits);
917 // Round up to a power of 2
918 MinBW = llvm::bit_ceil(MinBW);
919
920 // We don't modify the types of PHIs. Reductions will already have been
921 // truncated if possible, and inductions' sizes will have been chosen by
922 // indvars.
923 // If we are required to shrink a PHI, abandon this entire equivalence class.
924 bool Abort = false;
925 for (Value *M : ECs.members(*E))
926 if (isa<PHINode>(M) && MinBW < M->getType()->getScalarSizeInBits()) {
927 Abort = true;
928 break;
929 }
930 if (Abort)
931 continue;
932
933 for (Value *M : ECs.members(*E)) {
934 auto *MI = dyn_cast<Instruction>(M);
935 if (!MI)
936 continue;
937 Type *Ty = M->getType();
938 if (Roots.count(MI))
939 Ty = MI->getOperand(0)->getType();
940
941 if (MinBW >= Ty->getScalarSizeInBits())
942 continue;
943
944 // If any of M's operands demand more bits than MinBW then M cannot be
945 // performed safely in MinBW.
946 auto *Call = dyn_cast<CallBase>(MI);
947 auto Ops = Call ? Call->args() : MI->operands();
948 if (any_of(Ops, [&DB, MinBW](Use &U) {
949 auto *CI = dyn_cast<ConstantInt>(U);
950 // For constants shift amounts, check if the shift would result in
951 // poison.
952 if (CI &&
954 U.getOperandNo() == 1)
955 return CI->uge(MinBW);
956 uint64_t BW = bit_width(DB.getDemandedBits(&U).getZExtValue());
957 return bit_ceil(BW) > MinBW;
958 }))
959 continue;
960
961 MinBWs[MI] = MinBW;
962 }
963 }
964
965 return MinBWs;
966}
967
968/// Add all access groups in @p AccGroups to @p List.
969template <typename ListT>
970static void addToAccessGroupList(ListT &List, MDNode *AccGroups) {
971 // Interpret an access group as a list containing itself.
972 if (AccGroups->getNumOperands() == 0) {
973 assert(isValidAsAccessGroup(AccGroups) && "Node must be an access group");
974 List.insert(AccGroups);
975 return;
976 }
977
978 for (const auto &AccGroupListOp : AccGroups->operands()) {
979 auto *Item = cast<MDNode>(AccGroupListOp.get());
980 assert(isValidAsAccessGroup(Item) && "List item must be an access group");
981 List.insert(Item);
982 }
983}
984
985MDNode *llvm::uniteAccessGroups(MDNode *AccGroups1, MDNode *AccGroups2) {
986 if (!AccGroups1)
987 return AccGroups2;
988 if (!AccGroups2)
989 return AccGroups1;
990 if (AccGroups1 == AccGroups2)
991 return AccGroups1;
992
994 addToAccessGroupList(Union, AccGroups1);
995 addToAccessGroupList(Union, AccGroups2);
996
997 if (Union.size() == 0)
998 return nullptr;
999 if (Union.size() == 1)
1000 return cast<MDNode>(Union.front());
1001
1002 LLVMContext &Ctx = AccGroups1->getContext();
1003 return MDNode::get(Ctx, Union.getArrayRef());
1004}
1005
1007 const Instruction *Inst2) {
1008 bool MayAccessMem1 = Inst1->mayReadOrWriteMemory();
1009 bool MayAccessMem2 = Inst2->mayReadOrWriteMemory();
1010
1011 if (!MayAccessMem1 && !MayAccessMem2)
1012 return nullptr;
1013 if (!MayAccessMem1)
1014 return Inst2->getMetadata(LLVMContext::MD_access_group);
1015 if (!MayAccessMem2)
1016 return Inst1->getMetadata(LLVMContext::MD_access_group);
1017
1018 MDNode *MD1 = Inst1->getMetadata(LLVMContext::MD_access_group);
1019 MDNode *MD2 = Inst2->getMetadata(LLVMContext::MD_access_group);
1020 if (!MD1 || !MD2)
1021 return nullptr;
1022 if (MD1 == MD2)
1023 return MD1;
1024
1025 // Use set for scalable 'contains' check.
1026 SmallPtrSet<Metadata *, 4> AccGroupSet2;
1027 addToAccessGroupList(AccGroupSet2, MD2);
1028
1029 SmallVector<Metadata *, 4> Intersection;
1030 if (MD1->getNumOperands() == 0) {
1031 assert(isValidAsAccessGroup(MD1) && "Node must be an access group");
1032 if (AccGroupSet2.count(MD1))
1033 Intersection.push_back(MD1);
1034 } else {
1035 for (const MDOperand &Node : MD1->operands()) {
1036 auto *Item = cast<MDNode>(Node.get());
1037 assert(isValidAsAccessGroup(Item) && "List item must be an access group");
1038 if (AccGroupSet2.count(Item))
1039 Intersection.push_back(Item);
1040 }
1041 }
1042
1043 if (Intersection.size() == 0)
1044 return nullptr;
1045 if (Intersection.size() == 1)
1046 return cast<MDNode>(Intersection.front());
1047
1048 LLVMContext &Ctx = Inst1->getContext();
1049 return MDNode::get(Ctx, Intersection);
1050}
1051
1052/// Add metadata from \p Inst to \p Metadata, if it can be preserved after
1053/// vectorization.
1055 Instruction *Inst,
1056 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Metadata) {
1058 static const unsigned SupportedIDs[] = {
1059 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
1060 LLVMContext::MD_noalias, LLVMContext::MD_fpmath,
1061 LLVMContext::MD_nontemporal, LLVMContext::MD_invariant_load,
1062 LLVMContext::MD_access_group, LLVMContext::MD_mmra};
1063
1064 // Remove any unsupported metadata kinds from Metadata.
1065 for (unsigned Idx = 0; Idx != Metadata.size();) {
1066 if (is_contained(SupportedIDs, Metadata[Idx].first)) {
1067 ++Idx;
1068 } else {
1069 // Swap element to end and remove it.
1070 std::swap(Metadata[Idx], Metadata.back());
1071 Metadata.pop_back();
1072 }
1073 }
1074}
1075
1076/// \returns \p I after propagating metadata from \p VL.
1078 if (VL.empty())
1079 return Inst;
1082
1083 for (auto &[Kind, MD] : Metadata) {
1084 // Skip MMRA metadata if the instruction cannot have it.
1085 if (Kind == LLVMContext::MD_mmra && !canInstructionHaveMMRAs(*Inst))
1086 continue;
1087
1088 for (int J = 1, E = VL.size(); MD && J != E; ++J) {
1089 const Instruction *IJ = cast<Instruction>(VL[J]);
1090 MDNode *IMD = IJ->getMetadata(Kind);
1091
1092 switch (Kind) {
1093 case LLVMContext::MD_mmra: {
1094 MD = MMRAMetadata::combine(Inst->getContext(), MD, IMD);
1095 break;
1096 }
1097 case LLVMContext::MD_tbaa:
1098 MD = MDNode::getMostGenericTBAA(MD, IMD);
1099 break;
1100 case LLVMContext::MD_alias_scope:
1102 break;
1103 case LLVMContext::MD_fpmath:
1104 MD = MDNode::getMostGenericFPMath(MD, IMD);
1105 break;
1106 case LLVMContext::MD_noalias:
1107 case LLVMContext::MD_nontemporal:
1108 case LLVMContext::MD_invariant_load:
1109 MD = MDNode::intersect(MD, IMD);
1110 break;
1111 case LLVMContext::MD_access_group:
1112 MD = intersectAccessGroups(Inst, IJ);
1113 break;
1114 default:
1115 llvm_unreachable("unhandled metadata");
1116 }
1117 }
1118
1119 Inst->setMetadata(Kind, MD);
1120 }
1121
1122 return Inst;
1123}
1124
1125Constant *
1127 const InterleaveGroup<Instruction> &Group) {
1128 // All 1's means mask is not needed.
1129 if (Group.isFull())
1130 return nullptr;
1131
1132 // TODO: support reversed access.
1133 assert(!Group.isReverse() && "Reversed group not supported.");
1134
1136 for (unsigned i = 0; i < VF; i++)
1137 for (unsigned j = 0; j < Group.getFactor(); ++j) {
1138 unsigned HasMember = Group.getMember(j) ? 1 : 0;
1139 Mask.push_back(Builder.getInt1(HasMember));
1140 }
1141
1142 return ConstantVector::get(Mask);
1143}
1144
1146llvm::createReplicatedMask(unsigned ReplicationFactor, unsigned VF) {
1147 SmallVector<int, 16> MaskVec;
1148 for (unsigned i = 0; i < VF; i++)
1149 for (unsigned j = 0; j < ReplicationFactor; j++)
1150 MaskVec.push_back(i);
1151
1152 return MaskVec;
1153}
1154
1156 unsigned NumVecs) {
1158 for (unsigned i = 0; i < VF; i++)
1159 for (unsigned j = 0; j < NumVecs; j++)
1160 Mask.push_back(j * VF + i);
1161
1162 return Mask;
1163}
1164
1166llvm::createStrideMask(unsigned Start, unsigned Stride, unsigned VF) {
1168 for (unsigned i = 0; i < VF; i++)
1169 Mask.push_back(Start + i * Stride);
1170
1171 return Mask;
1172}
1173
1175 unsigned NumInts,
1176 unsigned NumUndefs) {
1178 for (unsigned i = 0; i < NumInts; i++)
1179 Mask.push_back(Start + i);
1180
1181 for (unsigned i = 0; i < NumUndefs; i++)
1182 Mask.push_back(-1);
1183
1184 return Mask;
1185}
1186
1188 unsigned NumElts) {
1189 // Avoid casts in the loop and make sure we have a reasonable number.
1190 int NumEltsSigned = NumElts;
1191 assert(NumEltsSigned > 0 && "Expected smaller or non-zero element count");
1192
1193 // If the mask chooses an element from operand 1, reduce it to choose from the
1194 // corresponding element of operand 0. Undef mask elements are unchanged.
1195 SmallVector<int, 16> UnaryMask;
1196 for (int MaskElt : Mask) {
1197 assert((MaskElt < NumEltsSigned * 2) && "Expected valid shuffle mask");
1198 int UnaryElt = MaskElt >= NumEltsSigned ? MaskElt - NumEltsSigned : MaskElt;
1199 UnaryMask.push_back(UnaryElt);
1200 }
1201 return UnaryMask;
1202}
1203
1204/// A helper function for concatenating vectors. This function concatenates two
1205/// vectors having the same element type. If the second vector has fewer
1206/// elements than the first, it is padded with undefs.
1208 Value *V2) {
1209 VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType());
1210 VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType());
1211 assert(VecTy1 && VecTy2 &&
1212 VecTy1->getScalarType() == VecTy2->getScalarType() &&
1213 "Expect two vectors with the same element type");
1214
1215 unsigned NumElts1 = cast<FixedVectorType>(VecTy1)->getNumElements();
1216 unsigned NumElts2 = cast<FixedVectorType>(VecTy2)->getNumElements();
1217 assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements");
1218
1219 if (NumElts1 > NumElts2) {
1220 // Extend with UNDEFs.
1221 V2 = Builder.CreateShuffleVector(
1222 V2, createSequentialMask(0, NumElts2, NumElts1 - NumElts2));
1223 }
1224
1225 return Builder.CreateShuffleVector(
1226 V1, V2, createSequentialMask(0, NumElts1 + NumElts2, 0));
1227}
1228
1230 ArrayRef<Value *> Vecs) {
1231 unsigned NumVecs = Vecs.size();
1232 assert(NumVecs > 1 && "Should be at least two vectors");
1233
1235 ResList.append(Vecs.begin(), Vecs.end());
1236 do {
1238 for (unsigned i = 0; i < NumVecs - 1; i += 2) {
1239 Value *V0 = ResList[i], *V1 = ResList[i + 1];
1240 assert((V0->getType() == V1->getType() || i == NumVecs - 2) &&
1241 "Only the last vector may have a different type");
1242
1243 TmpList.push_back(concatenateTwoVectors(Builder, V0, V1));
1244 }
1245
1246 // Push the last vector if the total number of vectors is odd.
1247 if (NumVecs % 2 != 0)
1248 TmpList.push_back(ResList[NumVecs - 1]);
1249
1250 ResList = TmpList;
1251 NumVecs = ResList.size();
1252 } while (NumVecs > 1);
1253
1254 return ResList[0];
1255}
1256
1258 assert(isa<VectorType>(Mask->getType()) &&
1259 isa<IntegerType>(Mask->getType()->getScalarType()) &&
1260 cast<IntegerType>(Mask->getType()->getScalarType())->getBitWidth() ==
1261 1 &&
1262 "Mask must be a vector of i1");
1263
1264 auto AllOneOrUndef = m_CombineOr(m_AllOnes(), m_UndefValue());
1265 return match(Mask, m_CombineOr(AllOneOrUndef, m_ContainsMatchingVectorElement(
1266 AllOneOrUndef)));
1267}
1268
1269/// TODO: This is a lot like known bits, but for
1270/// vectors. Is there something we can common this with?
1272 assert(isa<FixedVectorType>(Mask->getType()) &&
1273 isa<IntegerType>(Mask->getType()->getScalarType()) &&
1274 cast<IntegerType>(Mask->getType()->getScalarType())->getBitWidth() ==
1275 1 &&
1276 "Mask must be a fixed width vector of i1");
1277
1278 const unsigned VWidth =
1279 cast<FixedVectorType>(Mask->getType())->getNumElements();
1280 APInt DemandedElts = APInt::getAllOnes(VWidth);
1281 if (auto *CV = dyn_cast<ConstantVector>(Mask))
1282 for (unsigned i = 0; i < VWidth; i++)
1283 if (CV->getAggregateElement(i)->isNullValue())
1284 DemandedElts.clearBit(i);
1285 return DemandedElts;
1286}
1287
1288bool InterleavedAccessInfo::isStrided(int Stride) {
1289 unsigned Factor = std::abs(Stride);
1290 return Factor >= 2 && Factor <= MaxInterleaveGroupFactor;
1291}
1292
1293void InterleavedAccessInfo::collectConstStrideAccesses(
1295 const SymbolicStrideMap &Strides,
1297 auto &DL = TheLoop->getHeader()->getDataLayout();
1298
1299 // Since it's desired that the load/store instructions be maintained in
1300 // "program order" for the interleaved access analysis, we have to visit the
1301 // blocks in the loop in reverse postorder (i.e., in a topological order).
1302 // Such an ordering will ensure that any load/store that may be executed
1303 // before a second load/store will precede the second load/store in
1304 // AccessStrideInfo.
1305 LoopBlocksDFS DFS(TheLoop);
1306 DFS.perform(LI);
1307 for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO()))
1308 for (auto &I : *BB) {
1310 if (!Ptr)
1311 continue;
1312 Type *ElementTy = getLoadStoreType(&I);
1313
1314 // Currently, codegen doesn't support cases where the type size doesn't
1315 // match the alloc size. Skip them for now.
1316 uint64_t Size = DL.getTypeAllocSize(ElementTy);
1317 if (Size * 8 != DL.getTypeSizeInBits(ElementTy))
1318 continue;
1319
1320 // We don't check wrapping here because we don't know yet if Ptr will be
1321 // part of a full group or a group with gaps. Checking wrapping for all
1322 // pointers (even those that end up in groups with no gaps) will be overly
1323 // conservative. For full groups, wrapping should be ok since if we would
1324 // wrap around the address space we would do a memory access at nullptr
1325 // even without the transformation. The wrapping checks are therefore
1326 // deferred until after we've formed the interleaved groups.
1327 int64_t Stride = getPtrStride(PSE, ElementTy, Ptr, TheLoop, *DT, Strides,
1328 /*ShouldCheckWrap=*/false, Predicates)
1329 .value_or(0);
1330
1331 const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
1332 AccessStrideInfo[&I] = StrideDescriptor(Stride, Scev, Size,
1334 }
1335}
1336
1337// Analyze interleaved accesses and collect them into interleaved load and
1338// store groups.
1339//
1340// When generating code for an interleaved load group, we effectively hoist all
1341// loads in the group to the location of the first load in program order. When
1342// generating code for an interleaved store group, we sink all stores to the
1343// location of the last store. This code motion can change the order of load
1344// and store instructions and may break dependences.
1345//
1346// The code generation strategy mentioned above ensures that we won't violate
1347// any write-after-read (WAR) dependences.
1348//
1349// E.g., for the WAR dependence: a = A[i]; // (1)
1350// A[i] = b; // (2)
1351//
1352// The store group of (2) is always inserted at or below (2), and the load
1353// group of (1) is always inserted at or above (1). Thus, the instructions will
1354// never be reordered. All other dependences are checked to ensure the
1355// correctness of the instruction reordering.
1356//
1357// The algorithm visits all memory accesses in the loop in bottom-up program
1358// order. Program order is established by traversing the blocks in the loop in
1359// reverse postorder when collecting the accesses.
1360//
1361// We visit the memory accesses in bottom-up order because it can simplify the
1362// construction of store groups in the presence of write-after-write (WAW)
1363// dependences.
1364//
1365// E.g., for the WAW dependence: A[i] = a; // (1)
1366// A[i] = b; // (2)
1367// A[i + 1] = c; // (3)
1368//
1369// We will first create a store group with (3) and (2). (1) can't be added to
1370// this group because it and (2) are dependent. However, (1) can be grouped
1371// with other accesses that may precede it in program order. Note that a
1372// bottom-up order does not imply that WAW dependences should not be checked.
1374 bool EnablePredicatedInterleavedMemAccesses) {
1375 LLVM_DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
1376 const auto &Strides = LAI->getSymbolicStrides();
1377
1378 // Holds all accesses with a constant stride.
1381 collectConstStrideAccesses(AccessStrideInfo, Strides,
1382 OptForSize ? nullptr : &Predicates);
1383
1384 if (AccessStrideInfo.empty())
1385 return;
1386
1387 // Collect the dependences in the loop.
1388 collectDependences();
1389
1390 // Holds all interleaved store groups temporarily.
1392 // Holds all interleaved load groups temporarily.
1394 // Groups added to this set cannot have new members added.
1395 SmallPtrSet<InterleaveGroup<Instruction> *, 4> CompletedLoadGroups;
1396
1397 // Search in bottom-up program order for pairs of accesses (A and B) that can
1398 // form interleaved load or store groups. In the algorithm below, access A
1399 // precedes access B in program order. We initialize a group for B in the
1400 // outer loop of the algorithm, and then in the inner loop, we attempt to
1401 // insert each A into B's group if:
1402 //
1403 // 1. A and B have the same stride,
1404 // 2. A and B have the same memory object size, and
1405 // 3. A belongs in B's group according to its distance from B.
1406 //
1407 // Special care is taken to ensure group formation will not break any
1408 // dependences.
1409 for (auto BI = AccessStrideInfo.rbegin(), E = AccessStrideInfo.rend();
1410 BI != E; ++BI) {
1411 Instruction *B = BI->first;
1412 StrideDescriptor DesB = BI->second;
1413
1414 // Initialize a group for B if it has an allowable stride. Even if we don't
1415 // create a group for B, we continue with the bottom-up algorithm to ensure
1416 // we don't break any of B's dependences.
1417 InterleaveGroup<Instruction> *GroupB = nullptr;
1418 if (isStrided(DesB.Stride) &&
1419 (!isPredicated(B->getParent()) || EnablePredicatedInterleavedMemAccesses)) {
1420 GroupB = getInterleaveGroup(B);
1421 if (!GroupB) {
1422 LLVM_DEBUG(dbgs() << "LV: Creating an interleave group with:" << *B
1423 << '\n');
1424 GroupB = createInterleaveGroup(B, DesB.Stride, DesB.Alignment);
1425 if (B->mayWriteToMemory())
1426 StoreGroups.insert(GroupB);
1427 else
1428 LoadGroups.insert(GroupB);
1429 }
1430 }
1431
1432 for (auto AI = std::next(BI); AI != E; ++AI) {
1433 Instruction *A = AI->first;
1434 StrideDescriptor DesA = AI->second;
1435
1436 // Our code motion strategy implies that we can't have dependences
1437 // between accesses in an interleaved group and other accesses located
1438 // between the first and last member of the group. Note that this also
1439 // means that a group can't have more than one member at a given offset.
1440 // The accesses in a group can have dependences with other accesses, but
1441 // we must ensure we don't extend the boundaries of the group such that
1442 // we encompass those dependent accesses.
1443 //
1444 // For example, assume we have the sequence of accesses shown below in a
1445 // stride-2 loop:
1446 //
1447 // (1, 2) is a group | A[i] = a; // (1)
1448 // | A[i-1] = b; // (2) |
1449 // A[i-3] = c; // (3)
1450 // A[i] = d; // (4) | (2, 4) is not a group
1451 //
1452 // Because accesses (2) and (3) are dependent, we can group (2) with (1)
1453 // but not with (4). If we did, the dependent access (3) would be within
1454 // the boundaries of the (2, 4) group.
1455 auto DependentMember = [&](InterleaveGroup<Instruction> *Group,
1456 StrideEntry *A) -> Instruction * {
1457 for (uint32_t Index = 0; Index < Group->getFactor(); ++Index) {
1458 Instruction *MemberOfGroupB = Group->getMember(Index);
1459 if (MemberOfGroupB && !canReorderMemAccessesForInterleavedGroups(
1460 A, &*AccessStrideInfo.find(MemberOfGroupB)))
1461 return MemberOfGroupB;
1462 }
1463 return nullptr;
1464 };
1465
1466 auto GroupA = getInterleaveGroup(A);
1467 // If A is a load, dependencies are tolerable, there's nothing to do here.
1468 // If both A and B belong to the same (store) group, they are independent,
1469 // even if dependencies have not been recorded.
1470 // If both GroupA and GroupB are null, there's nothing to do here.
1471 if (A->mayWriteToMemory() && GroupA != GroupB) {
1472 Instruction *DependentInst = nullptr;
1473 // If GroupB is a load group, we have to compare AI against all
1474 // members of GroupB because if any load within GroupB has a dependency
1475 // on AI, we need to mark GroupB as complete and also release the
1476 // store GroupA (if A belongs to one). The former prevents incorrect
1477 // hoisting of load B above store A while the latter prevents incorrect
1478 // sinking of store A below load B.
1479 if (GroupB && LoadGroups.contains(GroupB))
1480 DependentInst = DependentMember(GroupB, &*AI);
1481 else if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI))
1482 DependentInst = B;
1483
1484 if (DependentInst) {
1485 // A has a store dependence on B (or on some load within GroupB) and
1486 // is part of a store group. Release A's group to prevent illegal
1487 // sinking of A below B. A will then be free to form another group
1488 // with instructions that precede it.
1489 if (GroupA && StoreGroups.contains(GroupA)) {
1490 LLVM_DEBUG(dbgs() << "LV: Invalidated store group due to "
1491 "dependence between "
1492 << *A << " and " << *DependentInst << '\n');
1493 StoreGroups.remove(GroupA);
1494 releaseGroup(GroupA);
1495 }
1496 // If B is a load and part of an interleave group, no earlier loads
1497 // can be added to B's interleave group, because this would mean the
1498 // DependentInst would move across store A. Mark the interleave group
1499 // as complete.
1500 if (GroupB && LoadGroups.contains(GroupB)) {
1501 LLVM_DEBUG(dbgs() << "LV: Marking interleave group for " << *B
1502 << " as complete.\n");
1503 CompletedLoadGroups.insert(GroupB);
1504 }
1505 }
1506 }
1507 if (CompletedLoadGroups.contains(GroupB)) {
1508 // Skip trying to add A to B, continue to look for other conflicting A's
1509 // in groups to be released.
1510 continue;
1511 }
1512
1513 // At this point, we've checked for illegal code motion. If either A or B
1514 // isn't strided, there's nothing left to do.
1515 if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride))
1516 continue;
1517
1518 // Ignore A if it's already in a group or isn't the same kind of memory
1519 // operation as B.
1520 // Note that mayReadFromMemory() isn't mutually exclusive to
1521 // mayWriteToMemory in the case of atomic loads. We shouldn't see those
1522 // here, canVectorizeMemory() should have returned false - except for the
1523 // case we asked for optimization remarks.
1524 if (isInterleaved(A) ||
1525 (A->mayReadFromMemory() != B->mayReadFromMemory()) ||
1526 (A->mayWriteToMemory() != B->mayWriteToMemory()))
1527 continue;
1528
1529 // Check rules 1 and 2. Ignore A if its stride or size is different from
1530 // that of B.
1531 if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size)
1532 continue;
1533
1534 // Ignore A if the memory object of A and B don't belong to the same
1535 // address space
1537 continue;
1538
1539 // Calculate the distance from A to B.
1540 const SCEVConstant *DistToB = dyn_cast<SCEVConstant>(
1541 PSE.getSE()->getMinusSCEV(DesA.Scev, DesB.Scev));
1542 if (!DistToB)
1543 continue;
1544 int64_t DistanceToB = DistToB->getAPInt().getSExtValue();
1545
1546 // Check rule 3. Ignore A if its distance to B is not a multiple of the
1547 // size.
1548 if (DistanceToB % static_cast<int64_t>(DesB.Size))
1549 continue;
1550
1551 // All members of a predicated interleave-group must have the same predicate,
1552 // and currently must reside in the same BB.
1553 BasicBlock *BlockA = A->getParent();
1554 BasicBlock *BlockB = B->getParent();
1555 if ((isPredicated(BlockA) || isPredicated(BlockB)) &&
1556 (!EnablePredicatedInterleavedMemAccesses || BlockA != BlockB))
1557 continue;
1558
1559 // The index of A is the index of B plus A's distance to B in multiples
1560 // of the size.
1561 int IndexA =
1562 GroupB->getIndex(B) + DistanceToB / static_cast<int64_t>(DesB.Size);
1563
1564 // Try to insert A into B's group.
1565 if (GroupB->insertMember(A, IndexA, DesA.Alignment)) {
1566 LLVM_DEBUG(dbgs() << "LV: Inserted:" << *A << '\n'
1567 << " into the interleave group with" << *B
1568 << '\n');
1569 InterleaveGroupMap[A] = GroupB;
1570
1571 // Set the first load in program order as the insert position.
1572 if (A->mayReadFromMemory())
1573 GroupB->setInsertPos(A);
1574 }
1575 } // Iteration over A accesses.
1576 } // Iteration over B accesses.
1577
1578 // Commit the collected predicates to PSE if any candidate group was formed.
1579 if (!LoadGroups.empty() || !StoreGroups.empty())
1580 PSE.addPredicates(Predicates);
1581
1582 auto InvalidateGroupIfMemberMayWrap = [&](InterleaveGroup<Instruction> *Group,
1583 int Index,
1584 const char *FirstOrLast) -> bool {
1585 Instruction *Member = Group->getMember(Index);
1586 assert(Member && "Group member does not exist");
1587 Value *MemberPtr = getLoadStorePointerOperand(Member);
1588 Type *AccessTy = getLoadStoreType(Member);
1589 if (getPtrStride(PSE, AccessTy, MemberPtr, TheLoop, *DT, Strides,
1590 /*Assume=*/false, /*ShouldCheckWrap=*/true)
1591 .value_or(0))
1592 return false;
1593 LLVM_DEBUG(dbgs() << "LV: Invalidate candidate interleaved group due to "
1594 << FirstOrLast
1595 << " group member potentially pointer-wrapping.\n");
1596 releaseGroup(Group);
1597 return true;
1598 };
1599
1600 // Remove interleaved groups with gaps whose memory
1601 // accesses may wrap around. We have to revisit the getPtrStride analysis,
1602 // this time with ShouldCheckWrap=true, since collectConstStrideAccesses does
1603 // not check wrapping (see documentation there).
1604 // FORNOW we use Assume=false;
1605 // TODO: Change to Assume=true but making sure we don't exceed the threshold
1606 // of runtime SCEV assumptions checks (thereby potentially failing to
1607 // vectorize altogether).
1608 // Additional optional optimizations:
1609 // TODO: If we are peeling the loop and we know that the first pointer doesn't
1610 // wrap then we can deduce that all pointers in the group don't wrap.
1611 // This means that we can forcefully peel the loop in order to only have to
1612 // check the first pointer for no-wrap. When we'll change to use Assume=true
1613 // we'll only need at most one runtime check per interleaved group.
1614 for (auto *Group : LoadGroups) {
1615 // Case 1: A full group. Can Skip the checks; For full groups, if the wide
1616 // load would wrap around the address space we would do a memory access at
1617 // nullptr even without the transformation.
1618 if (Group->isFull())
1619 continue;
1620
1621 // Case 2: If first and last members of the group don't wrap this implies
1622 // that all the pointers in the group don't wrap.
1623 // So we check only group member 0 (which is always guaranteed to exist),
1624 // and group member Factor - 1; If the latter doesn't exist we rely on
1625 // peeling (if it is a non-reversed access -- see Case 3).
1626 if (InvalidateGroupIfMemberMayWrap(Group, 0, "first"))
1627 continue;
1628 if (Group->getMember(Group->getFactor() - 1))
1629 InvalidateGroupIfMemberMayWrap(Group, Group->getFactor() - 1, "last");
1630 else {
1631 // Case 3: A non-reversed interleaved load group with gaps: We need
1632 // to execute at least one scalar epilogue iteration. This will ensure
1633 // we don't speculatively access memory out-of-bounds. We only need
1634 // to look for a member at index factor - 1, since every group must have
1635 // a member at index zero.
1636 if (Group->isReverse()) {
1637 LLVM_DEBUG(
1638 dbgs() << "LV: Invalidate candidate interleaved group due to "
1639 "a reverse access with gaps.\n");
1640 releaseGroup(Group);
1641 continue;
1642 }
1643 LLVM_DEBUG(
1644 dbgs() << "LV: Interleaved group requires epilogue iteration.\n");
1645 RequiresScalarEpilogue = true;
1646 }
1647 }
1648
1649 for (auto *Group : StoreGroups) {
1650 // Case 1: A full group. Can Skip the checks; For full groups, if the wide
1651 // store would wrap around the address space we would do a memory access at
1652 // nullptr even without the transformation.
1653 if (Group->isFull())
1654 continue;
1655
1656 // Interleave-store-group with gaps is implemented using masked wide store.
1657 // Remove interleaved store groups with gaps if
1658 // masked-interleaved-accesses are not enabled by the target.
1659 if (!EnablePredicatedInterleavedMemAccesses) {
1660 LLVM_DEBUG(
1661 dbgs() << "LV: Invalidate candidate interleaved store group due "
1662 "to gaps.\n");
1663 releaseGroup(Group);
1664 continue;
1665 }
1666
1667 // Case 2: If first and last members of the group don't wrap this implies
1668 // that all the pointers in the group don't wrap.
1669 // So we check only group member 0 (which is always guaranteed to exist),
1670 // and the last group member. Case 3 (scalar epilog) is not relevant for
1671 // stores with gaps, which are implemented with masked-store (rather than
1672 // speculative access, as in loads).
1673 if (InvalidateGroupIfMemberMayWrap(Group, 0, "first"))
1674 continue;
1675 for (int Index = Group->getFactor() - 1; Index > 0; Index--)
1676 if (Group->getMember(Index)) {
1677 InvalidateGroupIfMemberMayWrap(Group, Index, "last");
1678 break;
1679 }
1680 }
1681}
1682
1684 // If no group had triggered the requirement to create an epilogue loop,
1685 // there is nothing to do.
1687 return;
1688
1689 // Release groups requiring scalar epilogues. Note that this also removes them
1690 // from InterleaveGroups.
1691 bool ReleasedGroup = InterleaveGroups.remove_if([&](auto *Group) {
1692 if (!Group->requiresScalarEpilogue())
1693 return false;
1694 LLVM_DEBUG(
1695 dbgs()
1696 << "LV: Invalidate candidate interleaved group due to gaps that "
1697 "require a scalar epilogue (not allowed under optsize) and cannot "
1698 "be masked (not enabled). \n");
1699 releaseGroupWithoutRemovingFromSet(Group);
1700 return true;
1701 });
1702 assert(ReleasedGroup && "At least one group must be invalidated, as a "
1703 "scalar epilogue was required");
1704 (void)ReleasedGroup;
1705 RequiresScalarEpilogue = false;
1706}
1707
1708template <typename InstT>
1709void InterleaveGroup<InstT>::addMetadata(InstT *NewInst) const {
1710 llvm_unreachable("addMetadata can only be used for Instruction");
1711}
1712
1713namespace llvm {
1714template <>
1719} // namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Generic implementation of equivalence classes through the use Tarjan's efficient union-find algorithm...
IRTranslator LLVM IR MI
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define I(x, y, z)
Definition MD5.cpp:57
This file provides utility for Memory Model Relaxation Annotations (MMRAs).
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static unsigned getScalarSizeInBits(Type *Ty)
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
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:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1426
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1350
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1582
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & front() const
Get the first element.
Definition ArrayRef.h:144
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
LLVM Basic Block Representation.
Definition BasicBlock.h:62
This class represents a function call, abstracting a target machine's calling convention.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:43
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:254
This represents a collection of equivalence classes and supports three efficient operations: insert a...
iterator_range< member_iterator > members(const ECValue &ECV) const
const ElemTy & getOrInsertLeaderValue(const ElemTy &V)
Return the leader for the specified value that is in the set.
member_iterator unionSets(const ElemTy &V1, const ElemTy &V2)
Merge the two equivalence sets for the specified values, inserting them if they do not already exist ...
Common base class shared among various IRBuilders.
Definition IRBuilder.h:114
This instruction inserts a single (scalar) element into a VectorType value.
bool mayReadOrWriteMemory() const
Return true if this instruction may read or write memory.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
void getAllMetadataOtherThanDebugLoc(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
This does the same thing as getAllMetadata, except that it filters out the debug location.
The group of interleaved loads/stores sharing the same stride and close to each other.
uint32_t getFactor() const
InstTy * getMember(uint32_t Index) const
Get the member with the given index Index.
bool isFull() const
Return true if this group is full, i.e. it has no gaps.
uint32_t getIndex(const InstTy *Instr) const
Get the index for the given member.
void setInsertPos(InstTy *Inst)
bool isReverse() const
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.
InterleaveGroup< Instruction > * getInterleaveGroup(const Instruction *Instr) const
Get the interleave group that Instr belongs to.
bool requiresScalarEpilogue() const
Returns true if an interleaved group that may access memory out-of-bounds requires a scalar epilogue ...
bool isInterleaved(Instruction *Instr) const
Check if Instr belongs to any interleave group.
LLVM_ABI void analyzeInterleaving(bool EnableMaskedInterleavedGroup)
Analyze the interleaved accesses and collect them in interleave groups.
LLVM_ABI void invalidateGroupsRequiringScalarEpilogue()
Invalidate groups that require a scalar epilogue (due to gaps).
A wrapper class for inspecting calls to intrinsic functions.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
Metadata node.
Definition Metadata.h:1081
static LLVM_ABI MDNode * getMostGenericAliasScope(MDNode *A, MDNode *B)
static LLVM_ABI MDNode * getMostGenericTBAA(MDNode *A, MDNode *B)
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1435
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1578
static LLVM_ABI MDNode * getMostGenericFPMath(MDNode *A, MDNode *B)
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1443
static LLVM_ABI MDNode * intersect(MDNode *A, MDNode *B)
LLVMContext & getContext() const
Definition Metadata.h:1245
Tracking metadata reference owned by Metadata.
Definition Metadata.h:902
static LLVM_ABI MDNode * combine(LLVMContext &Ctx, const MMRAMetadata &A, const MMRAMetadata &B)
Combines A and B according to MMRA semantics.
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
iterator find(const KeyT &Key)
Definition MapVector.h:156
bool empty() const
Definition MapVector.h:79
reverse_iterator rend()
Definition MapVector.h:76
reverse_iterator rbegin()
Definition MapVector.h:72
Root of the metadata hierarchy.
Definition Metadata.h:64
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
This class represents a constant integer value.
const APInt & getAPInt() const
bool remove(const value_type &X)
Remove an item from the set vector.
Definition SetVector.h:187
bool contains(const_arg_type key) const
Check if the SetVector contains the given key.
Definition SetVector.h:258
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
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.
bool remove_if(UnaryPredicate P)
Remove elements that match the given predicate.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:345
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
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.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
ArrayRef< Type * > subtypes() const
Definition Type.h:376
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Value * getOperand(unsigned i) const
Definition User.h:207
static LLVM_ABI std::optional< unsigned > getVectorLengthParamPos(Intrinsic::ID IntrinsicID)
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
Base class of all SIMD vector types.
Type * getElementType() const
An efficient, type-erasing, non-owning reference to a callable.
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI bool isTriviallyScalarizable(ID id)
Returns true if the intrinsic is trivially scalarizable.
LLVM_ABI bool isTargetIntrinsic(ID IID)
isTargetIntrinsic - Returns true if IID is an intrinsic specific to a certain target.
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
AllOnesConstantMatch m_AllOnes()
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_UndefValue()
Match an arbitrary UndefValue constant.
auto m_Constant()
Match an arbitrary Constant and ignore it.
ContainsMatchingVectorElement_match< SPTy > m_ContainsMatchingVectorElement(const SPTy &SubPattern)
Match a vector constant where at least one of its elements matches the subpattern.
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
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.
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
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:1755
unsigned getLoadStoreAddressSpace(const Value *I)
A helper function that returns the address space of the pointer operand of load or store instruction.
LLVM_ABI Intrinsic::ID getVectorIntrinsicIDForCall(const CallInst *CI, const TargetLibraryInfo *TLI)
Returns intrinsic ID for call.
LLVM_ABI bool canInstructionHaveMMRAs(const Instruction &I)
LLVM_ABI 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 ...
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2570
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
LLVM_ABI 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 ...
LLVM_ABI void getMetadataToPropagate(Instruction *Inst, SmallVectorImpl< std::pair< unsigned, MDNode * > > &Metadata)
Add metadata from Inst to Metadata, if it can be preserved after vectorization.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI const SCEV * replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE, const SymbolicStrideMap &PtrToStride, Value *Ptr)
Return the SCEV corresponding to a pointer with the symbolic stride replaced with constant one,...
int bit_width(T Value)
Returns the number of bits needed to represent Value if Value is nonzero.
Definition bit.h:325
LLVM_ABI Value * concatenateVectors(IRBuilderBase &Builder, ArrayRef< Value * > Vecs)
Concatenate a list of vectors.
Align getLoadStoreAlignment(const Value *I)
A helper function that returns the alignment of load or store instruction.
LLVM_ABI 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...
LLVM_ABI Instruction * propagateMetadata(Instruction *I, ArrayRef< Value * > VL)
Specifically, let Kinds = [MD_tbaa, MD_alias_scope, MD_noalias, MD_fpmath, MD_nontemporal,...
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
LLVM_ABI std::optional< int64_t > getPtrStride(PredicatedScalarEvolution &PSE, Type *AccessTy, Value *Ptr, const Loop *Lp, const DominatorTree &DT, const SymbolicStrideMap &StridesMap=SymbolicStrideMap(), bool ShouldCheckWrap=true, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
If the pointer has a constant stride return it in units of the access type size.
T bit_ceil(T Value)
Returns the smallest integral power of two no smaller than Value if Value is nonzero.
Definition bit.h:362
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
Definition STLExtras.h:2189
LLVM_ABI MDNode * intersectAccessGroups(const Instruction *Inst1, const Instruction *Inst2)
Compute the access-group list of access groups that Inst1 and Inst2 are both in.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
unsigned M1(unsigned Val)
Definition VE.h:377
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI 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...
LLVM_ABI 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...
LLVM_ABI 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
LLVM_ABI llvm::SmallVector< int, 16 > createStrideMask(unsigned Start, unsigned Stride, unsigned VF)
Create a stride shuffle mask.
LLVM_ABI void getHorizDemandedEltsForFirstOperand(unsigned VectorBitWidth, const APInt &DemandedElts, APInt &DemandedLHS, APInt &DemandedRHS)
Compute the demanded elements mask of horizontal binary operations.
LLVM_ABI llvm::SmallVector< int, 16 > createReplicatedMask(unsigned ReplicationFactor, unsigned VF)
Create a mask with replicated elements.
DenseMap< Value *, const SCEVUnknown * > SymbolicStrideMap
Maps a pointer to its symbolic (non-constant) stride.
LLVM_ABI unsigned getDeinterleaveIntrinsicFactor(Intrinsic::ID ID)
Returns the corresponding factor of llvm.vector.deinterleaveN intrinsics.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI unsigned getInterleaveIntrinsicFactor(Intrinsic::ID ID)
Returns the corresponding factor of llvm.vector.interleaveN intrinsics.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
constexpr int PoisonMaskElem
LLVM_ABI bool isTriviallyScalarizable(Intrinsic::ID ID)
Identify if the intrinsic is trivially scalarizable.
LLVM_ABI bool isValidAsAccessGroup(MDNode *AccGroup)
Return whether an MDNode might represent an access group.
LLVM_ABI Intrinsic::ID getIntrinsicForCallSite(const CallBase &CB, const TargetLibraryInfo *TLI)
Map a call instruction to an intrinsic ID.
LLVM_ABI bool isVectorIntrinsicWithStructReturnOverloadAtField(Intrinsic::ID ID, int RetIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic that returns a struct is overloaded at the struct elem...
TargetTransformInfo TTI
LLVM_ABI 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_ABI bool isMaskedSlidePair(ArrayRef< int > Mask, int NumElts, std::array< std::pair< int, int >, 2 > &SrcInfo)
Does this shuffle mask represent either one slide shuffle or a pair of two slide shuffles,...
LLVM_ABI VectorType * getDeinterleavedVectorType(IntrinsicInst *DI)
Given a deinterleaveN intrinsic, return the (narrow) vector type of each factor.
LLVM_ABI llvm::SmallVector< int, 16 > createInterleaveMask(unsigned VF, unsigned NumVecs)
Create an interleave shuffle mask.
LLVM_ABI bool isVectorIntrinsicWithScalarOpAtArg(Intrinsic::ID ID, unsigned ScalarOpdIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic has a scalar operand.
LLVM_ABI Value * findScalarElement(Value *V, unsigned EltNo)
Given a vector and an element number, see if the scalar value is already around as a register,...
LLVM_ABI MDNode * uniteAccessGroups(MDNode *AccGroups1, MDNode *AccGroups2)
Compute the union of two access-group lists.
unsigned M0(unsigned Val)
Definition VE.h:376
auto make_second_range(ContainerTy &&c)
Given a container of pairs, return a range over the second elements.
Definition STLExtras.h:1425
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:2035
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
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:1788
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
LLVM_ABI 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 is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
LLVM_ABI 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, bool)> ManyInputsAction)
Splits and processes shuffle mask depending on the number of input and output registers.
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:2182
LLVM_ABI bool maskContainsAllOneOrUndef(Value *Mask)
Given a mask vector of i1, Return true if any of the elements of this predicate mask are known to be ...
LLVM_ABI bool isTriviallyVectorizable(Intrinsic::ID ID)
Identify if the intrinsic is trivially vectorizable.
LLVM_ABI llvm::SmallVector< int, 16 > createSequentialMask(unsigned Start, unsigned NumInts, unsigned NumUndefs)
Create a sequential shuffle mask.
LLVM_ABI bool isVectorIntrinsicWithOverloadTypeAtArg(Intrinsic::ID ID, int OpdIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic is overloaded on the type of the operand at index OpdI...
LLVM_ABI 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.
LLVM_ABI bool scaleShuffleMaskElts(unsigned NumDstElts, ArrayRef< int > Mask, SmallVectorImpl< int > &ScaledMask)
Attempt to narrow/widen the Mask shuffle mask to the NumDstElts target width.
LLVM_ABI 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:880