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