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