LLVM 24.0.0git
LoopAccessAnalysis.cpp
Go to the documentation of this file.
1//===- LoopAccessAnalysis.cpp - Loop Access Analysis Implementation --------==//
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// The implementation for the loop memory dependence that was originally
10// developed for the loop vectorizer.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SetVector.h"
22#include "llvm/ADT/SmallSet.h"
40#include "llvm/IR/BasicBlock.h"
41#include "llvm/IR/Constants.h"
42#include "llvm/IR/DataLayout.h"
43#include "llvm/IR/DebugLoc.h"
46#include "llvm/IR/Dominators.h"
47#include "llvm/IR/Function.h"
48#include "llvm/IR/InstrTypes.h"
49#include "llvm/IR/Instruction.h"
52#include "llvm/IR/PassManager.h"
53#include "llvm/IR/Type.h"
54#include "llvm/IR/Value.h"
55#include "llvm/IR/ValueHandle.h"
58#include "llvm/Support/Debug.h"
62#include <algorithm>
63#include <cassert>
64#include <cstdint>
65#include <iterator>
66#include <utility>
67#include <variant>
68#include <vector>
69
70using namespace llvm;
71using namespace llvm::SCEVPatternMatch;
72
73#define DEBUG_TYPE "loop-accesses"
74
76 VectorizationFactor("force-vector-width", cl::Hidden,
77 cl::desc("Sets the SIMD width. Zero is autoselect."),
80
82VectorizationInterleave("force-vector-interleave", cl::Hidden,
83 cl::desc("Sets the vectorization interleave count. "
84 "Zero is autoselect."),
88
90 "runtime-memory-check-threshold", cl::Hidden,
91 cl::desc("When performing memory disambiguation checks at runtime do not "
92 "generate more than this number of comparisons (default = 8)."),
95
96/// The maximum iterations used to merge memory checks
98 "memory-check-merge-threshold", cl::Hidden,
99 cl::desc("Maximum number of comparisons done when trying to merge "
100 "runtime memory checks. (default = 100)"),
101 cl::init(100));
102
103/// Maximum SIMD width.
104const unsigned VectorizerParams::MaxVectorWidth = 64;
105
106/// We collect dependences up to this threshold.
108 MaxDependences("max-dependences", cl::Hidden,
109 cl::desc("Maximum number of dependences collected by "
110 "loop-access analysis (default = 100)"),
111 cl::init(100));
112
113/// This enables versioning on the strides of symbolically striding memory
114/// accesses in code like the following.
115/// for (i = 0; i < N; ++i)
116/// A[i * Stride1] += B[i * Stride2] ...
117///
118/// Will be roughly translated to
119/// if (Stride1 == 1 && Stride2 == 1) {
120/// for (i = 0; i < N; i+=4)
121/// A[i:i+3] += ...
122/// } else
123/// ...
125 "enable-mem-access-versioning", cl::init(true), cl::Hidden,
126 cl::desc("Enable symbolic stride memory access versioning"));
127
128/// Enable store-to-load forwarding conflict detection. This option can
129/// be disabled for correctness testing.
131 "store-to-load-forwarding-conflict-detection", cl::Hidden,
132 cl::desc("Enable conflict detection in loop-access analysis"),
133 cl::init(true));
134
136 "max-forked-scev-depth", cl::Hidden,
137 cl::desc("Maximum recursion depth when finding forked SCEVs (default = 5)"),
138 cl::init(5));
139
141 "laa-speculate-unit-stride", cl::Hidden,
142 cl::desc("Speculate that non-constant strides are unit in LAA"),
143 cl::init(true));
144
146 "hoist-runtime-checks", cl::Hidden,
147 cl::desc(
148 "Hoist inner loop runtime memory checks to outer loop if possible"),
151
153 return ::VectorizationInterleave.getNumOccurrences() > 0;
154}
155
156const SCEV *
158 const SymbolicStrideMap &PtrToStride,
159 Value *Ptr) {
160 const SCEV *OrigSCEV = PSE.getSCEV(Ptr);
161
162 // If there is an entry in the map return the SCEV of the pointer with the
163 // symbolic stride replaced by one.
164 const SCEVUnknown *StrideSCEV = PtrToStride.lookup(Ptr);
165 if (!StrideSCEV)
166 // For a non-symbolic stride, just return the original expression.
167 return OrigSCEV;
168
169 ScalarEvolution *SE = PSE.getSE();
170 const SCEV *CT = SE->getOne(StrideSCEV->getType());
171 PSE.addPredicate(*SE->getEqualPredicate(StrideSCEV, CT));
172 const SCEV *Expr = PSE.getSCEV(Ptr);
173
174 LLVM_DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV
175 << " by: " << *Expr << "\n");
176 return Expr;
177}
178
180 unsigned Index, const RuntimePointerChecking &RtCheck)
181 : High(RtCheck.Pointers[Index].End), Low(RtCheck.Pointers[Index].Start),
182 AddressSpace(RtCheck.Pointers[Index]
183 .PointerValue->getType()
185 NeedsFreeze(RtCheck.Pointers[Index].NeedsFreeze) {
186 Members.push_back(Index);
187}
188
189/// Returns \p A + \p B, if it is guaranteed not to unsigned wrap. Otherwise
190/// return nullptr. \p A and \p B must have the same type.
191static const SCEV *addSCEVNoOverflow(const SCEV *A, const SCEV *B,
192 ScalarEvolution &SE) {
193 if (!SE.willNotOverflow(Instruction::Add, /*IsSigned=*/false, A, B))
194 return nullptr;
195 return SE.getAddExpr(A, B);
196}
197
198/// Returns \p A * \p B, if it is guaranteed not to unsigned wrap. Otherwise
199/// return nullptr. \p A and \p B must have the same type.
200static const SCEV *mulSCEVNoOverflow(const SCEV *A, const SCEV *B,
201 ScalarEvolution &SE) {
202 if (!SE.willNotOverflow(Instruction::Mul, /*IsSigned=*/false, A, B))
203 return nullptr;
204 return SE.getMulExpr(A, B);
205}
206
207/// Return true, if evaluating \p AR at \p MaxBTC cannot wrap, because \p AR at
208/// \p MaxBTC is guaranteed inbounds of the accessed object.
210 const SCEVAddRecExpr *AR, const SCEV *MaxBTC, const SCEV *EltSize,
212 AssumptionCache *AC,
213 std::optional<ScalarEvolution::LoopGuards> &LoopGuards) {
214 auto *PointerBase = SE.getPointerBase(AR->getStart());
215 auto *StartPtr = dyn_cast<SCEVUnknown>(PointerBase);
216 if (!StartPtr)
217 return false;
218 const Loop *L = AR->getLoop();
219 bool CheckForNonNull;
220 Value *StartPtrV = StartPtr->getValue();
221 // We can ignore frees, as the fact that an object of a certain size existed
222 // at the location *at some point* is sufficient to derive the nowrap fact.
223 uint64_t DerefBytes = StartPtrV->getPointerDereferenceableBytes(
224 DL, CheckForNonNull, /*CanBeFreed=*/nullptr);
225
226 // If the deref size is only known when the pointer is non-null, ignore it
227 // here and fall back to a dereferenceable assumption below.
228 if (DerefBytes && CheckForNonNull)
229 DerefBytes = 0;
230
231 const SCEV *Step = AR->getStepRecurrence(SE);
232 Type *WiderTy = SE.getWiderType(MaxBTC->getType(), Step->getType());
233 const SCEV *DerefBytesSCEV = SE.getConstant(WiderTy, DerefBytes);
234
235 // Check if we have a suitable dereferencable assumption we can use.
236 Instruction *CtxI = &*L->getHeader()->getFirstNonPHIIt();
237 if (BasicBlock *LoopPred = L->getLoopPredecessor()) {
238 if (isa<UncondBrInst, CondBrInst>(LoopPred->getTerminator()))
239 CtxI = LoopPred->getTerminator();
240 }
242 StartPtrV, Attribute::Dereferenceable, *AC,
243 [&](RetainedKnowledge RK, Instruction *Assume, auto) {
244 if (!isValidAssumeForContext(Assume, CtxI, DT))
245 return false;
246 const SCEV *DerefRKSCEV = SE.getSCEV(RK.IRArgValue);
247 Type *CommonTy =
248 SE.getWiderType(DerefBytesSCEV->getType(), DerefRKSCEV->getType());
249 DerefBytesSCEV = SE.getNoopOrZeroExtend(DerefBytesSCEV, CommonTy);
250 DerefRKSCEV = SE.getNoopOrZeroExtend(DerefRKSCEV, CommonTy);
251 DerefBytesSCEV = SE.getUMaxExpr(DerefBytesSCEV, DerefRKSCEV);
252 // Continue with other assumptions.
253 return false;
254 });
255
256 if (DerefBytesSCEV->isZero())
257 return false;
258
259 bool IsKnownNonNegative = SE.isKnownNonNegative(Step);
260 if (!IsKnownNonNegative && !SE.isKnownNegative(Step))
261 return false;
262
263 WiderTy = SE.getWiderType(WiderTy, DerefBytesSCEV->getType());
264 Step = SE.getNoopOrSignExtend(Step, WiderTy);
265 MaxBTC = SE.getNoopOrZeroExtend(MaxBTC, WiderTy);
266
267 // For the computations below, make sure they don't unsigned wrap.
268 // FIXME: for a negative step the lowest accessed address is not
269 // AR->getStart() but AR->evaluateAtIteration(MaxBTC, SE); the check below
270 // therefore compares StartPtr against the highest accessed address instead
271 // of the lowest.
272 if (!SE.isKnownPredicate(CmpInst::ICMP_UGE, AR->getStart(), StartPtr))
273 return false;
274 const SCEV *StartOffset = SE.getNoopOrZeroExtend(
275 SE.getMinusSCEV(AR->getStart(), StartPtr), WiderTy);
276
277 if (!LoopGuards)
278 LoopGuards.emplace(ScalarEvolution::LoopGuards::collect(AR->getLoop(), SE));
279 MaxBTC = SE.applyLoopGuards(MaxBTC, *LoopGuards);
280
281 const SCEV *AbsStep = SE.getAbsExpr(Step, /*IsNSW=*/false);
282 // Total distance (in bytes) between the first and the last
283 // accessed pointer.
284 const SCEV *DistToLastIter = mulSCEVNoOverflow(MaxBTC, AbsStep, SE);
285 if (!DistToLastIter) {
286 // Re-try with constant max backedge-taken count if using the symbolic one
287 // failed.
288 MaxBTC = SE.getConstantMaxBackedgeTakenCount(AR->getLoop());
289 if (isa<SCEVCouldNotCompute>(MaxBTC))
290 return false;
291 MaxBTC = SE.getNoopOrZeroExtend(MaxBTC, WiderTy);
292 DistToLastIter = mulSCEVNoOverflow(MaxBTC, AbsStep, SE);
293 if (!DistToLastIter)
294 return false;
295 }
296
297 // Total length in bytes of the accessed range (from the first accessed
298 // byte through the end of the last access).
299 const SCEV *AccessedBytes = addSCEVNoOverflow(
300 DistToLastIter, SE.getNoopOrZeroExtend(EltSize, WiderTy), SE);
301 if (!AccessedBytes)
302 return false;
303
304 // Compute MaxOffset per direction: exclusive upper offset of the
305 // accessed range.
306 const SCEV *MaxOffset;
307 if (IsKnownNonNegative) {
308 MaxOffset = addSCEVNoOverflow(StartOffset, AccessedBytes, SE);
309 if (!MaxOffset)
310 return false;
311 DerefBytesSCEV = SE.applyLoopGuards(DerefBytesSCEV, *LoopGuards);
312 } else {
313 // FIXME: two independent off-by-EltSize bugs on this branch:
314 // 1. StartOffset here is actually the HIGHEST offset, because it is
315 // computed from AR->getStart() rather than
316 // AR->evaluateAtIteration(MaxBTC, SE) (see FIXME above).
317 // 2. The lower check is over-strict by EltSize and the upper is
318 // under-counted by EltSize.
319 assert(SE.isKnownNegative(Step) && "must be known negative");
320 if (!SE.isKnownPredicate(CmpInst::ICMP_SGE, StartOffset, AccessedBytes))
321 return false;
322 MaxOffset = StartOffset;
323 }
324 // MaxOffset must not exceed the deref-region end.
325 return SE.isKnownPredicate(CmpInst::ICMP_ULE, MaxOffset, DerefBytesSCEV);
326}
327
328/// Return true if \p S is known to be monotonically non-decreasing
329/// (in the unsigned sense, without unsigned wrap) across iterations of \p L.
330static bool isKnownNonDecreasingInLoop(const SCEV *S, const Loop *L,
331 ScalarEvolution &SE) {
332 if (SE.isLoopInvariant(S, L))
333 return true;
334
335 switch (S->getSCEVType()) {
336 case scUDivExpr: {
337 // Non-decreasing in the numerator when the divisor is loop-invariant.
338 const auto *UDiv = cast<SCEVUDivExpr>(S);
339 return SE.isLoopInvariant(UDiv->getRHS(), L) &&
340 isKnownNonDecreasingInLoop(UDiv->getLHS(), L, SE);
341 }
342 case scAddRecExpr: {
343 auto *AR = cast<SCEVAddRecExpr>(S);
344 assert(AR->getLoop() == L &&
345 "trying to check for AddRec in different loop");
348 }
349 default:
350 return false;
351 }
352}
353
354/// Try to bound a loop-variant pointer that is not an affine AddRec.
355///
356/// If the offset is provably monotonically non-decreasing the accessed range is
357/// bounded by the offset's value at the first iteration (via
358/// SplitIntoInitAndPostInc) and last iteration (via getSCEVAtScope). The
359/// returned range is half-open: \p EltSizeSCEV is added to the address of the
360/// last accessed element to form the end.
361///
362/// Returns {nullptr, nullptr} if no such bound can be formed.
363static std::pair<const SCEV *, const SCEV *>
364getNonAffineMonotonicBounds(const Loop *Lp, const SCEV *PtrExpr,
365 const SCEV *EltSizeSCEV, ScalarEvolution *SE) {
366 const auto *PtrAdd = dyn_cast<SCEVAddExpr>(PtrExpr);
367 if (!PtrAdd || !PtrAdd->hasNoUnsignedWrap())
368 return {nullptr, nullptr};
369
370 const SCEV *Base = *find_if(PtrAdd->operands(), [](const auto &Op) {
371 return Op->getType()->isPointerTy();
372 });
374 return {nullptr, nullptr};
375
376 const SCEV *Offset = SE->getMinusSCEV(PtrExpr, Base);
379 return {nullptr, nullptr};
380
381 const SCEV *OffStart = SE->SplitIntoInitAndPostInc(Lp, Offset).first;
382 const SCEV *OffEnd = SE->getSCEVAtScope(Offset, Lp->getParentLoop());
383 if (isa<SCEVCouldNotCompute>(OffStart) || isa<SCEVCouldNotCompute>(OffEnd) ||
384 !SE->isLoopInvariant(OffStart, Lp) || !SE->isLoopInvariant(OffEnd, Lp))
385 return {nullptr, nullptr};
386
387 return {SE->getAddExpr(Base, OffStart),
388 SE->getAddExpr(Base, OffEnd, EltSizeSCEV)};
389}
390
391std::pair<const SCEV *, const SCEV *> llvm::getStartAndEndForAccess(
392 const Loop *Lp, const SCEV *PtrExpr, Type *AccessTy, const SCEV *BTC,
393 const SCEV *MaxBTC, ScalarEvolution *SE,
394 DenseMap<std::pair<const SCEV *, const SCEV *>,
395 std::pair<const SCEV *, const SCEV *>> *PointerBounds,
397 std::optional<ScalarEvolution::LoopGuards> &LoopGuards) {
398 auto &DL = Lp->getHeader()->getDataLayout();
399 Type *IdxTy = DL.getIndexType(PtrExpr->getType());
400 const SCEV *EltSizeSCEV = SE->getStoreSizeOfExpr(IdxTy, AccessTy);
401
402 // Delegate to the SCEV-based overload, passing through the cache.
403 return getStartAndEndForAccess(Lp, PtrExpr, EltSizeSCEV, BTC, MaxBTC, SE,
404 PointerBounds, DT, AC, LoopGuards);
405}
406
407std::pair<const SCEV *, const SCEV *> llvm::getStartAndEndForAccess(
408 const Loop *Lp, const SCEV *PtrExpr, const SCEV *EltSizeSCEV,
409 const SCEV *BTC, const SCEV *MaxBTC, ScalarEvolution *SE,
410 DenseMap<std::pair<const SCEV *, const SCEV *>,
411 std::pair<const SCEV *, const SCEV *>> *PointerBounds,
413 std::optional<ScalarEvolution::LoopGuards> &LoopGuards) {
414 std::pair<const SCEV *, const SCEV *> *PtrBoundsPair;
415 if (PointerBounds) {
416 auto [Iter, Ins] = PointerBounds->insert(
417 {{PtrExpr, EltSizeSCEV},
418 {SE->getCouldNotCompute(), SE->getCouldNotCompute()}});
419 if (!Ins)
420 return Iter->second;
421 PtrBoundsPair = &Iter->second;
422 }
423
424 // ScStart is the lowest accessed address; ScEnd is the highest one plus the
425 // size of the accessed element.
426 const SCEV *ScStart;
427 const SCEV *ScEnd;
428
429 auto &DL = Lp->getHeader()->getDataLayout();
430 if (SE->isLoopInvariant(PtrExpr, Lp)) {
431 ScStart = PtrExpr;
432 ScEnd = SE->getAddExpr(PtrExpr, EltSizeSCEV);
433 } else if (auto *AR = dyn_cast<SCEVAddRecExpr>(PtrExpr)) {
434 const SCEV *Step = AR->getStepRecurrence(*SE);
435 // The address of the last accessed element, if it can be computed
436 // precisely.
437 const SCEV *LastAddr = nullptr;
438 if (!isa<SCEVCouldNotCompute>(BTC)) {
439 // Evaluating AR at an exact BTC is safe: LAA separately checks that
440 // accesses cannot wrap in the loop. If evaluating AR at BTC wraps, then
441 // the loop either triggers UB when executing a memory access with a
442 // poison pointer or the wrapping/poisoned pointer is not used.
443 LastAddr = AR->evaluateAtIteration(BTC, *SE);
445 AR, MaxBTC, EltSizeSCEV, *SE, DL, DT, AC, LoopGuards)) {
446 LastAddr = AR->evaluateAtIteration(MaxBTC, *SE);
447 }
448 const SCEV *Start = AR->getStart();
449 Type *PtrTy = AR->getType();
450 if (SE->isKnownNegative(Step)) {
451 ScStart =
452 LastAddr
453 ? LastAddr
455 Constant::getNullValue(DL.getIndexType(PtrTy)), PtrTy));
456 ScEnd = SE->getAddExpr(Start, EltSizeSCEV);
457 } else if (SE->isKnownNonNegative(Step)) {
458 ScStart = Start;
459 // The highest address for the type saturates; adding EltSize to it would
460 // wrap to the start of the address space.
461 ScEnd =
462 LastAddr
463 ? SE->getAddExpr(LastAddr, EltSizeSCEV)
465 Constant::getAllOnesValue(DL.getIndexType(PtrTy)), PtrTy));
466 } else {
467 if (!LastAddr)
468 return {SE->getCouldNotCompute(), SE->getCouldNotCompute()};
469 // Fallback case: the step is not constant, but we can still
470 // get the upper and lower bounds of the interval by using min/max
471 // expressions.
472 ScStart = SE->getUMinExpr(Start, LastAddr);
473 ScEnd = SE->getAddExpr(SE->getUMaxExpr(Start, LastAddr), EltSizeSCEV);
474 }
475 } else {
476 // The pointer is loop-variant but not an affine AddRec. Try to form a
477 // tight bound for a monotonic offset (see getNonAffineMonotonicBounds).
478 std::tie(ScStart, ScEnd) =
479 getNonAffineMonotonicBounds(Lp, PtrExpr, EltSizeSCEV, SE);
480 if (!ScStart)
481 return {SE->getCouldNotCompute(), SE->getCouldNotCompute()};
482 }
483
484 assert(SE->isLoopInvariant(ScStart, Lp) && "ScStart needs to be invariant");
485 assert(SE->isLoopInvariant(ScEnd, Lp) && "ScEnd needs to be invariant");
486
487 std::pair<const SCEV *, const SCEV *> Res = {ScStart, ScEnd};
488 if (PointerBounds)
489 *PtrBoundsPair = Res;
490 return Res;
491}
492
493/// Calculate Start and End points of memory access using
494/// getStartAndEndForAccess.
495bool RuntimePointerChecking::insert(Loop *Lp, Value *Ptr, const SCEV *PtrExpr,
496 Type *AccessTy, bool WritePtr,
497 unsigned DepSetId, unsigned ASId,
499 bool NeedsFreeze) {
500 const SCEV *SymbolicMaxBTC = PSE.getSymbolicMaxBackedgeTakenCount();
501 const SCEV *BTC = PSE.getBackedgeTakenCount();
502 const auto &[ScStart, ScEnd] = getStartAndEndForAccess(
503 Lp, PtrExpr, AccessTy, BTC, SymbolicMaxBTC, PSE.getSE(),
504 &DC.getPointerBounds(), DC.getDT(), DC.getAC(), LoopGuards);
506 return false;
507 Pointers.emplace_back(Ptr, ScStart, ScEnd, WritePtr, DepSetId, ASId, PtrExpr,
508 NeedsFreeze);
509 return true;
510}
511
512bool RuntimePointerChecking::tryToCreateDiffCheck(
513 const RuntimeCheckingPtrGroup &CGI, const RuntimeCheckingPtrGroup &CGJ) {
514 // If either group contains multiple different pointers, bail out.
515 // TODO: Support multiple pointers by using the minimum or maximum pointer,
516 // depending on src & sink.
517 if (CGI.Members.size() != 1 || CGJ.Members.size() != 1)
518 return false;
519
520 const PointerInfo *Src = &Pointers[CGI.Members[0]];
521 const PointerInfo *Sink = &Pointers[CGJ.Members[0]];
522
523 // If either pointer is read and written, multiple checks may be needed. Bail
524 // out.
525 if (!DC.getOrderForAccess(Src->PointerValue, !Src->IsWritePtr).empty() ||
526 !DC.getOrderForAccess(Sink->PointerValue, !Sink->IsWritePtr).empty())
527 return false;
528
529 ArrayRef<unsigned> AccSrc =
530 DC.getOrderForAccess(Src->PointerValue, Src->IsWritePtr);
531 ArrayRef<unsigned> AccSink =
532 DC.getOrderForAccess(Sink->PointerValue, Sink->IsWritePtr);
533 // If either pointer is accessed multiple times, there may not be a clear
534 // src/sink relation. Bail out for now.
535 if (AccSrc.size() != 1 || AccSink.size() != 1)
536 return false;
537
538 // If the sink is accessed before src, swap src/sink.
539 if (AccSink[0] < AccSrc[0])
540 std::swap(Src, Sink);
541
542 const SCEVConstant *Step;
543 const SCEV *SrcStart;
544 const SCEV *SinkStart;
545 const Loop *InnerLoop = DC.getInnermostLoop();
546 if (!match(Src->Expr,
548 m_SpecificLoop(InnerLoop))) ||
549 !match(Sink->Expr,
551 m_SpecificLoop(InnerLoop))))
552 return false;
553
555 DC.getInstructionsForAccess(Src->PointerValue, Src->IsWritePtr);
557 DC.getInstructionsForAccess(Sink->PointerValue, Sink->IsWritePtr);
558 Type *SrcTy = getLoadStoreType(SrcInsts[0]);
559 Type *DstTy = getLoadStoreType(SinkInsts[0]);
561 return false;
562
563 const DataLayout &DL = InnerLoop->getHeader()->getDataLayout();
564 unsigned AllocSize =
565 std::max(DL.getTypeAllocSize(SrcTy), DL.getTypeAllocSize(DstTy));
566
567 // Only matching constant steps matching the AllocSize are supported at the
568 // moment. This simplifies the difference computation. Can be extended in the
569 // future.
570 if (Step->getAPInt().abs() != AllocSize)
571 return false;
572
573 // When counting down, the dependence distance needs to be swapped.
574 if (Step->getValue()->isNegative())
575 std::swap(SinkStart, SrcStart);
576
577 const SCEV *SinkStartInt = SE->getPtrToAddrExpr(SinkStart);
578 const SCEV *SrcStartInt = SE->getPtrToAddrExpr(SrcStart);
579 if (isa<SCEVCouldNotCompute>(SinkStartInt) ||
580 isa<SCEVCouldNotCompute>(SrcStartInt))
581 return false;
582
583 // If the start values for both Src and Sink also vary according to an outer
584 // loop, then it's probably better to avoid creating diff checks because
585 // they may not be hoisted. We should instead let llvm::addRuntimeChecks
586 // do the expanded full range overlap checks, which can be hoisted.
587 if (HoistRuntimeChecks && InnerLoop->getParentLoop() &&
588 isa<SCEVAddRecExpr>(SinkStartInt) && isa<SCEVAddRecExpr>(SrcStartInt)) {
589 auto *SrcStartAR = cast<SCEVAddRecExpr>(SrcStartInt);
590 auto *SinkStartAR = cast<SCEVAddRecExpr>(SinkStartInt);
591 const Loop *StartARLoop = SrcStartAR->getLoop();
592 if (StartARLoop == SinkStartAR->getLoop() &&
593 StartARLoop == InnerLoop->getParentLoop() &&
594 // If the diff check would already be loop invariant (due to the
595 // recurrences being the same), then we prefer to keep the diff checks
596 // because they are cheaper.
597 SrcStartAR->getStepRecurrence(*SE) !=
598 SinkStartAR->getStepRecurrence(*SE)) {
599 LLVM_DEBUG(dbgs() << "LAA: Not creating diff runtime check, since these "
600 "cannot be hoisted out of the outer loop\n");
601 return false;
602 }
603 }
604
605 LLVM_DEBUG(dbgs() << "LAA: Creating diff runtime check for:\n"
606 << "SrcStart: " << *SrcStartInt << '\n'
607 << "SinkStartInt: " << *SinkStartInt << '\n');
608 DiffChecks.emplace_back(SrcStartInt, SinkStartInt, AllocSize,
609 Src->NeedsFreeze || Sink->NeedsFreeze);
610 return true;
611}
612
614 SmallVector<RuntimePointerCheck, 4> Checks;
615
616 for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
617 for (unsigned J = I + 1; J < CheckingGroups.size(); ++J) {
620
621 if (needsChecking(CGI, CGJ)) {
622 CanUseDiffCheck = CanUseDiffCheck && tryToCreateDiffCheck(CGI, CGJ);
623 Checks.emplace_back(&CGI, &CGJ);
624 }
625 }
626 }
627 return Checks;
628}
629
632 assert(Checks.empty() && "Checks is not empty");
633 groupChecks(DepCands);
634 Checks = generateChecks();
635}
636
638 const RuntimeCheckingPtrGroup &M, const RuntimeCheckingPtrGroup &N) const {
639 for (const auto &I : M.Members)
640 for (const auto &J : N.Members)
641 if (needsChecking(I, J))
642 return true;
643 return false;
644}
645
646/// Compare \p I and \p J and return the minimum.
647/// Return nullptr in case we couldn't find an answer.
648static const SCEV *getMinFromExprs(const SCEV *I, const SCEV *J,
649 ScalarEvolution *SE) {
650 std::optional<APInt> Diff = SE->computeConstantDifference(J, I);
651 if (!Diff)
652 return nullptr;
653 return Diff->isNegative() ? J : I;
654}
655
657 unsigned Index, const RuntimePointerChecking &RtCheck) {
658 return addPointer(
659 Index, RtCheck.Pointers[Index].Start, RtCheck.Pointers[Index].End,
660 RtCheck.Pointers[Index].PointerValue->getType()->getPointerAddressSpace(),
661 RtCheck.Pointers[Index].NeedsFreeze, *RtCheck.SE);
662}
663
664bool RuntimeCheckingPtrGroup::addPointer(unsigned Index, const SCEV *Start,
665 const SCEV *End, unsigned AS,
666 bool NeedsFreeze,
667 ScalarEvolution &SE) {
668 assert(AddressSpace == AS &&
669 "all pointers in a checking group must be in the same address space");
670
671 // Compare the starts and ends with the known minimum and maximum
672 // of this set. We need to know how we compare against the min/max
673 // of the set in order to be able to emit memchecks.
674 const SCEV *Min0 = getMinFromExprs(Start, Low, &SE);
675 if (!Min0)
676 return false;
677
678 const SCEV *Min1 = getMinFromExprs(End, High, &SE);
679 if (!Min1)
680 return false;
681
682 // Update the low bound expression if we've found a new min value.
683 if (Min0 == Start)
684 Low = Start;
685
686 // Update the high bound expression if we've found a new max value.
687 if (Min1 != End)
688 High = End;
689
690 Members.push_back(Index);
691 this->NeedsFreeze |= NeedsFreeze;
692 return true;
693}
694
695void RuntimePointerChecking::groupChecks(
697 // We build the groups from dependency candidates equivalence classes
698 // because:
699 // - We know that pointers in the same equivalence class share
700 // the same underlying object and therefore there is a chance
701 // that we can compare pointers
702 // - We wouldn't be able to merge two pointers for which we need
703 // to emit a memcheck. The classes in DepCands are already
704 // conveniently built such that no two pointers in the same
705 // class need checking against each other.
706
707 // We use the following (greedy) algorithm to construct the groups
708 // For every pointer in the equivalence class:
709 // For each existing group:
710 // - if the difference between this pointer and the min/max bounds
711 // of the group is a constant, then make the pointer part of the
712 // group and update the min/max bounds of that group as required.
713
714 CheckingGroups.clear();
715
716 // If we need to check two pointers to the same underlying object
717 // with a non-constant difference, we shouldn't perform any pointer
718 // grouping with those pointers. This is because we can easily get
719 // into cases where the resulting check would return false, even when
720 // the accesses are safe.
721 //
722 // The following example shows this:
723 // for (i = 0; i < 1000; ++i)
724 // a[5000 + i * m] = a[i] + a[i + 9000]
725 //
726 // Here grouping gives a check of (5000, 5000 + 1000 * m) against
727 // (0, 10000) which is always false. However, if m is 1, there is no
728 // dependence. Not grouping the checks for a[i] and a[i + 9000] allows
729 // us to perform an accurate check in this case.
730 //
731 // In the above case, we have a non-constant distance and an Unknown
732 // dependence between accesses to the same underlying object, and could retry
733 // with runtime checks without dependency information being available. In this
734 // case we will use the fallback path and create separate checking groups for
735 // accesses not present in DepCands.
736
737 unsigned TotalComparisons = 0;
738
740 for (unsigned Index = 0; Index < Pointers.size(); ++Index)
741 PositionMap[Pointers[Index].PointerValue].push_back(Index);
742
743 // We need to keep track of what pointers we've already seen so we
744 // don't process them twice.
746
747 // Go through all equivalence classes, get the "pointer check groups"
748 // and add them to the overall solution. We use the order in which accesses
749 // appear in 'Pointers' to enforce determinism.
750 for (unsigned I = 0; I < Pointers.size(); ++I) {
751 // We've seen this pointer before, and therefore already processed
752 // its equivalence class.
753 if (Seen.contains(I))
754 continue;
755
757 Pointers[I].IsWritePtr);
758
759 // If there is no entry in the dependency partition, there are no potential
760 // accesses to merge; simply add a new pointer checking group.
761 if (!DepCands.contains(Access)) {
762 CheckingGroups.push_back(RuntimeCheckingPtrGroup(I, *this));
763 continue;
764 }
765
767
768 // Because DepCands is constructed by visiting accesses in the order in
769 // which they appear in alias sets (which is deterministic) and the
770 // iteration order within an equivalence class member is only dependent on
771 // the order in which unions and insertions are performed on the
772 // equivalence class, the iteration order is deterministic.
773 for (auto M : DepCands.members(Access)) {
774 auto PointerI = PositionMap.find(M.getPointer());
775 // If we can't find the pointer in PositionMap that means we can't
776 // generate a memcheck for it.
777 if (PointerI == PositionMap.end())
778 continue;
779 for (unsigned Pointer : PointerI->second) {
780 bool Merged = false;
781 // Mark this pointer as seen.
782 Seen.insert(Pointer);
783
784 // Go through all the existing sets and see if we can find one
785 // which can include this pointer.
786 for (RuntimeCheckingPtrGroup &Group : Groups) {
787 // Don't perform more than a certain amount of comparisons.
788 // This should limit the cost of grouping the pointers to something
789 // reasonable. If we do end up hitting this threshold, the algorithm
790 // will create separate groups for all remaining pointers.
791 if (TotalComparisons > MemoryCheckMergeThreshold)
792 break;
793
794 TotalComparisons++;
795
796 if (Group.addPointer(Pointer, *this)) {
797 Merged = true;
798 break;
799 }
800 }
801
802 if (!Merged)
803 // We couldn't add this pointer to any existing set or the threshold
804 // for the number of comparisons has been reached. Create a new group
805 // to hold the current pointer.
806 Groups.emplace_back(Pointer, *this);
807 }
808 }
809
810 // We've computed the grouped checks for this partition.
811 // Save the results and continue with the next one.
813 }
814}
815
817 const SmallVectorImpl<int> &PtrToPartition, unsigned PtrIdx1,
818 unsigned PtrIdx2) {
819 return (PtrToPartition[PtrIdx1] != -1 &&
820 PtrToPartition[PtrIdx1] == PtrToPartition[PtrIdx2]);
821}
822
823bool RuntimePointerChecking::needsChecking(unsigned I, unsigned J) const {
824 const PointerInfo &PointerI = Pointers[I];
825 const PointerInfo &PointerJ = Pointers[J];
826
827 // No need to check if two readonly pointers intersect.
828 if (!PointerI.IsWritePtr && !PointerJ.IsWritePtr)
829 return false;
830
831 // Only need to check pointers between two different dependency sets.
832 if (PointerI.DependencySetId == PointerJ.DependencySetId)
833 return false;
834
835 // Only need to check pointers in the same alias set.
836 return PointerI.AliasSetId == PointerJ.AliasSetId;
837}
838
839/// Assign each RuntimeCheckingPtrGroup pointer an index for stable UTC output.
843 for (const auto &[Idx, CG] : enumerate(CheckingGroups))
844 PtrIndices[&CG] = Idx;
845 return PtrIndices;
846}
847
850 unsigned Depth) const {
851 unsigned N = 0;
852 auto PtrIndices = getPtrToIdxMap(CheckingGroups);
853 for (const auto &[Check1, Check2] : Checks) {
854 const auto &First = Check1->Members, &Second = Check2->Members;
855 OS.indent(Depth) << "Check " << N++ << ":\n";
856 OS.indent(Depth + 2) << "Comparing group GRP" << PtrIndices.at(Check1)
857 << ":\n";
858 for (unsigned K : First)
859 OS.indent(Depth + 2) << *Pointers[K].PointerValue << "\n";
860 OS.indent(Depth + 2) << "Against group GRP" << PtrIndices.at(Check2)
861 << ":\n";
862 for (unsigned K : Second)
863 OS.indent(Depth + 2) << *Pointers[K].PointerValue << "\n";
864 }
865}
866
868
869 OS.indent(Depth) << "Run-time memory checks:\n";
870 printChecks(OS, Checks, Depth);
871
872 OS.indent(Depth) << "Grouped accesses:\n";
873 auto PtrIndices = getPtrToIdxMap(CheckingGroups);
874 for (const auto &CG : CheckingGroups) {
875 OS.indent(Depth + 2) << "Group GRP" << PtrIndices.at(&CG) << ":\n";
876 OS.indent(Depth + 4) << "(Low: " << *CG.Low << " High: " << *CG.High
877 << ")\n";
878 for (unsigned Member : CG.Members) {
879 OS.indent(Depth + 6) << "Member: " << *Pointers[Member].Expr << "\n";
880 }
881 }
882}
883
884namespace {
885
886/// Analyses memory accesses in a loop.
887///
888/// Checks whether run time pointer checks are needed and builds sets for data
889/// dependence checking.
890class AccessAnalysis {
891public:
892 using MemAccessInfo =
893 PointerIntPair<Value * /* AccessPtr */, 1, bool /* IsWrite */>;
894
895 AccessAnalysis(const Loop *TheLoop, AAResults *AA, const LoopInfo *LI,
898 SmallPtrSetImpl<MDNode *> &LoopAliasScopes)
899 : TheLoop(TheLoop), BAA(*AA), AST(BAA), LI(LI), DT(DT), DepCands(DA),
900 PSE(PSE), LoopAliasScopes(LoopAliasScopes) {
901 // We're analyzing dependences across loop iterations.
902 BAA.enableCrossIterationMode();
903 }
904
905 /// Register a load and whether it is only read from.
906 void addLoad(const MemoryLocation &Loc, Type *AccessTy, bool IsReadOnly) {
907 Value *Ptr = const_cast<Value *>(Loc.Ptr);
908 AST.add(adjustLoc(Loc));
909 Accesses[MemAccessInfo(Ptr, false)].insert(AccessTy);
910 if (IsReadOnly)
911 ReadOnlyPtr.insert(Ptr);
912 }
913
914 /// Register a store.
915 void addStore(const MemoryLocation &Loc, Type *AccessTy) {
916 Value *Ptr = const_cast<Value *>(Loc.Ptr);
917 AST.add(adjustLoc(Loc));
918 Accesses[MemAccessInfo(Ptr, true)].insert(AccessTy);
919 }
920
921 /// Check if we can emit a run-time no-alias check for \p Access.
922 ///
923 /// Returns true if we can emit a run-time no alias check for \p Access.
924 /// If we can check this access, this also adds it to a dependence set and
925 /// adds a run-time to check for it to \p RtCheck. If \p Assume is true,
926 /// we will attempt to use additional run-time checks in order to get
927 /// the bounds of the pointer.
928 bool createCheckForAccess(RuntimePointerChecking &RtCheck,
929 MemAccessInfo Access, Type *AccessTy,
930 const SymbolicStrideMap &Strides,
931 DenseMap<Value *, unsigned> &DepSetId,
932 Loop *TheLoop, unsigned &RunningDepId,
933 unsigned ASId, bool Assume);
934
935 /// Check whether we can check the pointers at runtime for
936 /// non-intersection.
937 ///
938 /// Returns true if we need no check or if we do and we can generate them
939 /// (i.e. the pointers have computable bounds). A return value of false means
940 /// we couldn't analyze and generate runtime checks for all pointers in the
941 /// loop, but if \p AllowPartial is set then we will have checks for those
942 /// pointers we could analyze. \p DepChecker is used to remove unknown
943 /// dependences from DepCands.
944 bool canCheckPtrAtRT(RuntimePointerChecking &RtCheck, Loop *TheLoop,
945 const SymbolicStrideMap &Strides,
946 Value *&UncomputablePtr, bool AllowPartial,
947 const MemoryDepChecker &DepChecker);
948
949 /// Goes over all memory accesses, checks whether a RT check is needed
950 /// and builds sets of dependent accesses.
951 void buildDependenceSets();
952
953 /// Initial processing of memory accesses determined that we need to
954 /// perform dependency checking.
955 ///
956 /// Note that this can later be cleared if we retry memcheck analysis without
957 /// dependency checking (i.e. ShouldRetryWithRuntimeChecks).
958 bool isDependencyCheckNeeded() const { return !CheckDeps.empty(); }
959
960 /// We decided that no dependence analysis would be used. Reset the state.
961 void resetDepChecks(MemoryDepChecker &DepChecker) {
962 CheckDeps.clear();
963 DepChecker.clearDependences();
964 }
965
966 ArrayRef<MemAccessInfo> getDependenciesToCheck() const { return CheckDeps; }
967
968private:
969 using PtrAccessMap = MapVector<MemAccessInfo, SmallSetVector<Type *, 1>>;
970
971 /// Adjust the MemoryLocation so that it represents accesses to this
972 /// location across all iterations, rather than a single one.
973 MemoryLocation adjustLoc(MemoryLocation Loc) const {
974 // The accessed location varies within the loop, but remains within the
975 // underlying object.
977 Loc.AATags.Scope = adjustAliasScopeList(Loc.AATags.Scope);
978 Loc.AATags.NoAlias = adjustAliasScopeList(Loc.AATags.NoAlias);
979 return Loc;
980 }
981
982 /// Drop alias scopes that are only valid within a single loop iteration.
983 MDNode *adjustAliasScopeList(MDNode *ScopeList) const {
984 if (!ScopeList)
985 return nullptr;
986
987 // For the sake of simplicity, drop the whole scope list if any scope is
988 // iteration-local.
989 if (any_of(ScopeList->operands(), [&](Metadata *Scope) {
990 return LoopAliasScopes.contains(cast<MDNode>(Scope));
991 }))
992 return nullptr;
993
994 return ScopeList;
995 }
996
997 /// Map of all accesses. Values are the types used to access memory pointed to
998 /// by the pointer.
999 PtrAccessMap Accesses;
1000
1001 /// The loop being checked.
1002 const Loop *TheLoop;
1003
1004 /// List of accesses that need a further dependence check.
1006
1007 /// Set of pointers that are read only.
1008 SmallPtrSet<Value*, 16> ReadOnlyPtr;
1009
1010 /// Batched alias analysis results.
1011 BatchAAResults BAA;
1012
1013 /// An alias set tracker to partition the access set by underlying object and
1014 //intrinsic property (such as TBAA metadata).
1015 AliasSetTracker AST;
1016
1017 /// The LoopInfo of the loop being checked.
1018 const LoopInfo *LI;
1019
1020 /// The dominator tree of the function.
1021 DominatorTree &DT;
1022
1023 /// Sets of potentially dependent accesses - members of one set share an
1024 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
1025 /// dependence check.
1027
1028 /// Initial processing of memory accesses determined that we may need
1029 /// to add memchecks. Perform the analysis to determine the necessary checks.
1030 ///
1031 /// Note that, this is different from isDependencyCheckNeeded. When we retry
1032 /// memcheck analysis without dependency checking
1033 /// (i.e. ShouldRetryWithRuntimeChecks), isDependencyCheckNeeded is
1034 /// cleared while this remains set if we have potentially dependent accesses.
1035 bool IsRTCheckAnalysisNeeded = false;
1036
1037 /// The SCEV predicate containing all the SCEV-related assumptions.
1038 PredicatedScalarEvolution &PSE;
1039
1040 DenseMap<Value *, SmallVector<const Value *, 16>> UnderlyingObjects;
1041
1042 /// Alias scopes that are declared inside the loop, and as such not valid
1043 /// across iterations.
1044 SmallPtrSetImpl<MDNode *> &LoopAliasScopes;
1045};
1046
1047} // end anonymous namespace
1048
1049std::optional<int64_t>
1051 Type *AccessTy, Value *Ptr,
1053 if (isa<ScalableVectorType>(AccessTy)) {
1054 LLVM_DEBUG(dbgs() << "LAA: Bad stride - Scalable object: " << *AccessTy
1055 << "\n");
1056 return std::nullopt;
1057 }
1058
1059 // The access function must stride over the innermost loop.
1060 if (Lp != AR->getLoop()) {
1061 LLVM_DEBUG({
1062 dbgs() << "LAA: Bad stride - Not striding over innermost loop ";
1063 if (Ptr)
1064 dbgs() << *Ptr << " ";
1065
1066 dbgs() << "SCEV: " << *AR << "\n";
1067 });
1068 return std::nullopt;
1069 }
1070
1071 // Check the step is constant.
1072 const SCEV *Step = AR->getStepRecurrence(*PSE.getSE());
1073
1074 // Calculate the pointer stride and check if it is constant.
1075 const APInt *APStepVal;
1076 if (!match(Step, m_scev_APInt(APStepVal))) {
1077 LLVM_DEBUG({
1078 dbgs() << "LAA: Bad stride - Not a constant strided ";
1079 if (Ptr)
1080 dbgs() << *Ptr << " ";
1081 dbgs() << "SCEV: " << *AR << "\n";
1082 });
1083 return std::nullopt;
1084 }
1085
1086 const auto &DL = Lp->getHeader()->getDataLayout();
1087 TypeSize AllocSize = DL.getTypeAllocSize(AccessTy);
1088 int64_t Size = AllocSize.getFixedValue();
1089
1090 // Huge step value - give up.
1091 std::optional<int64_t> StepVal = APStepVal->trySExtValue();
1092 if (!StepVal)
1093 return std::nullopt;
1094
1095 // Strided access.
1096 return *StepVal % Size ? std::nullopt : std::make_optional(*StepVal / Size);
1097}
1098
1099/// Check whether \p AR is a non-wrapping AddRec. If \p Ptr is not nullptr, use
1100/// information from the IR pointer value to determine no-wrap. If \p Predicates
1101/// is not nullptr add no-wrap assumptions if needed.
1102static bool
1104 Type *AccessTy, const Loop *L, const DominatorTree &DT,
1105 std::optional<int64_t> Stride = std::nullopt,
1106 SmallVectorImpl<const SCEVPredicate *> *Predicates = nullptr) {
1107 // FIXME: This should probably only return true for NUW.
1108 if (any(AR->getNoWrapFlags(SCEV::NoWrapMask)))
1109 return true;
1110
1112 return true;
1113
1114 // An nusw getelementptr that is an AddRec cannot wrap. If it would wrap,
1115 // the distance between the previously accessed location and the wrapped
1116 // location will be larger than half the pointer index type space. In that
1117 // case, the GEP would be poison and any memory access dependent on it would
1118 // be immediate UB when executed.
1120 GEP && GEP->hasNoUnsignedSignedWrap()) {
1121 // For the above reasoning to apply, the pointer must be dereferenced in
1122 // every iteration.
1123 if (L->getHeader() == L->getLoopLatch() ||
1124 any_of(GEP->users(), [L, &DT, GEP](User *U) {
1125 if (getLoadStorePointerOperand(U) != GEP)
1126 return false;
1127 BasicBlock *UserBB = cast<Instruction>(U)->getParent();
1128 if (!L->contains(UserBB))
1129 return false;
1130 return !LoopAccessInfo::blockNeedsPredication(UserBB, L, &DT);
1131 }))
1132 return true;
1133 }
1134
1135 if (!Stride)
1136 Stride = getStrideFromAddRec(AR, L, AccessTy, Ptr, PSE);
1137 if (Stride) {
1138 // If the null pointer is undefined, then a access sequence which would
1139 // otherwise access it can be assumed not to unsigned wrap. Note that this
1140 // assumes the object in memory is aligned to the natural alignment.
1141 unsigned AddrSpace = AR->getType()->getPointerAddressSpace();
1142 if (!NullPointerIsDefined(L->getHeader()->getParent(), AddrSpace) &&
1143 (Stride == 1 || Stride == -1))
1144 return true;
1145 }
1146
1147 if (Ptr && Predicates) {
1148 ScalarEvolution &SE = *PSE.getSE();
1152 Predicates->push_back(SE.getWrapPredicate(AR, Flags));
1153 LLVM_DEBUG(dbgs() << "LAA: Pointer may wrap:\n"
1154 << "LAA: Pointer: " << *Ptr << "\n"
1155 << "LAA: SCEV: " << *AR << "\n"
1156 << "LAA: Added an overflow assumption\n");
1157 return true;
1158 }
1159
1160 return false;
1161}
1162
1163static void visitPointers(Value *StartPtr, const Loop &InnermostLoop,
1164 function_ref<void(Value *)> AddPointer) {
1166 SmallVector<Value *> WorkList;
1167 WorkList.push_back(StartPtr);
1168
1169 while (!WorkList.empty()) {
1170 Value *Ptr = WorkList.pop_back_val();
1171 if (!Visited.insert(Ptr).second)
1172 continue;
1173 auto *PN = dyn_cast<PHINode>(Ptr);
1174 // SCEV does not look through non-header PHIs inside the loop. Such phis
1175 // can be analyzed by adding separate accesses for each incoming pointer
1176 // value.
1177 if (PN && InnermostLoop.contains(PN->getParent()) &&
1178 PN->getParent() != InnermostLoop.getHeader()) {
1179 llvm::append_range(WorkList, PN->incoming_values());
1180 } else
1181 AddPointer(Ptr);
1182 }
1183}
1184
1185// Walk back through the IR for a pointer, looking for a select like the
1186// following:
1187//
1188// %offset = select i1 %cmp, i64 %a, i64 %b
1189// %addr = getelementptr double, double* %base, i64 %offset
1190// %ld = load double, double* %addr, align 8
1191//
1192// We won't be able to form a single SCEVAddRecExpr from this since the
1193// address for each loop iteration depends on %cmp. We could potentially
1194// produce multiple valid SCEVAddRecExprs, though, and check all of them for
1195// memory safety/aliasing if needed.
1196//
1197// If we encounter some IR we don't yet handle, or something obviously fine
1198// like a constant, then we just add the SCEV for that term to the list passed
1199// in by the caller. If we have a node that may potentially yield a valid
1200// SCEVAddRecExpr then we decompose it into parts and build the SCEV terms
1201// ourselves before adding to the list.
1203 ScalarEvolution *SE, const Loop *L, Value *Ptr,
1205 unsigned Depth) {
1206 // If our Value is a SCEVAddRecExpr, loop invariant, not an instruction, or
1207 // we've exceeded our limit on recursion, just return whatever we have
1208 // regardless of whether it can be used for a forked pointer or not, along
1209 // with an indication of whether it might be a poison or undef value.
1210 const SCEV *Scev = SE->getSCEV(Ptr);
1211 if (isa<SCEVAddRecExpr>(Scev) || L->isLoopInvariant(Ptr) ||
1212 !isa<Instruction>(Ptr) || Depth == 0) {
1213 ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr));
1214 return;
1215 }
1216
1217 Depth--;
1218
1219 auto UndefPoisonCheck = [](PointerIntPair<const SCEV *, 1, bool> S) {
1220 return get<1>(S);
1221 };
1222
1223 auto GetBinOpExpr = [&SE](unsigned Opcode, const SCEV *L, const SCEV *R) {
1224 switch (Opcode) {
1225 case Instruction::Add:
1226 return SE->getAddExpr(L, R);
1227 case Instruction::Sub:
1228 return SE->getMinusSCEV(L, R);
1229 default:
1230 llvm_unreachable("Unexpected binary operator when walking ForkedPtrs");
1231 }
1232 };
1233
1235 unsigned Opcode = I->getOpcode();
1236 switch (Opcode) {
1237 case Instruction::GetElementPtr: {
1238 auto *GEP = cast<GetElementPtrInst>(I);
1239 Type *SourceTy = GEP->getSourceElementType();
1240 // We only handle base + single offset GEPs here for now.
1241 // Not dealing with preexisting gathers yet, so no vectors.
1242 if (I->getNumOperands() != 2 || SourceTy->isVectorTy()) {
1243 ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(GEP));
1244 break;
1245 }
1248 findForkedSCEVs(SE, L, I->getOperand(0), BaseScevs, Depth);
1249 findForkedSCEVs(SE, L, I->getOperand(1), OffsetScevs, Depth);
1250
1251 // See if we need to freeze our fork...
1252 bool NeedsFreeze = any_of(BaseScevs, UndefPoisonCheck) ||
1253 any_of(OffsetScevs, UndefPoisonCheck);
1254
1255 // Check that we only have a single fork, on either the base or the offset.
1256 // Copy the SCEV across for the one without a fork in order to generate
1257 // the full SCEV for both sides of the GEP.
1258 if (OffsetScevs.size() == 2 && BaseScevs.size() == 1)
1259 BaseScevs.push_back(BaseScevs[0]);
1260 else if (BaseScevs.size() == 2 && OffsetScevs.size() == 1)
1261 OffsetScevs.push_back(OffsetScevs[0]);
1262 else {
1263 ScevList.emplace_back(Scev, NeedsFreeze);
1264 break;
1265 }
1266
1267 Type *IntPtrTy = SE->getEffectiveSCEVType(GEP->getPointerOperandType());
1268
1269 // Find the size of the type being pointed to. We only have a single
1270 // index term (guarded above) so we don't need to index into arrays or
1271 // structures, just get the size of the scalar value.
1272 const SCEV *Size = SE->getSizeOfExpr(IntPtrTy, SourceTy);
1273
1274 for (auto [B, O] : zip(BaseScevs, OffsetScevs)) {
1275 const SCEV *Base = get<0>(B);
1276 const SCEV *Offset = get<0>(O);
1277
1278 // Scale up the offsets by the size of the type, then add to the bases.
1279 const SCEV *Scaled =
1281 ScevList.emplace_back(SE->getAddExpr(Base, Scaled), NeedsFreeze);
1282 }
1283 break;
1284 }
1285 case Instruction::Select: {
1287 // A select means we've found a forked pointer, but we currently only
1288 // support a single select per pointer so if there's another behind this
1289 // then we just bail out and return the generic SCEV.
1290 findForkedSCEVs(SE, L, I->getOperand(1), ChildScevs, Depth);
1291 findForkedSCEVs(SE, L, I->getOperand(2), ChildScevs, Depth);
1292 if (ChildScevs.size() == 2)
1293 append_range(ScevList, ChildScevs);
1294 else
1295 ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr));
1296 break;
1297 }
1298 case Instruction::PHI: {
1300 // A phi means we've found a forked pointer, but we currently only
1301 // support a single phi per pointer so if there's another behind this
1302 // then we just bail out and return the generic SCEV.
1303 if (I->getNumOperands() == 2) {
1304 findForkedSCEVs(SE, L, I->getOperand(0), ChildScevs, Depth);
1305 findForkedSCEVs(SE, L, I->getOperand(1), ChildScevs, Depth);
1306 }
1307 if (ChildScevs.size() == 2)
1308 append_range(ScevList, ChildScevs);
1309 else
1310 ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr));
1311 break;
1312 }
1313 case Instruction::Add:
1314 case Instruction::Sub: {
1317 findForkedSCEVs(SE, L, I->getOperand(0), LScevs, Depth);
1318 findForkedSCEVs(SE, L, I->getOperand(1), RScevs, Depth);
1319
1320 // See if we need to freeze our fork...
1321 bool NeedsFreeze =
1322 any_of(LScevs, UndefPoisonCheck) || any_of(RScevs, UndefPoisonCheck);
1323
1324 // Check that we only have a single fork, on either the left or right side.
1325 // Copy the SCEV across for the one without a fork in order to generate
1326 // the full SCEV for both sides of the BinOp.
1327 if (LScevs.size() == 2 && RScevs.size() == 1)
1328 RScevs.push_back(RScevs[0]);
1329 else if (RScevs.size() == 2 && LScevs.size() == 1)
1330 LScevs.push_back(LScevs[0]);
1331 else {
1332 ScevList.emplace_back(Scev, NeedsFreeze);
1333 break;
1334 }
1335
1336 for (auto [L, R] : zip(LScevs, RScevs))
1337 ScevList.emplace_back(GetBinOpExpr(Opcode, get<0>(L), get<0>(R)),
1338 NeedsFreeze);
1339 break;
1340 }
1341 default:
1342 // Just return the current SCEV if we haven't handled the instruction yet.
1343 LLVM_DEBUG(dbgs() << "ForkedPtr unhandled instruction: " << *I << "\n");
1344 ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr));
1345 break;
1346 }
1347}
1348
1349bool AccessAnalysis::createCheckForAccess(RuntimePointerChecking &RtCheck,
1350 MemAccessInfo Access, Type *AccessTy,
1351 const SymbolicStrideMap &StridesMap,
1353 Loop *TheLoop, unsigned &RunningDepId,
1354 unsigned ASId, bool Assume) {
1355 Value *Ptr = Access.getPointer();
1356 ScalarEvolution *SE = PSE.getSE();
1357 const DataLayout &DL = TheLoop->getHeader()->getDataLayout();
1358 assert(SE->isSCEVable(Ptr->getType()) && "Value is not SCEVable!");
1359
1361 findForkedSCEVs(SE, TheLoop, Ptr, RTCheckPtrs, MaxForkedSCEVDepth);
1362 assert(!RTCheckPtrs.empty() &&
1363 "Must have some runtime-check pointer candidates");
1364
1365 // RTCheckPtrs must have size 2 if there are forked pointers. Otherwise, there
1366 // are no forked pointers; replaceSymbolicStridesSCEV in this case.
1367 auto IsLoopInvariantOrAR =
1368 [&SE, &TheLoop](const PointerIntPair<const SCEV *, 1, bool> &P) {
1369 return SE->isLoopInvariant(P.getPointer(), TheLoop) ||
1370 isa<SCEVAddRecExpr>(P.getPointer());
1371 };
1372 if (RTCheckPtrs.size() == 2 && all_of(RTCheckPtrs, IsLoopInvariantOrAR)) {
1373 LLVM_DEBUG(dbgs() << "LAA: Found forked pointer: " << *Ptr << "\n";
1374 for (const auto &[Idx, Q] : enumerate(RTCheckPtrs)) dbgs()
1375 << "\t(" << Idx << ") " << *Q.getPointer() << "\n");
1376 } else {
1377 RTCheckPtrs = {{replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr), false}};
1378 }
1379
1380 /// Check whether all pointers can participate in a runtime bounds check. They
1381 /// must either be invariant or non-wrapping affine AddRecs.
1383 for (auto &P : RTCheckPtrs) {
1384 // The bounds for loop-invariant pointer is trivial.
1385 if (SE->isLoopInvariant(P.getPointer(), TheLoop))
1386 continue;
1387
1388 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(P.getPointer());
1389 if (!AR && Assume)
1390 AR = PSE.getAsAddRec(Ptr, &Predicates);
1391 if (!AR || !AR->isAffine()) {
1392 // Check if bounds for non-affine monotonic expressions can be formed.
1393 const SCEV *EltSizeSCEV = SE->getStoreSizeOfExpr(
1394 DL.getIndexType(P.getPointer()->getType()), AccessTy);
1395 if (!Assume ||
1396 !getNonAffineMonotonicBounds(TheLoop, P.getPointer(), EltSizeSCEV, SE)
1397 .first)
1398 return false;
1399 continue;
1400 }
1401
1402 // If there's only one option for Ptr, commit the predicates collected by
1403 // getAsAddRec and look Ptr up again afterwards: the lookup below reads the
1404 // assumptions back from PSE, so they need to be committed first.
1405 if (RTCheckPtrs.size() == 1) {
1406 PSE.addPredicates(Predicates);
1407 Predicates.clear();
1408 if (auto *StrideAR = dyn_cast<SCEVAddRecExpr>(
1409 replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr)))
1410 AR = StrideAR;
1411 P.setPointer(AR);
1412 }
1413
1414 if (!isNoWrap(PSE, AR, RTCheckPtrs.size() == 1 ? Ptr : nullptr, AccessTy,
1415 TheLoop, DT, /*Stride=*/std::nullopt,
1416 Assume ? &Predicates : nullptr))
1417 return false;
1418 }
1419 PSE.addPredicates(Predicates);
1420
1421 // Remember the number of pointers inserted so far, to remove the pointers of
1422 // this access again if the bounds of any of them cannot be computed, to avoid
1423 // partial inserts.
1424 unsigned NumPointers = RtCheck.Pointers.size();
1425 for (const auto &[PtrExpr, NeedsFreeze] : RTCheckPtrs) {
1426 // The id of the dependence set.
1427 unsigned DepId;
1428
1429 if (DepCands.contains(Access)) {
1430 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
1431 unsigned &LeaderId = DepSetId[Leader];
1432 if (!LeaderId)
1433 LeaderId = RunningDepId++;
1434 DepId = LeaderId;
1435 } else
1436 // Each access has its own dependence set.
1437 DepId = RunningDepId++;
1438
1439 bool IsWrite = Access.getInt();
1440 if (!RtCheck.insert(TheLoop, Ptr, PtrExpr, AccessTy, IsWrite, DepId, ASId,
1441 PSE, NeedsFreeze)) {
1442 RtCheck.Pointers.truncate(NumPointers);
1443 return false;
1444 }
1445 LLVM_DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
1446 }
1447
1448 return true;
1449}
1450
1451bool AccessAnalysis::canCheckPtrAtRT(RuntimePointerChecking &RtCheck,
1452 Loop *TheLoop,
1453 const SymbolicStrideMap &StridesMap,
1454 Value *&UncomputablePtr, bool AllowPartial,
1455 const MemoryDepChecker &DepChecker) {
1456 // Find pointers with computable bounds. We are going to use this information
1457 // to place a runtime bound check.
1458 bool CanDoRT = true;
1459
1460 bool MayNeedRTCheck = false;
1461 if (!IsRTCheckAnalysisNeeded) return true;
1462
1463 if (auto *Deps = DepChecker.getDependences()) {
1464 // If there are unknown dependences, this means runtime checks are needed to
1465 // ensure there's no overlap between accesses to the same underlying object.
1466 // Remove the equivalence classes containing both source and destination
1467 // accesses from DepCands. This ensures runtime checks will be generated
1468 // between those accesses and prevents them from being grouped together.
1469 for (const auto &Dep : *Deps) {
1470 if (Dep.Type != MemoryDepChecker::Dependence::Unknown) {
1473 "Should only skip safe dependences");
1474 continue;
1475 }
1476 Instruction *Src = Dep.getSource(DepChecker);
1477 Instruction *Dst = Dep.getDestination(DepChecker);
1478 DepCands.eraseClass({getPointerOperand(Src), Src->mayWriteToMemory()});
1479 DepCands.eraseClass({getPointerOperand(Dst), Dst->mayWriteToMemory()});
1480 }
1481 } else {
1482 CheckDeps.clear();
1483 DepCands = {};
1484 }
1485
1486 // We assign a consecutive id to access from different alias sets.
1487 // Accesses between different groups doesn't need to be checked.
1488 unsigned ASId = 0;
1489 for (const auto &AS : AST) {
1490 int NumReadPtrChecks = 0;
1491 int NumWritePtrChecks = 0;
1492 bool CanDoAliasSetRT = true;
1493 ++ASId;
1494 auto ASPointers = AS.getPointers();
1495
1496 // We assign consecutive id to access from different dependence sets.
1497 // Accesses within the same set don't need a runtime check.
1498 unsigned RunningDepId = 1;
1500
1502
1503 // First, count how many write and read accesses are in the alias set. Also
1504 // collect MemAccessInfos for later.
1506 for (const Value *ConstPtr : ASPointers) {
1507 Value *Ptr = const_cast<Value *>(ConstPtr);
1508 bool IsWrite = Accesses.contains(MemAccessInfo(Ptr, true));
1509 if (IsWrite)
1510 ++NumWritePtrChecks;
1511 else
1512 ++NumReadPtrChecks;
1513 AccessInfos.emplace_back(Ptr, IsWrite);
1514 }
1515
1516 // We do not need runtime checks for this alias set, if there are no writes
1517 // or a single write and no reads.
1518 if (NumWritePtrChecks == 0 ||
1519 (NumWritePtrChecks == 1 && NumReadPtrChecks == 0)) {
1520 assert((ASPointers.size() <= 1 ||
1521 all_of(ASPointers,
1522 [this](const Value *Ptr) {
1523 MemAccessInfo AccessWrite(const_cast<Value *>(Ptr),
1524 true);
1525 return !DepCands.contains(AccessWrite);
1526 })) &&
1527 "Can only skip updating CanDoRT below, if all entries in AS "
1528 "are reads or there is at most 1 entry");
1529 continue;
1530 }
1531
1532 for (auto &Access : AccessInfos) {
1533 for (const auto &AccessTy : Accesses[Access]) {
1534 if (!createCheckForAccess(RtCheck, Access, AccessTy, StridesMap,
1535 DepSetId, TheLoop, RunningDepId, ASId,
1536 false)) {
1537 LLVM_DEBUG(dbgs() << "LAA: Can't find bounds for ptr:"
1538 << *Access.getPointer() << '\n');
1539 Retries.emplace_back(Access, AccessTy);
1540 CanDoAliasSetRT = false;
1541 }
1542 }
1543 }
1544
1545 // Note that this function computes CanDoRT and MayNeedRTCheck
1546 // independently. For example CanDoRT=false, MayNeedRTCheck=false means that
1547 // we have a pointer for which we couldn't find the bounds but we don't
1548 // actually need to emit any checks so it does not matter.
1549 //
1550 // We need runtime checks for this alias set, if there are at least 2
1551 // dependence sets (in which case RunningDepId > 2) or if we need to re-try
1552 // any bound checks (because in that case the number of dependence sets is
1553 // incomplete).
1554 bool NeedsAliasSetRTCheck = RunningDepId > 2 || !Retries.empty();
1555
1556 // We need to perform run-time alias checks, but some pointers had bounds
1557 // that couldn't be checked.
1558 if (NeedsAliasSetRTCheck && !CanDoAliasSetRT) {
1559 // Reset the CanDoSetRt flag and retry all accesses that have failed.
1560 // We know that we need these checks, so we can now be more aggressive
1561 // and add further checks if required (overflow checks).
1562 CanDoAliasSetRT = true;
1563 for (const auto &[Access, AccessTy] : Retries) {
1564 if (!createCheckForAccess(RtCheck, Access, AccessTy, StridesMap,
1565 DepSetId, TheLoop, RunningDepId, ASId,
1566 /*Assume=*/true)) {
1567 CanDoAliasSetRT = false;
1568 UncomputablePtr = Access.getPointer();
1569 if (!AllowPartial)
1570 break;
1571 }
1572 }
1573 }
1574
1575 CanDoRT &= CanDoAliasSetRT;
1576 MayNeedRTCheck |= NeedsAliasSetRTCheck;
1577 ++ASId;
1578 }
1579
1580 // If the pointers that we would use for the bounds comparison have different
1581 // address spaces, assume the values aren't directly comparable, so we can't
1582 // use them for the runtime check. We also have to assume they could
1583 // overlap. In the future there should be metadata for whether address spaces
1584 // are disjoint.
1585 unsigned NumPointers = RtCheck.Pointers.size();
1586 for (unsigned i = 0; i < NumPointers; ++i) {
1587 for (unsigned j = i + 1; j < NumPointers; ++j) {
1588 // Only need to check pointers between two different dependency sets.
1589 if (RtCheck.Pointers[i].DependencySetId ==
1590 RtCheck.Pointers[j].DependencySetId)
1591 continue;
1592 // Only need to check pointers in the same alias set.
1593 if (RtCheck.Pointers[i].AliasSetId != RtCheck.Pointers[j].AliasSetId)
1594 continue;
1595
1596 Value *PtrI = RtCheck.Pointers[i].PointerValue;
1597 Value *PtrJ = RtCheck.Pointers[j].PointerValue;
1598
1599 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
1600 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
1601 if (ASi != ASj) {
1602 LLVM_DEBUG(
1603 dbgs() << "LAA: Runtime check would require comparison between"
1604 " different address spaces\n");
1605 return false;
1606 }
1607 }
1608 }
1609
1610 if (MayNeedRTCheck && (CanDoRT || AllowPartial))
1611 RtCheck.generateChecks(DepCands);
1612
1613 LLVM_DEBUG(dbgs() << "LAA: We need to do " << RtCheck.getNumberOfChecks()
1614 << " pointer comparisons.\n");
1615
1616 // If we can do run-time checks, but there are no checks, no runtime checks
1617 // are needed. This can happen when all pointers point to the same underlying
1618 // object for example.
1619 RtCheck.Need = CanDoRT ? RtCheck.getNumberOfChecks() != 0 : MayNeedRTCheck;
1620
1621 bool CanDoRTIfNeeded = !RtCheck.Need || CanDoRT;
1622 assert(CanDoRTIfNeeded == (CanDoRT || !MayNeedRTCheck) &&
1623 "CanDoRTIfNeeded depends on RtCheck.Need");
1624 if (!CanDoRTIfNeeded && !AllowPartial)
1625 RtCheck.reset();
1626 return CanDoRTIfNeeded;
1627}
1628
1629void AccessAnalysis::buildDependenceSets() {
1630 // We process the set twice: first we process read-write pointers, last we
1631 // process read-only pointers. This allows us to skip dependence tests for
1632 // read-only pointers.
1633
1634 LLVM_DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
1635 LLVM_DEBUG(dbgs() << " AST: "; AST.dump());
1636 LLVM_DEBUG(dbgs() << "LAA: Accesses(" << Accesses.size() << "):\n");
1637 LLVM_DEBUG({
1638 for (const auto &[A, _] : Accesses)
1639 dbgs() << "\t" << *A.getPointer() << " ("
1640 << (A.getInt()
1641 ? "write"
1642 : (ReadOnlyPtr.contains(A.getPointer()) ? "read-only"
1643 : "read"))
1644 << ")\n";
1645 });
1646
1647 // The AliasSetTracker has nicely partitioned our pointers by metadata
1648 // compatibility and potential for underlying-object overlap. As a result, we
1649 // only need to check for potential pointer dependencies within each alias
1650 // set.
1651 for (const auto &AS : AST) {
1652 bool AliasSetHasWrite = false;
1653
1654 // Map of (pointer to underlying objects, accessed address space) to last
1655 // access encountered.
1656 using UnderlyingObjToAccessMap =
1658 UnderlyingObjToAccessMap ObjToLastAccess;
1659
1660 // Set of access to check after all writes have been processed.
1661 PtrAccessMap DeferredAccesses;
1662
1663 // Iterate over each alias set twice, once to process read/write pointers,
1664 // and then to process read-only pointers.
1665
1666 auto ProcessAccesses = [&](bool UseDeferred) {
1667 PtrAccessMap &S = UseDeferred ? DeferredAccesses : Accesses;
1668
1669 // Note that both the alias-set tracker and the alias sets themselves used
1670 // ordered collections internally and so the iteration order here is
1671 // deterministic.
1672 for (const Value *ConstPtr : AS.getPointers()) {
1673 Value *Ptr = const_cast<Value *>(ConstPtr);
1674
1675 // For a single memory access in AliasSetTracker, Accesses may contain
1676 // both read and write, and they both need to be handled for CheckDeps.
1677 for (auto [AccessPtr, IsWrite] : S.keys()) {
1678 if (AccessPtr != Ptr)
1679 continue;
1680
1681 // If we're using the deferred access set, then it contains only
1682 // reads.
1683 bool IsReadOnlyPtr = ReadOnlyPtr.contains(Ptr) && !IsWrite;
1684 if (UseDeferred && !IsReadOnlyPtr)
1685 continue;
1686 // Otherwise, the pointer must be in the PtrAccessSet, either as a
1687 // read or a write.
1688 assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
1689 S.contains(MemAccessInfo(Ptr, false))) &&
1690 "Alias-set pointer not in the access set?");
1691
1692 MemAccessInfo Access(Ptr, IsWrite);
1693 DepCands.insert(Access);
1694
1695 // Memorize read-only pointers for later processing and skip them in
1696 // the first round (they need to be checked after we have seen all
1697 // write pointers). Note: we also mark pointer that are not
1698 // consecutive as "read-only" pointers (so that we check
1699 // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
1700 if (!UseDeferred && IsReadOnlyPtr) {
1701 // We only use the pointer keys, the types vector values don't
1702 // matter.
1703 DeferredAccesses.insert({Access, {}});
1704 continue;
1705 }
1706
1707 // If this is a write - check other reads and writes for conflicts. If
1708 // this is a read only check other writes for conflicts (but only if
1709 // there is no other write to the ptr - this is an optimization to
1710 // catch "a[i] = a[i] + " without having to do a dependence check).
1711 if ((IsWrite || IsReadOnlyPtr) && AliasSetHasWrite) {
1712 CheckDeps.push_back(Access);
1713 IsRTCheckAnalysisNeeded = true;
1714 }
1715
1716 if (IsWrite)
1717 AliasSetHasWrite = true;
1718
1719 // Create sets of pointers connected by a shared alias set and
1720 // underlying object.
1721 SmallVector<const Value *, 16> &UOs = UnderlyingObjects[Ptr];
1722 UOs = {};
1723 ::getUnderlyingObjects(Ptr, UOs, LI);
1725 << "Underlying objects for pointer " << *Ptr << "\n");
1726 for (const Value *UnderlyingObj : UOs) {
1727 // nullptr never alias, don't join sets for pointer that have "null"
1728 // in their UnderlyingObjects list.
1729 if (isa<ConstantPointerNull>(UnderlyingObj) &&
1731 TheLoop->getHeader()->getParent(),
1732 UnderlyingObj->getType()->getPointerAddressSpace()))
1733 continue;
1734
1735 auto [It, Inserted] = ObjToLastAccess.try_emplace(
1736 {UnderlyingObj,
1737 cast<PointerType>(Ptr->getType())->getAddressSpace()},
1738 Access);
1739 if (!Inserted) {
1740 DepCands.unionSets(Access, It->second);
1741 It->second = Access;
1742 }
1743
1744 LLVM_DEBUG(dbgs() << " " << *UnderlyingObj << "\n");
1745 }
1746 }
1747 }
1748 };
1749
1750 ProcessAccesses(false);
1751 ProcessAccesses(true);
1752 }
1753}
1754
1755/// Check whether the access through \p Ptr has a constant stride.
1756std::optional<int64_t>
1758 const Loop *Lp, const DominatorTree &DT,
1759 const SymbolicStrideMap &StridesMap, bool ShouldCheckWrap,
1761 const SCEV *PtrScev = replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr);
1762 if (PSE.getSE()->isLoopInvariant(PtrScev, Lp))
1763 return 0;
1764
1765 assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
1766
1767 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
1768 if (Predicates && !AR) {
1769 AR = PSE.getSE()->convertSCEVToAddRecWithPredicates(PtrScev, Lp,
1770 *Predicates);
1771 }
1772
1773 if (!AR) {
1774 LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer " << *Ptr
1775 << " SCEV: " << *PtrScev << "\n");
1776 return std::nullopt;
1777 }
1778
1779 std::optional<int64_t> Stride =
1780 getStrideFromAddRec(AR, Lp, AccessTy, Ptr, PSE);
1781 if (!ShouldCheckWrap || !Stride)
1782 return Stride;
1783
1784 if (isNoWrap(PSE, AR, Ptr, AccessTy, Lp, DT, Stride, Predicates))
1785 return Stride;
1786
1787 LLVM_DEBUG(
1788 dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
1789 << *Ptr << " SCEV: " << *AR << "\n");
1790 return std::nullopt;
1791}
1792
1793/// Check whether the access through \p Ptr has a constant stride.
1795 Type *AccessTy, Value *Ptr,
1796 const Loop *Lp,
1797 const DominatorTree &DT,
1798 const SymbolicStrideMap &StridesMap,
1799 bool Assume, bool ShouldCheckWrap) {
1801 std::optional<int64_t> Stride =
1802 getPtrStride(PSE, AccessTy, Ptr, Lp, DT, StridesMap, ShouldCheckWrap,
1803 Assume ? &Predicates : nullptr);
1804 PSE.addPredicates(Predicates);
1805 return Stride;
1806}
1807
1808std::optional<int64_t> llvm::getPointersDiff(Type *ElemTyA, Value *PtrA,
1809 Type *ElemTyB, Value *PtrB,
1810 const DataLayout &DL,
1811 ScalarEvolution &SE,
1812 bool StrictCheck, bool CheckType) {
1813 assert(PtrA && PtrB && "Expected non-nullptr pointers.");
1814
1815 // Make sure that A and B are different pointers.
1816 if (PtrA == PtrB)
1817 return 0;
1818
1819 // Make sure that the element types are the same if required.
1820 if (CheckType && ElemTyA != ElemTyB)
1821 return std::nullopt;
1822
1823 unsigned ASA = PtrA->getType()->getPointerAddressSpace();
1824 unsigned ASB = PtrB->getType()->getPointerAddressSpace();
1825
1826 // Check that the address spaces match.
1827 if (ASA != ASB)
1828 return std::nullopt;
1829 unsigned IdxWidth = DL.getIndexSizeInBits(ASA);
1830
1831 APInt OffsetA(IdxWidth, 0), OffsetB(IdxWidth, 0);
1832 const Value *PtrA1 = PtrA->stripAndAccumulateConstantOffsets(
1833 DL, OffsetA, /*AllowNonInbounds=*/true);
1834 const Value *PtrB1 = PtrB->stripAndAccumulateConstantOffsets(
1835 DL, OffsetB, /*AllowNonInbounds=*/true);
1836
1837 std::optional<int64_t> Val;
1838 if (PtrA1 == PtrB1) {
1839 // Retrieve the address space again as pointer stripping now tracks through
1840 // `addrspacecast`.
1841 ASA = cast<PointerType>(PtrA1->getType())->getAddressSpace();
1842 ASB = cast<PointerType>(PtrB1->getType())->getAddressSpace();
1843 // Check that the address spaces match and that the pointers are valid.
1844 if (ASA != ASB)
1845 return std::nullopt;
1846
1847 IdxWidth = DL.getIndexSizeInBits(ASA);
1848 OffsetA = OffsetA.sextOrTrunc(IdxWidth);
1849 OffsetB = OffsetB.sextOrTrunc(IdxWidth);
1850
1851 OffsetB -= OffsetA;
1852 Val = OffsetB.trySExtValue();
1853 } else {
1854 // Otherwise compute the distance with SCEV between the base pointers.
1855 const SCEV *PtrSCEVA = SE.getSCEV(PtrA);
1856 const SCEV *PtrSCEVB = SE.getSCEV(PtrB);
1857 std::optional<APInt> Diff =
1858 SE.computeConstantDifference(PtrSCEVB, PtrSCEVA);
1859 if (!Diff)
1860 return std::nullopt;
1861 Val = Diff->trySExtValue();
1862 }
1863
1864 if (!Val)
1865 return std::nullopt;
1866
1867 int64_t Size = DL.getTypeStoreSize(ElemTyA);
1868 int64_t Dist = *Val / Size;
1869
1870 // Ensure that the calculated distance matches the type-based one after all
1871 // the bitcasts removal in the provided pointers.
1872 if (!StrictCheck || Dist * Size == Val)
1873 return Dist;
1874 return std::nullopt;
1875}
1876
1878 const DataLayout &DL, ScalarEvolution &SE,
1879 SmallVectorImpl<unsigned> &SortedIndices) {
1881 VL, [](const Value *V) { return V->getType()->isPointerTy(); }) &&
1882 "Expected list of pointer operands.");
1883 // Walk over the pointers, and map each of them to an offset relative to
1884 // first pointer in the array.
1885 Value *Ptr0 = VL[0];
1886
1887 using DistOrdPair = std::pair<int64_t, unsigned>;
1888 auto Compare = llvm::less_first();
1889 std::set<DistOrdPair, decltype(Compare)> Offsets(Compare);
1890 Offsets.emplace(0, 0);
1891 bool IsConsecutive = true;
1892 for (auto [Idx, Ptr] : drop_begin(enumerate(VL))) {
1893 std::optional<int64_t> Diff =
1894 getPointersDiff(ElemTy, Ptr0, ElemTy, Ptr, DL, SE,
1895 /*StrictCheck=*/true);
1896 if (!Diff)
1897 return false;
1898
1899 // Check if the pointer with the same offset is found.
1900 int64_t Offset = *Diff;
1901 auto [It, IsInserted] = Offsets.emplace(Offset, Idx);
1902 if (!IsInserted)
1903 return false;
1904 // Consecutive order if the inserted element is the last one.
1905 IsConsecutive &= std::next(It) == Offsets.end();
1906 }
1907 SortedIndices.clear();
1908 if (!IsConsecutive) {
1909 // Fill SortedIndices array only if it is non-consecutive.
1910 SortedIndices.resize(VL.size());
1911 for (auto [Idx, Off] : enumerate(Offsets))
1912 SortedIndices[Idx] = Off.second;
1913 }
1914 return true;
1915}
1916
1917/// Returns true if the memory operations \p A and \p B are consecutive.
1919 ScalarEvolution &SE, bool CheckType) {
1922 if (!PtrA || !PtrB)
1923 return false;
1924 Type *ElemTyA = getLoadStoreType(A);
1925 Type *ElemTyB = getLoadStoreType(B);
1926 std::optional<int64_t> Diff =
1927 getPointersDiff(ElemTyA, PtrA, ElemTyB, PtrB, DL, SE,
1928 /*StrictCheck=*/true, CheckType);
1929 return Diff == 1;
1930}
1931
1933 visitPointers(SI->getPointerOperand(), *InnermostLoop,
1934 [this, SI](Value *Ptr) {
1935 Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
1936 InstMap.push_back(SI);
1937 ++AccessIdx;
1938 });
1939}
1940
1942 visitPointers(LI->getPointerOperand(), *InnermostLoop,
1943 [this, LI](Value *Ptr) {
1944 Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
1945 InstMap.push_back(LI);
1946 ++AccessIdx;
1947 });
1948}
1949
1969
1971 switch (Type) {
1972 case NoDep:
1973 case Forward:
1975 case Unknown:
1976 case IndirectUnsafe:
1977 case InvariantUnsafe:
1978 return false;
1979
1981 case Backward:
1983 return true;
1984 }
1985 llvm_unreachable("unexpected DepType!");
1986}
1987
1992
1994 switch (Type) {
1995 case Forward:
1997 return true;
1998
1999 case NoDep:
2000 case Unknown:
2002 case Backward:
2004 case IndirectUnsafe:
2005 case InvariantUnsafe:
2006 return false;
2007 }
2008 llvm_unreachable("unexpected DepType!");
2009}
2010
2011bool MemoryDepChecker::couldPreventStoreLoadForward(uint64_t Distance,
2012 uint64_t TypeByteSize,
2013 unsigned CommonStride) {
2014 // If loads occur at a distance that is not a multiple of a feasible vector
2015 // factor store-load forwarding does not take place.
2016 // Positive dependences might cause troubles because vectorizing them might
2017 // prevent store-load forwarding making vectorized code run a lot slower.
2018 // a[i] = a[i-3] ^ a[i-8];
2019 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
2020 // hence on your typical architecture store-load forwarding does not take
2021 // place. Vectorizing in such cases does not make sense.
2022 // Store-load forwarding distance.
2023
2024 // Maximum vector factor.
2025 uint64_t MaxVFWithoutSLForwardIssuesPowerOf2 =
2026 std::min(VectorizerParams::MaxVectorWidth * TypeByteSize,
2027 MaxStoreLoadForwardSafeDistanceInBits);
2028
2029 // Compute the smallest VF at which the store and load would be misaligned
2030 // and recent enough to still be in the store buffer.
2031 for (uint64_t VF = 2 * TypeByteSize;
2032 VF <= MaxVFWithoutSLForwardIssuesPowerOf2; VF *= 2) {
2033 if (isStoreLoadForwardingConflict(Distance, VF, TypeByteSize, VF)) {
2034 MaxVFWithoutSLForwardIssuesPowerOf2 = (VF >> 1);
2035 break;
2036 }
2037 }
2038
2039 if (MaxVFWithoutSLForwardIssuesPowerOf2 < 2 * TypeByteSize) {
2040 LLVM_DEBUG(
2041 dbgs() << "LAA: Distance " << Distance
2042 << " that could cause a store-load forwarding conflict\n");
2043 return true;
2044 }
2045
2046 if (CommonStride &&
2047 MaxVFWithoutSLForwardIssuesPowerOf2 <
2048 MaxStoreLoadForwardSafeDistanceInBits &&
2049 MaxVFWithoutSLForwardIssuesPowerOf2 !=
2050 VectorizerParams::MaxVectorWidth * TypeByteSize) {
2051 uint64_t MaxVF =
2052 bit_floor(MaxVFWithoutSLForwardIssuesPowerOf2 / CommonStride);
2053 uint64_t MaxVFInBits = MaxVF * TypeByteSize * 8;
2054 MaxStoreLoadForwardSafeDistanceInBits =
2055 std::min(MaxStoreLoadForwardSafeDistanceInBits, MaxVFInBits);
2056
2057 if (MaxVF < 2) {
2058 LLVM_DEBUG(
2059 dbgs() << "LAA: strided access with Distance " << Distance
2060 << " that could cause a store-load forwarding conflict\n");
2061 return true;
2062 }
2063 }
2064 return false;
2065}
2066
2067void MemoryDepChecker::mergeInStatus(VectorizationSafetyStatus S) {
2068 if (Status < S)
2069 Status = S;
2070}
2071
2072/// Given a dependence-distance \p Dist between two memory accesses, that have
2073/// strides in the same direction whose absolute value of the maximum stride is
2074/// given in \p MaxStride, in a loop whose maximum backedge taken count is \p
2075/// MaxBTC, check if it is possible to prove statically that the dependence
2076/// distance is larger than the range that the accesses will travel through the
2077/// execution of the loop. If so, return true; false otherwise. This is useful
2078/// for example in loops such as the following (PR31098):
2079///
2080/// for (i = 0; i < D; ++i) {
2081/// = out[i];
2082/// out[i+D] =
2083/// }
2085 const SCEV &MaxBTC, const SCEV &Dist,
2086 uint64_t MaxStride) {
2087
2088 // If we can prove that
2089 // (**) |Dist| > MaxBTC * Step
2090 // where Step is the absolute stride of the memory accesses in bytes,
2091 // then there is no dependence.
2092 //
2093 // Rationale:
2094 // We basically want to check if the absolute distance (|Dist/Step|)
2095 // is >= the loop iteration count (or > MaxBTC).
2096 // This is equivalent to the Strong SIV Test (Practical Dependence Testing,
2097 // Section 4.2.1); Note, that for vectorization it is sufficient to prove
2098 // that the dependence distance is >= VF; This is checked elsewhere.
2099 // But in some cases we can prune dependence distances early, and
2100 // even before selecting the VF, and without a runtime test, by comparing
2101 // the distance against the loop iteration count. Since the vectorized code
2102 // will be executed only if LoopCount >= VF, proving distance >= LoopCount
2103 // also guarantees that distance >= VF.
2104 //
2105 const SCEV *Step = SE.getConstant(MaxBTC.getType(), MaxStride);
2106 const SCEV *Product = SE.getMulExpr(&MaxBTC, Step);
2107
2108 const SCEV *CastedDist = &Dist;
2109 const SCEV *CastedProduct = Product;
2110 uint64_t DistTypeSizeBits = DL.getTypeSizeInBits(Dist.getType());
2111 uint64_t ProductTypeSizeBits = DL.getTypeSizeInBits(Product->getType());
2112
2113 // The dependence distance can be positive/negative, so we sign extend Dist;
2114 // The multiplication of the absolute stride in bytes and the
2115 // backedgeTakenCount is non-negative, so we zero extend Product.
2116 if (DistTypeSizeBits > ProductTypeSizeBits)
2117 CastedProduct = SE.getZeroExtendExpr(Product, Dist.getType());
2118 else
2119 CastedDist = SE.getNoopOrSignExtend(&Dist, Product->getType());
2120
2121 // Is Dist - (MaxBTC * Step) > 0 ?
2122 // (If so, then we have proven (**) because |Dist| >= Dist)
2123 const SCEV *Minus = SE.getMinusSCEV(CastedDist, CastedProduct);
2124 if (SE.isKnownPositive(Minus))
2125 return true;
2126
2127 // Second try: Is -Dist - (MaxBTC * Step) > 0 ?
2128 // (If so, then we have proven (**) because |Dist| >= -1*Dist)
2129 const SCEV *NegDist = SE.getNegativeSCEV(CastedDist);
2130 Minus = SE.getMinusSCEV(NegDist, CastedProduct);
2131 return SE.isKnownPositive(Minus);
2132}
2133
2134/// Check the dependence for two accesses with the same stride \p Stride.
2135/// \p Distance is the positive distance in bytes, and \p TypeByteSize is type
2136/// size in bytes.
2137///
2138/// \returns true if they are independent.
2140 uint64_t TypeByteSize) {
2141 assert(Stride > 1 && "The stride must be greater than 1");
2142 assert(TypeByteSize > 0 && "The type size in byte must be non-zero");
2143 assert(Distance > 0 && "The distance must be non-zero");
2144
2145 // Skip if the distance is not multiple of type byte size.
2146 if (Distance % TypeByteSize)
2147 return false;
2148
2149 // No dependence if the distance is not multiple of the stride.
2150 // E.g.
2151 // for (i = 0; i < 1024 ; i += 4)
2152 // A[i+2] = A[i] + 1;
2153 //
2154 // Two accesses in memory (distance is 2, stride is 4):
2155 // | A[0] | | | | A[4] | | | |
2156 // | | | A[2] | | | | A[6] | |
2157 //
2158 // E.g.
2159 // for (i = 0; i < 1024 ; i += 3)
2160 // A[i+4] = A[i] + 1;
2161 //
2162 // Two accesses in memory (distance is 4, stride is 3):
2163 // | A[0] | | | A[3] | | | A[6] | | |
2164 // | | | | | A[4] | | | A[7] | |
2165 return Distance % Stride;
2166}
2167
2168bool MemoryDepChecker::areAccessesCompletelyBeforeOrAfter(const SCEV *Src,
2169 Type *SrcTy,
2170 const SCEV *Sink,
2171 Type *SinkTy) {
2172 const SCEV *BTC = PSE.getBackedgeTakenCount();
2173 const SCEV *SymbolicMaxBTC = PSE.getSymbolicMaxBackedgeTakenCount();
2174 ScalarEvolution &SE = *PSE.getSE();
2175 const auto &[SrcStart_, SrcEnd_] =
2176 getStartAndEndForAccess(InnermostLoop, Src, SrcTy, BTC, SymbolicMaxBTC,
2177 &SE, &PointerBounds, DT, AC, LoopGuards);
2178 if (isa<SCEVCouldNotCompute>(SrcStart_) || isa<SCEVCouldNotCompute>(SrcEnd_))
2179 return false;
2180
2181 const auto &[SinkStart_, SinkEnd_] =
2182 getStartAndEndForAccess(InnermostLoop, Sink, SinkTy, BTC, SymbolicMaxBTC,
2183 &SE, &PointerBounds, DT, AC, LoopGuards);
2184 if (isa<SCEVCouldNotCompute>(SinkStart_) ||
2185 isa<SCEVCouldNotCompute>(SinkEnd_))
2186 return false;
2187
2188 if (!LoopGuards)
2189 LoopGuards.emplace(ScalarEvolution::LoopGuards::collect(InnermostLoop, SE));
2190
2191 auto SrcEnd = SE.applyLoopGuards(SrcEnd_, *LoopGuards);
2192 auto SinkStart = SE.applyLoopGuards(SinkStart_, *LoopGuards);
2193 if (SE.isKnownPredicate(CmpInst::ICMP_ULE, SrcEnd, SinkStart))
2194 return true;
2195
2196 auto SinkEnd = SE.applyLoopGuards(SinkEnd_, *LoopGuards);
2197 auto SrcStart = SE.applyLoopGuards(SrcStart_, *LoopGuards);
2198 return SE.isKnownPredicate(CmpInst::ICMP_ULE, SinkEnd, SrcStart);
2199}
2200
2202 MemoryDepChecker::DepDistanceStrideAndSizeInfo>
2203MemoryDepChecker::getDependenceDistanceStrideAndSize(
2204 const AccessAnalysis::MemAccessInfo &A, Instruction *AInst,
2205 const AccessAnalysis::MemAccessInfo &B, Instruction *BInst) {
2206 const auto &DL = InnermostLoop->getHeader()->getDataLayout();
2207 auto &SE = *PSE.getSE();
2208 const auto &[APtr, AIsWrite] = A;
2209 const auto &[BPtr, BIsWrite] = B;
2210
2211 // Two reads are independent.
2212 if (!AIsWrite && !BIsWrite)
2214
2215 Type *ATy = getLoadStoreType(AInst);
2216 Type *BTy = getLoadStoreType(BInst);
2217
2218 // We cannot check pointers in different address spaces.
2219 if (APtr->getType()->getPointerAddressSpace() !=
2220 BPtr->getType()->getPointerAddressSpace())
2222
2224 std::optional<int64_t> StrideAPtr =
2225 getPtrStride(PSE, ATy, APtr, InnermostLoop, *DT, SymbolicStrides,
2226 /*ShouldCheckWrap=*/true, &Predicates);
2227 std::optional<int64_t> StrideBPtr =
2228 getPtrStride(PSE, BTy, BPtr, InnermostLoop, *DT, SymbolicStrides,
2229 /*ShouldCheckWrap=*/true, &Predicates);
2230 PSE.addPredicates(Predicates);
2231
2232 const SCEV *Src = PSE.getSCEV(APtr);
2233 const SCEV *Sink = PSE.getSCEV(BPtr);
2234
2235 // If the induction step is negative we have to invert source and sink of the
2236 // dependence when measuring the distance between them. We should not swap
2237 // AIsWrite with BIsWrite, as their uses expect them in program order.
2238 if (StrideAPtr && *StrideAPtr < 0) {
2239 std::swap(Src, Sink);
2240 std::swap(AInst, BInst);
2241 std::swap(ATy, BTy);
2242 std::swap(StrideAPtr, StrideBPtr);
2243 }
2244
2245 const SCEV *Dist = SE.getMinusSCEV(Sink, Src);
2246
2247 LLVM_DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
2248 << "\n");
2249 LLVM_DEBUG(dbgs() << "LAA: Distance for " << *AInst << " to " << *BInst
2250 << ": " << *Dist << "\n");
2251
2252 // Need accesses with constant strides and the same direction for further
2253 // dependence analysis. We don't want to vectorize "A[B[i]] += ..." and
2254 // similar code or pointer arithmetic that could wrap in the address space.
2255
2256 // If either Src or Sink are not strided (i.e. not a non-wrapping AddRec) and
2257 // not loop-invariant (stride will be 0 in that case), we cannot analyze the
2258 // dependence further and also cannot generate runtime checks.
2259 if (!StrideAPtr || !StrideBPtr) {
2260 LLVM_DEBUG(dbgs() << "Pointer access with non-constant stride\n");
2262 }
2263
2264 int64_t StrideAPtrInt = *StrideAPtr;
2265 int64_t StrideBPtrInt = *StrideBPtr;
2266 LLVM_DEBUG(dbgs() << "LAA: Src induction step: " << StrideAPtrInt
2267 << " Sink induction step: " << StrideBPtrInt << "\n");
2268 // At least Src or Sink are loop invariant and the other is strided or
2269 // invariant.
2270 if (!StrideAPtrInt || !StrideBPtrInt) {
2271 // If both are loop-invariant and access the same location, we cannot
2272 // vectorize.
2273 if (!StrideAPtrInt && !StrideBPtrInt && Dist->isZero())
2275 // Otherwise, we can generate a runtime check to disambiguate the accesses.
2277 }
2278
2279 // Both Src and Sink have a constant stride, check if they are in the same
2280 // direction.
2281 if ((StrideAPtrInt > 0) != (StrideBPtrInt > 0)) {
2282 LLVM_DEBUG(
2283 dbgs() << "Pointer access with strides in different directions\n");
2285 }
2286
2287 TypeSize AStoreSz = DL.getTypeStoreSize(ATy);
2288 TypeSize BStoreSz = DL.getTypeStoreSize(BTy);
2289
2290 // If store sizes are not the same, set TypeByteSize to zero, so we can check
2291 // it in the caller isDependent.
2292 uint64_t ASz = DL.getTypeAllocSize(ATy);
2293 uint64_t BSz = DL.getTypeAllocSize(BTy);
2294 uint64_t TypeByteSize = (AStoreSz == BStoreSz) ? BSz : 0;
2295
2296 uint64_t StrideAScaled = AbsoluteValue(StrideAPtrInt) * ASz;
2297 uint64_t StrideBScaled = AbsoluteValue(StrideBPtrInt) * BSz;
2298
2299 uint64_t MaxStride = std::max(StrideAScaled, StrideBScaled);
2300
2301 std::optional<uint64_t> CommonStride;
2302 if (StrideAScaled == StrideBScaled)
2303 CommonStride = StrideAScaled;
2304
2305 // TODO: Historically, we didn't retry with runtime checks when (unscaled)
2306 // strides were different but there is no inherent reason to.
2307 if (!isa<SCEVConstant>(Dist))
2308 ShouldRetryWithRuntimeChecks |= StrideAPtrInt == StrideBPtrInt;
2309
2310 // If distance is a SCEVCouldNotCompute, return Unknown immediately.
2311 if (isa<SCEVCouldNotCompute>(Dist)) {
2312 LLVM_DEBUG(dbgs() << "LAA: Uncomputable distance.\n");
2313 return Dependence::Unknown;
2314 }
2315
2316 return DepDistanceStrideAndSizeInfo(Dist, MaxStride, CommonStride,
2317 TypeByteSize, AIsWrite, BIsWrite);
2318}
2319
2321MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
2322 const MemAccessInfo &B, unsigned BIdx) {
2323 assert(AIdx < BIdx && "Must pass arguments in program order");
2324
2325 // Check if we can prove that Sink only accesses memory after Src's end or
2326 // vice versa. The helper is used to perform the checks only on the exit paths
2327 // where it helps to improve the analysis result.
2328 auto CheckCompletelyBeforeOrAfter = [&]() {
2329 auto *APtr = A.getPointer();
2330 auto *BPtr = B.getPointer();
2331 Type *ATy = getLoadStoreType(InstMap[AIdx]);
2332 Type *BTy = getLoadStoreType(InstMap[BIdx]);
2333 const SCEV *Src = PSE.getSCEV(APtr);
2334 const SCEV *Sink = PSE.getSCEV(BPtr);
2335 return areAccessesCompletelyBeforeOrAfter(Src, ATy, Sink, BTy);
2336 };
2337
2338 // Get the dependence distance, stride, type size and what access writes for
2339 // the dependence between A and B.
2340 auto Res =
2341 getDependenceDistanceStrideAndSize(A, InstMap[AIdx], B, InstMap[BIdx]);
2342 if (std::holds_alternative<Dependence::DepType>(Res)) {
2343 if (std::get<Dependence::DepType>(Res) == Dependence::Unknown &&
2344 CheckCompletelyBeforeOrAfter())
2345 return Dependence::NoDep;
2346 return std::get<Dependence::DepType>(Res);
2347 }
2348
2349 auto &[Dist, MaxStride, CommonStride, TypeByteSize, AIsWrite, BIsWrite] =
2350 std::get<DepDistanceStrideAndSizeInfo>(Res);
2351 bool HasSameSize = TypeByteSize > 0;
2352
2353 ScalarEvolution &SE = *PSE.getSE();
2354 auto &DL = InnermostLoop->getHeader()->getDataLayout();
2355
2356 // If the distance between the acecsses is larger than their maximum absolute
2357 // stride multiplied by the symbolic maximum backedge taken count (which is an
2358 // upper bound of the number of iterations), the accesses are independet, i.e.
2359 // they are far enough appart that accesses won't access the same location
2360 // across all loop ierations.
2361 if (HasSameSize &&
2363 DL, SE, *(PSE.getSymbolicMaxBackedgeTakenCount()), *Dist, MaxStride))
2364 return Dependence::NoDep;
2365
2366 const APInt *APDist = nullptr;
2367 uint64_t ConstDist = 0;
2368 if (match(Dist, m_scev_APInt(APDist))) {
2369 std::optional<uint64_t> Val = APDist->abs().tryZExtValue();
2370 if (!Val) {
2371 LLVM_DEBUG(dbgs() << "LAA: Constant distance does not fit in 64 bits.\n");
2372 return Dependence::Unknown;
2373 }
2374 ConstDist = *Val;
2375 }
2376
2377 // Attempt to prove strided accesses independent.
2378 if (APDist) {
2379 // If the distance between accesses and their strides are known constants,
2380 // check whether the accesses interlace each other.
2381 if (ConstDist > 0 && CommonStride && CommonStride > 1 && HasSameSize &&
2382 areStridedAccessesIndependent(ConstDist, *CommonStride, TypeByteSize)) {
2383 LLVM_DEBUG(dbgs() << "LAA: Strided accesses are independent\n");
2384 return Dependence::NoDep;
2385 }
2386 } else {
2387 if (!LoopGuards)
2388 LoopGuards.emplace(
2389 ScalarEvolution::LoopGuards::collect(InnermostLoop, SE));
2390 Dist = SE.applyLoopGuards(Dist, *LoopGuards);
2391 }
2392
2393 // Negative distances are not plausible dependencies.
2394 if (SE.isKnownNonPositive(Dist)) {
2395 if (SE.isKnownNonNegative(Dist)) {
2396 if (HasSameSize) {
2397 // Write to the same location with the same size.
2398 return Dependence::Forward;
2399 }
2400 LLVM_DEBUG(dbgs() << "LAA: possibly zero dependence difference but "
2401 "different type sizes\n");
2402 return Dependence::Unknown;
2403 }
2404
2405 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
2406 // Check if the first access writes to a location that is read in a later
2407 // iteration, where the distance between them is not a multiple of a vector
2408 // factor and relatively small.
2409 //
2410 // NOTE: There is no need to update MaxSafeVectorWidthInBits after call to
2411 // couldPreventStoreLoadForward, even if it changed MinDepDistBytes, since a
2412 // forward dependency will allow vectorization using any width.
2413
2414 if (IsTrueDataDependence && EnableForwardingConflictDetection) {
2415 if (!ConstDist) {
2416 return CheckCompletelyBeforeOrAfter() ? Dependence::NoDep
2418 }
2419 if (!HasSameSize ||
2420 couldPreventStoreLoadForward(ConstDist, TypeByteSize)) {
2421 LLVM_DEBUG(
2422 dbgs() << "LAA: Forward but may prevent st->ld forwarding\n");
2424 }
2425 }
2426
2427 LLVM_DEBUG(dbgs() << "LAA: Dependence is negative\n");
2428 return Dependence::Forward;
2429 }
2430
2431 std::optional<int64_t> MinDistanceOpt =
2433 if (!MinDistanceOpt) {
2434 LLVM_DEBUG(dbgs() << "LAA: Minimum distance does not fit in 64 bits.\n");
2435 return Dependence::Unknown;
2436 }
2437 int64_t MinDistance = *MinDistanceOpt;
2438 // Below we only handle strictly positive distances.
2439 if (MinDistance <= 0) {
2440 return CheckCompletelyBeforeOrAfter() ? Dependence::NoDep
2442 }
2443
2444 if (!HasSameSize) {
2445 if (CheckCompletelyBeforeOrAfter())
2446 return Dependence::NoDep;
2447 LLVM_DEBUG(dbgs() << "LAA: ReadWrite-Write positive dependency with "
2448 "different type sizes\n");
2449 return Dependence::Unknown;
2450 }
2451 // Bail out early if passed-in parameters make vectorization not feasible.
2452 unsigned MinForcedFactor =
2453 std::max(1U, VectorizerParams::VectorizationFactor.getKnownMinValue());
2454 unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
2456 // The minimum number of iterations for a vectorized/unrolled version.
2457 unsigned MinNumIter = std::max(MinForcedFactor * ForcedUnroll, 2U);
2458
2459 // It's not vectorizable if the distance is smaller than the minimum distance
2460 // needed for a vectroized/unrolled version. Vectorizing one iteration in
2461 // front needs MaxStride. Vectorizing the last iteration needs TypeByteSize.
2462 // (No need to plus the last gap distance).
2463 //
2464 // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
2465 // foo(int *A) {
2466 // int *B = (int *)((char *)A + 14);
2467 // for (i = 0 ; i < 1024 ; i += 2)
2468 // B[i] = A[i] + 1;
2469 // }
2470 //
2471 // Two accesses in memory (stride is 4 * 2):
2472 // | A[0] | | A[2] | | A[4] | | A[6] | |
2473 // | B[0] | | B[2] | | B[4] |
2474 //
2475 // MinDistance needs for vectorizing iterations except the last iteration:
2476 // 4 * 2 * (MinNumIter - 1). MinDistance needs for the last iteration: 4.
2477 // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4.
2478 //
2479 // If MinNumIter is 2, it is vectorizable as the minimum distance needed is
2480 // 12, which is less than distance.
2481 //
2482 // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4),
2483 // the minimum distance needed is 28, which is greater than distance. It is
2484 // not safe to do vectorization.
2485 //
2486 // We use MaxStride (maximum of src and sink strides) to get a conservative
2487 // lower bound on the MinDistanceNeeded in case of different strides.
2488
2489 // We know that Dist is positive, but it may not be constant. Use the signed
2490 // minimum for computations below, as this ensures we compute the closest
2491 // possible dependence distance.
2492 uint64_t MinDistanceNeeded = MaxStride * (MinNumIter - 1) + TypeByteSize;
2493 if (MinDistanceNeeded > static_cast<uint64_t>(MinDistance)) {
2494 if (!ConstDist) {
2495 // For non-constant distances, we checked the lower bound of the
2496 // dependence distance and the distance may be larger at runtime (and safe
2497 // for vectorization). Classify it as Unknown, so we re-try with runtime
2498 // checks, unless we can prove both accesses cannot overlap.
2499 return CheckCompletelyBeforeOrAfter() ? Dependence::NoDep
2501 }
2502 LLVM_DEBUG(dbgs() << "LAA: Failure because of positive minimum distance "
2503 << MinDistance << '\n');
2504 return Dependence::Backward;
2505 }
2506
2507 // Unsafe if the minimum distance needed is greater than smallest dependence
2508 // distance distance.
2509 if (MinDistanceNeeded > MinDepDistBytes) {
2510 LLVM_DEBUG(dbgs() << "LAA: Failure because it needs at least "
2511 << MinDistanceNeeded << " size in bytes\n");
2512 return Dependence::Backward;
2513 }
2514
2515 MinDepDistBytes =
2516 std::min(static_cast<uint64_t>(MinDistance), MinDepDistBytes);
2517
2518 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
2519 if (IsTrueDataDependence && EnableForwardingConflictDetection && ConstDist &&
2520 couldPreventStoreLoadForward(MinDistance, TypeByteSize, *CommonStride))
2522
2523 uint64_t MaxVF = MinDepDistBytes / MaxStride;
2524 LLVM_DEBUG(dbgs() << "LAA: Positive min distance " << MinDistance
2525 << " with max VF = " << MaxVF << '\n');
2526
2527 uint64_t MaxVFInBits = MaxVF * TypeByteSize * 8;
2528 if (!ConstDist && MaxVFInBits < MaxTargetVectorWidthInBits) {
2529 // For non-constant distances, we checked the lower bound of the dependence
2530 // distance and the distance may be larger at runtime (and safe for
2531 // vectorization). Classify it as Unknown, so we re-try with runtime checks,
2532 // unless we can prove both accesses cannot overlap.
2533 return CheckCompletelyBeforeOrAfter() ? Dependence::NoDep
2535 }
2536
2537 if (CheckCompletelyBeforeOrAfter())
2538 return Dependence::NoDep;
2539
2540 MaxSafeVectorWidthInBits = std::min(MaxSafeVectorWidthInBits, MaxVFInBits);
2542}
2543
2545 ArrayRef<MemAccessInfo> CheckDeps) {
2546
2547 MinDepDistBytes = -1;
2549 for (MemAccessInfo CurAccess : CheckDeps) {
2550 if (Visited.contains(CurAccess))
2551 continue;
2552
2553 // Check accesses within this set.
2555 DepCands.findLeader(CurAccess);
2557 DepCands.member_end();
2558
2559 // Check every access pair.
2560 while (AI != AE) {
2561 Visited.insert(*AI);
2562 bool AIIsWrite = AI->getInt();
2563 // Reads from the same pointer don't create extra hazards, but multiple
2564 // stores do (WAW), so start from AI for writes and next(AI) for reads.
2566 (AIIsWrite ? AI : std::next(AI));
2567 while (OI != AE) {
2568 // Check every accessing instruction pair in program order.
2569 auto &Acc = Accesses[*AI];
2570 for (std::vector<unsigned>::iterator I1 = Acc.begin(), I1E = Acc.end();
2571 I1 != I1E; ++I1)
2572 // When checking for WAW (OI == AI) caused by multiple writes to the
2573 // same pointer, start I2 at the next access past I1 to avoid
2574 // self-comparison.
2575 for (std::vector<unsigned>::iterator
2576 I2 = (OI == AI ? std::next(I1) : Accesses[*OI].begin()),
2577 I2E = (OI == AI ? I1E : Accesses[*OI].end());
2578 I2 != I2E; ++I2) {
2579 auto A = std::make_pair(&*AI, *I1);
2580 auto B = std::make_pair(&*OI, *I2);
2581
2582 assert(*I1 != *I2);
2583 if (*I1 > *I2)
2584 std::swap(A, B);
2585
2587 isDependent(*A.first, A.second, *B.first, B.second);
2589
2590 // Gather dependences unless we accumulated MaxDependences
2591 // dependences. In that case return as soon as we find the first
2592 // unsafe dependence. This puts a limit on this quadratic
2593 // algorithm.
2594 if (RecordDependences) {
2595 if (Type != Dependence::NoDep)
2596 Dependences.emplace_back(A.second, B.second, Type);
2597
2598 if (Dependences.size() >= MaxDependences) {
2599 RecordDependences = false;
2600 Dependences.clear();
2602 << "Too many dependences, stopped recording\n");
2603 }
2604 }
2605 if (!RecordDependences && !isSafeForVectorization())
2606 return false;
2607 }
2608 ++OI;
2609 }
2610 ++AI;
2611 }
2612 }
2613
2614 LLVM_DEBUG(dbgs() << "Total Dependences: " << Dependences.size() << "\n");
2615 return isSafeForVectorization();
2616}
2617
2620 MemAccessInfo Access(Ptr, IsWrite);
2621 auto I = Accesses.find(Access);
2623 if (I != Accesses.end()) {
2624 transform(I->second, std::back_inserter(Insts),
2625 [&](unsigned Idx) { return this->InstMap[Idx]; });
2626 }
2627
2628 return Insts;
2629}
2630
2632 "NoDep",
2633 "Unknown",
2634 "IndirectUnsafe",
2635 "InvariantUnsafe",
2636 "Forward",
2637 "ForwardButPreventsForwarding",
2638 "Backward",
2639 "BackwardVectorizable",
2640 "BackwardVectorizableButPreventsForwarding"};
2641
2643 raw_ostream &OS, unsigned Depth,
2644 const SmallVectorImpl<Instruction *> &Instrs) const {
2645 OS.indent(Depth) << DepName[Type] << ":\n";
2646 OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
2647 OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
2648}
2649
2650bool LoopAccessInfo::canAnalyzeLoop() {
2651 // We need to have a loop header.
2652 LLVM_DEBUG(dbgs() << "\nLAA: Checking a loop in '"
2653 << TheLoop->getHeader()->getParent()->getName() << "' from "
2654 << TheLoop->getLocStr() << "\n");
2655
2656 // We can only analyze innermost loops.
2657 if (!TheLoop->isInnermost()) {
2658 LLVM_DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
2659 recordAnalysis("NotInnerMostLoop") << "loop is not the innermost loop";
2660 return false;
2661 }
2662
2663 // We must have a single backedge.
2664 if (TheLoop->getNumBackEdges() != 1) {
2665 LLVM_DEBUG(
2666 dbgs() << "LAA: loop control flow is not understood by analyzer\n");
2667 recordAnalysis("CFGNotUnderstood")
2668 << "loop control flow is not understood by analyzer";
2669 return false;
2670 }
2671
2672 // ScalarEvolution needs to be able to find the symbolic max backedge taken
2673 // count, which is an upper bound on the number of loop iterations. The loop
2674 // may execute fewer iterations, if it exits via an uncountable exit.
2675 const SCEV *ExitCount = PSE->getSymbolicMaxBackedgeTakenCount();
2676 if (isa<SCEVCouldNotCompute>(ExitCount)) {
2677 recordAnalysis("CantComputeNumberOfIterations")
2678 << "could not determine number of loop iterations";
2679 LLVM_DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
2680 return false;
2681 }
2682
2683 LLVM_DEBUG(dbgs() << "LAA: Found an analyzable loop: "
2684 << TheLoop->getHeader()->getName() << "\n");
2685 return true;
2686}
2687
2688bool LoopAccessInfo::analyzeLoop(AAResults *AA, const LoopInfo *LI,
2689 const TargetLibraryInfo *TLI,
2690 DominatorTree *DT) {
2691 // Holds the Load and Store instructions.
2694 SmallPtrSet<MDNode *, 8> LoopAliasScopes;
2695
2696 // Holds all the different accesses in the loop.
2697 unsigned NumReads = 0;
2698 unsigned NumReadWrites = 0;
2699
2700 bool HasComplexMemInst = false;
2701
2702 // A runtime check is only legal to insert if there are no convergent calls.
2703 HasConvergentOp = false;
2704
2705 PtrRtChecking->Pointers.clear();
2706 PtrRtChecking->Need = false;
2707
2708 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
2709
2710 const bool EnableMemAccessVersioningOfLoop =
2712 !TheLoop->getHeader()->getParent()->hasOptSize();
2713
2714 // Traverse blocks in fixed RPOT order, regardless of their storage in the
2715 // loop info, as it may be arbitrary.
2716 LoopBlocksRPO RPOT(TheLoop);
2717 RPOT.perform(LI);
2718
2719 // Don't return early as soon as we found a memory access that cannot be
2720 // vectorize - HasConvergentOp must still be computed as it is part of LAI's
2721 // public API (used by LoopDistribute).
2722 for (BasicBlock *BB : RPOT) {
2723 // Scan the BB and collect legal loads and stores. Also detect any
2724 // convergent instructions.
2725 for (Instruction &I : *BB) {
2726 if (auto *Call = dyn_cast<CallBase>(&I)) {
2727 if (Call->isConvergent())
2728 HasConvergentOp = true;
2729 }
2730
2731 // Unsafe to vectorize and we already found a convergent operation, can
2732 // early return now.
2733 if (HasComplexMemInst && HasConvergentOp)
2734 return false;
2735
2736 // Already unsafe to vectorize; keep scanning for convergent ops.
2737 if (HasComplexMemInst)
2738 continue;
2739
2740 // Record alias scopes defined inside the loop.
2741 if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
2742 for (Metadata *Op : Decl->getScopeList()->operands())
2743 LoopAliasScopes.insert(cast<MDNode>(Op));
2744
2745 // Many math library functions read the rounding mode. We will only
2746 // vectorize a loop if it contains known function calls that don't set
2747 // the flag. Therefore, it is safe to ignore this read from memory.
2748 auto *Call = dyn_cast<CallInst>(&I);
2750 continue;
2751
2752 // If this is a load, save it. If this instruction can read from memory
2753 // but is not a load, we only allow it if it's a call to a function with a
2754 // vector mapping and no pointer arguments.
2755 if (I.mayReadFromMemory()) {
2756 auto hasPointerArgs = [](CallBase *CB) {
2757 return any_of(CB->args(), [](Value const *Arg) {
2758 return Arg->getType()->isPointerTy();
2759 });
2760 };
2761
2762 // If the function has an explicit vectorized counterpart, and does not
2763 // take output/input pointers, we can safely assume that it can be
2764 // vectorized.
2765 if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
2766 !hasPointerArgs(Call) && !VFDatabase::getMappings(*Call).empty())
2767 continue;
2768
2769 auto *Ld = dyn_cast<LoadInst>(&I);
2770 if (!Ld) {
2771 recordAnalysis("CantVectorizeInstruction", &I)
2772 << "instruction cannot be vectorized";
2773 HasComplexMemInst = true;
2774 continue;
2775 }
2776 if (!Ld->isSimple() && !IsAnnotatedParallel) {
2777 recordAnalysis("NonSimpleLoad", Ld)
2778 << "read with atomic ordering or volatile read";
2779 LLVM_DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
2780 HasComplexMemInst = true;
2781 continue;
2782 }
2783 NumLoads++;
2784 Loads.push_back(Ld);
2785 DepChecker->addAccess(Ld);
2786 if (EnableMemAccessVersioningOfLoop)
2787 collectStridedAccess(Ld);
2788 continue;
2789 }
2790
2791 // Save 'store' instructions. Abort if other instructions write to memory.
2792 if (I.mayWriteToMemory()) {
2793 auto *St = dyn_cast<StoreInst>(&I);
2794 if (!St) {
2795 recordAnalysis("CantVectorizeInstruction", &I)
2796 << "instruction cannot be vectorized";
2797 HasComplexMemInst = true;
2798 continue;
2799 }
2800 if (!St->isSimple() && !IsAnnotatedParallel) {
2801 recordAnalysis("NonSimpleStore", St)
2802 << "write with atomic ordering or volatile write";
2803 LLVM_DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
2804 HasComplexMemInst = true;
2805 continue;
2806 }
2807 NumStores++;
2808 Stores.push_back(St);
2809 DepChecker->addAccess(St);
2810 if (EnableMemAccessVersioningOfLoop)
2811 collectStridedAccess(St);
2812 }
2813 } // Next instr.
2814 } // Next block.
2815
2816 if (HasComplexMemInst)
2817 return false;
2818
2819 // Now we have two lists that hold the loads and the stores.
2820 // Next, we find the pointers that they use.
2821
2822 // Check if we see any stores. If there are no stores, then we don't
2823 // care if the pointers are *restrict*.
2824 if (!Stores.size()) {
2825 LLVM_DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
2826 return true;
2827 }
2828
2830 AccessAnalysis Accesses(TheLoop, AA, LI, *DT, DepCands, *PSE,
2831 LoopAliasScopes);
2832
2833 // Holds the analyzed pointers. We don't want to call getUnderlyingObjects
2834 // multiple times on the same object. If the ptr is accessed twice, once
2835 // for read and once for write, it will only appear once (on the write
2836 // list). This is okay, since we are going to check for conflicts between
2837 // writes and between reads and writes, but not between reads and reads.
2838 SmallSet<std::pair<Value *, Type *>, 16> Seen;
2839
2840 // Record uniform store addresses to identify if we have multiple stores
2841 // to the same address.
2842 SmallPtrSet<Value *, 16> UniformStores;
2843
2844 for (StoreInst *ST : Stores) {
2845 Value *Ptr = ST->getPointerOperand();
2846
2847 if (isInvariant(Ptr)) {
2848 // Record store instructions to loop invariant addresses
2849 StoresToInvariantAddresses.push_back(ST);
2850 HasStoreStoreDependenceInvolvingLoopInvariantAddress |=
2851 !UniformStores.insert(Ptr).second;
2852 }
2853
2854 // If we did *not* see this pointer before, insert it to the read-write
2855 // list. At this phase it is only a 'write' list.
2856 Type *AccessTy = getLoadStoreType(ST);
2857 if (Seen.insert({Ptr, AccessTy}).second) {
2858 ++NumReadWrites;
2859
2860 MemoryLocation Loc = MemoryLocation::get(ST);
2861 // The TBAA metadata could have a control dependency on the predication
2862 // condition, so we cannot rely on it when determining whether or not we
2863 // need runtime pointer checks.
2864 if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
2865 Loc.AATags.TBAA = nullptr;
2866
2867 // Expand forked pointers (i.e., a phi of multiple strided pointers) into
2868 // all alternatives.
2869 visitPointers(const_cast<Value *>(Loc.Ptr), *TheLoop,
2870 [&Accesses, AccessTy, Loc](Value *Ptr) {
2871 MemoryLocation NewLoc = Loc.getWithNewPtr(Ptr);
2872 Accesses.addStore(NewLoc, AccessTy);
2873 });
2874 }
2875 }
2876
2877 if (IsAnnotatedParallel) {
2878 LLVM_DEBUG(
2879 dbgs() << "LAA: A loop annotated parallel, ignore memory dependency "
2880 << "checks.\n");
2881 return true;
2882 }
2883
2884 for (LoadInst *LD : Loads) {
2885 Value *Ptr = LD->getPointerOperand();
2886 // If we did *not* see this pointer before, insert it to the read list. If
2887 // we *did* see it before, then it is already in the read-write list. This
2888 // allows us to vectorize expressions such as A[i] += x; Because the address
2889 // of A[i] is a read-write pointer. This only works if the index of A[i] is
2890 // strictly monotonic, which we approximate (conservatively) via
2891 // getPtrStride. If the address is unknown (e.g. A[B[i]]) then we may read,
2892 // modify, and write overlapping words. Note that "zero stride" is unsafe
2893 // and is being handled below.
2894 bool IsReadOnlyPtr = false;
2895 Type *AccessTy = getLoadStoreType(LD);
2896 if (Seen.insert({Ptr, AccessTy}).second ||
2897 !getPtrStride(*PSE, AccessTy, Ptr, TheLoop, *DT, SymbolicStrides, false,
2898 true)) {
2899 ++NumReads;
2900 IsReadOnlyPtr = true;
2901 }
2902
2903 // See if there is an unsafe dependency between a load to a uniform address and
2904 // store to the same uniform address.
2905 if (UniformStores.contains(Ptr)) {
2906 LLVM_DEBUG(dbgs() << "LAA: Found an unsafe dependency between a uniform "
2907 "load and uniform store to the same address!\n");
2908 HasLoadStoreDependenceInvolvingLoopInvariantAddress = true;
2909 }
2910
2911 MemoryLocation Loc = MemoryLocation::get(LD);
2912 // The TBAA metadata could have a control dependency on the predication
2913 // condition, so we cannot rely on it when determining whether or not we
2914 // need runtime pointer checks.
2915 if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
2916 Loc.AATags.TBAA = nullptr;
2917
2918 // Expand forked pointers (i.e., a phi of multiple strided pointers) into
2919 // all alternatives.
2920 visitPointers(const_cast<Value *>(Loc.Ptr), *TheLoop,
2921 [&Accesses, AccessTy, Loc, IsReadOnlyPtr](Value *Ptr) {
2922 MemoryLocation NewLoc = Loc.getWithNewPtr(Ptr);
2923 Accesses.addLoad(NewLoc, AccessTy, IsReadOnlyPtr);
2924 });
2925 }
2926
2927 // If we write (or read-write) to a single destination and there are no other
2928 // reads in this loop then is it safe to vectorize: the vectorized stores
2929 // preserve ordering via replication or order-preserving @llvm.masked.scatter.
2930 if (NumReadWrites == 1 && NumReads == 0) {
2931 LLVM_DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
2932 return true;
2933 }
2934
2935 // Build dependence sets and check whether we need a runtime pointer bounds
2936 // check.
2937 Accesses.buildDependenceSets();
2938
2939 // Find pointers with computable bounds. We are going to use this information
2940 // to place a runtime bound check.
2941 Value *UncomputablePtr = nullptr;
2942 HasCompletePtrRtChecking =
2943 Accesses.canCheckPtrAtRT(*PtrRtChecking, TheLoop, SymbolicStrides,
2944 UncomputablePtr, AllowPartial, getDepChecker());
2945 if (!HasCompletePtrRtChecking) {
2946 const auto *I = dyn_cast_or_null<Instruction>(UncomputablePtr);
2947 recordAnalysis("CantIdentifyArrayBounds", I)
2948 << "cannot identify array bounds";
2949 LLVM_DEBUG(dbgs() << "LAA: We can't vectorize because we can't find "
2950 << "the array bounds.\n");
2951 return false;
2952 }
2953
2954 LLVM_DEBUG(
2955 dbgs() << "LAA: May be able to perform a memory runtime check if needed.\n");
2956
2957 bool DepsAreSafe = true;
2958 if (Accesses.isDependencyCheckNeeded()) {
2959 LLVM_DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
2960 DepsAreSafe =
2961 DepChecker->areDepsSafe(DepCands, Accesses.getDependenciesToCheck());
2962
2963 if (!DepsAreSafe && DepChecker->shouldRetryWithRuntimeChecks()) {
2964 LLVM_DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
2965
2966 PtrRtChecking->reset();
2967 PtrRtChecking->Need = true;
2968
2969 UncomputablePtr = nullptr;
2970 HasCompletePtrRtChecking = Accesses.canCheckPtrAtRT(
2971 *PtrRtChecking, TheLoop, SymbolicStrides, UncomputablePtr,
2972 AllowPartial, getDepChecker());
2973
2974 // Check that we found the bounds for the pointer.
2975 if (!HasCompletePtrRtChecking) {
2976 auto *I = dyn_cast_or_null<Instruction>(UncomputablePtr);
2977 recordAnalysis("CantCheckMemDepsAtRunTime", I)
2978 << "cannot check memory dependencies at runtime";
2979 LLVM_DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
2980 return false;
2981 }
2982
2983 // Clear the dependency checks. They are no longer needed.
2984 Accesses.resetDepChecks(*DepChecker);
2985
2986 DepsAreSafe = true;
2987 }
2988 }
2989
2990 // Update the invariant address dependence flags based on dependences found
2991 // by the dep checker. Even if dependences were not recorded (too many to
2992 // track), any InvariantUnsafe dep would still have set the status to Unsafe
2993 if (const auto *Deps = DepChecker->getDependences()) {
2994 for (const auto &Dep : *Deps) {
2996 continue;
2997 Instruction *Src = Dep.getSource(*DepChecker);
2998 Instruction *Dst = Dep.getDestination(*DepChecker);
2999 if (isa<LoadInst>(Src) != isa<LoadInst>(Dst)) {
3000 HasLoadStoreDependenceInvolvingLoopInvariantAddress = true;
3001 } else {
3002 assert(isa<StoreInst>(Src) && isa<StoreInst>(Dst) &&
3003 "Expected both to be stores");
3004 HasStoreStoreDependenceInvolvingLoopInvariantAddress = true;
3005 }
3006 }
3007 }
3008
3009 if (HasConvergentOp) {
3010 recordAnalysis("CantInsertRuntimeCheckWithConvergent")
3011 << "cannot add control dependency to convergent operation";
3012 LLVM_DEBUG(dbgs() << "LAA: We can't vectorize because a runtime check "
3013 "would be needed with a convergent operation\n");
3014 return false;
3015 }
3016
3017 if (DepsAreSafe) {
3018 LLVM_DEBUG(
3019 dbgs() << "LAA: No unsafe dependent memory operations in loop. We"
3020 << (PtrRtChecking->Need ? "" : " don't")
3021 << " need runtime memory checks.\n");
3022 return true;
3023 }
3024
3025 emitUnsafeDependenceRemark();
3026 return false;
3027}
3028
3029void LoopAccessInfo::emitUnsafeDependenceRemark() {
3030 const auto *Deps = getDepChecker().getDependences();
3031 if (!Deps)
3032 return;
3033 const auto *Found =
3034 llvm::find_if(*Deps, [](const MemoryDepChecker::Dependence &D) {
3037 });
3038 if (Found == Deps->end())
3039 return;
3040 MemoryDepChecker::Dependence Dep = *Found;
3041
3042 LLVM_DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
3043
3044 // Emit remark for first unsafe dependence
3045 bool HasForcedDistribution =
3046 getBooleanLoopAttribute(TheLoop, "llvm.loop.distribute.enable");
3047
3048 const std::string Info =
3049 HasForcedDistribution
3050 ? "unsafe dependent memory operations in loop."
3051 : "unsafe dependent memory operations in loop. Use "
3052 "#pragma clang loop distribute(enable) to allow loop distribution "
3053 "to attempt to isolate the offending operations into a separate "
3054 "loop";
3055 OptimizationRemarkAnalysis &R =
3056 recordAnalysis("UnsafeDep", Dep.getDestination(getDepChecker())) << Info;
3057
3058 switch (Dep.Type) {
3062 llvm_unreachable("Unexpected dependence");
3064 R << "\nBackward loop carried data dependence.";
3065 break;
3067 R << "\nForward loop carried data dependence that prevents "
3068 "store-to-load forwarding.";
3069 break;
3071 R << "\nBackward loop carried data dependence that prevents "
3072 "store-to-load forwarding.";
3073 break;
3075 R << "\nUnsafe indirect dependence.";
3076 break;
3078 R << "\nUnsafe dependence on loop-invariant address.";
3079 break;
3081 R << "\nUnknown data dependence.";
3082 break;
3083 }
3084
3085 if (Instruction *I = Dep.getSource(getDepChecker())) {
3086 DebugLoc SourceLoc = I->getDebugLoc();
3088 SourceLoc = DD->getDebugLoc();
3089 if (SourceLoc)
3090 R << " Memory location is the same as accessed at "
3091 << ore::NV("Location", SourceLoc);
3092 }
3093}
3094
3096 const Loop *TheLoop,
3097 const DominatorTree *DT) {
3098 assert(TheLoop->contains(BB) && "Unknown block used");
3099
3100 // Blocks that do not dominate the latch need predication.
3101 const BasicBlock *Latch = TheLoop->getLoopLatch();
3102 assert(Latch && "Loop expected to have a single latch.");
3103 return !DT->dominates(BB, Latch);
3104}
3105
3107LoopAccessInfo::recordAnalysis(StringRef RemarkName, const Instruction *I) {
3108 assert(!Report && "Multiple reports generated");
3109
3110 const BasicBlock *CodeRegion = TheLoop->getHeader();
3111 DebugLoc DL = TheLoop->getStartLoc();
3112
3113 if (I) {
3114 CodeRegion = I->getParent();
3115 // If there is no debug location attached to the instruction, revert back to
3116 // using the loop's.
3117 if (I->getDebugLoc())
3118 DL = I->getDebugLoc();
3119 }
3120
3121 Report = std::make_unique<OptimizationRemarkAnalysis>(DEBUG_TYPE, RemarkName,
3122 DL, CodeRegion);
3123 return *Report;
3124}
3125
3127 auto *SE = PSE->getSE();
3128 if (TheLoop->isLoopInvariant(V))
3129 return true;
3130 if (!SE->isSCEVable(V->getType()))
3131 return false;
3132 const SCEV *S = SE->getSCEV(V);
3133 return SE->isLoopInvariant(S, TheLoop);
3134}
3135
3136/// If \p Ptr is a GEP, which has a loop-variant operand, return that operand.
3137/// Otherwise, return \p Ptr.
3139 Loop *Lp) {
3140 auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3141 if (!GEP)
3142 return Ptr;
3143
3144 Value *V = Ptr;
3145 for (const Use &U : GEP->operands()) {
3146 if (!SE->isLoopInvariant(SE->getSCEV(U), Lp)) {
3147 if (V == Ptr)
3148 V = U;
3149 else
3150 // There must be exactly one loop-variant operand.
3151 return Ptr;
3152 }
3153 }
3154 return V;
3155}
3156
3157/// Get the stride of a pointer access in a loop. Looks for symbolic
3158/// strides "a[i*stride]". Returns the symbolic stride, or null otherwise.
3159static const SCEV *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
3160 auto *PtrTy = dyn_cast<PointerType>(Ptr->getType());
3161 if (!PtrTy)
3162 return nullptr;
3163
3164 // Try to remove a gep instruction to make the pointer (actually index at this
3165 // point) easier analyzable. If OrigPtr is equal to Ptr we are analyzing the
3166 // pointer, otherwise, we are analyzing the index.
3167 Value *OrigPtr = Ptr;
3168
3169 Ptr = getLoopVariantGEPOperand(Ptr, SE, Lp);
3170 const SCEV *V = SE->getSCEV(Ptr);
3171
3172 if (Ptr != OrigPtr)
3173 // Strip off casts.
3174 while (auto *C = dyn_cast<SCEVIntegralCastExpr>(V))
3175 V = C->getOperand();
3176
3178 return nullptr;
3179
3180 // Note that the restriction after this loop invariant check are only
3181 // profitability restrictions.
3182 if (!SE->isLoopInvariant(V, Lp))
3183 return nullptr;
3184
3185 // Look for the loop invariant symbolic value.
3186 if (isa<SCEVUnknown>(V))
3187 return V;
3188
3189 // Look through multiplies that scale a stride by a constant.
3191 if (auto *C = dyn_cast<SCEVIntegralCastExpr>(V))
3192 if (isa<SCEVUnknown>(C->getOperand()))
3193 return V;
3194
3195 return nullptr;
3196}
3197
3198void LoopAccessInfo::collectStridedAccess(Value *MemAccess) {
3199 Value *Ptr = getLoadStorePointerOperand(MemAccess);
3200 if (!Ptr)
3201 return;
3202
3203 // Note: getStrideFromPointer is a *profitability* heuristic. We
3204 // could broaden the scope of values returned here - to anything
3205 // which happens to be loop invariant and contributes to the
3206 // computation of an interesting IV - but we chose not to as we
3207 // don't have a cost model here, and broadening the scope exposes
3208 // far too many unprofitable cases.
3209 const SCEV *StrideExpr = getStrideFromPointer(Ptr, PSE->getSE(), TheLoop);
3210 if (!StrideExpr)
3211 return;
3212
3213 if (match(StrideExpr, m_scev_UndefOrPoison()))
3214 return;
3215
3216 LLVM_DEBUG(dbgs() << "LAA: Found a strided access that is a candidate for "
3217 "versioning:");
3218 LLVM_DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *StrideExpr << "\n");
3219
3220 if (!SpeculateUnitStride) {
3221 LLVM_DEBUG(dbgs() << " Chose not to due to -laa-speculate-unit-stride\n");
3222 return;
3223 }
3224
3225 // Avoid adding the "Stride == 1" predicate when we know that
3226 // Stride >= Trip-Count. Such a predicate will effectively optimize a single
3227 // or zero iteration loop, as Trip-Count <= Stride == 1.
3228 //
3229 // TODO: We are currently not making a very informed decision on when it is
3230 // beneficial to apply stride versioning. It might make more sense that the
3231 // users of this analysis (such as the vectorizer) will trigger it, based on
3232 // their specific cost considerations; For example, in cases where stride
3233 // versioning does not help resolving memory accesses/dependences, the
3234 // vectorizer should evaluate the cost of the runtime test, and the benefit
3235 // of various possible stride specializations, considering the alternatives
3236 // of using gather/scatters (if available).
3237
3238 const SCEV *MaxBTC = PSE->getSymbolicMaxBackedgeTakenCount();
3239
3240 // Match the types so we can compare the stride and the MaxBTC.
3241 // The Stride can be positive/negative, so we sign extend Stride;
3242 // The backedgeTakenCount is non-negative, so we zero extend MaxBTC.
3243 const DataLayout &DL = TheLoop->getHeader()->getDataLayout();
3244 uint64_t StrideTypeSizeBits = DL.getTypeSizeInBits(StrideExpr->getType());
3245 uint64_t BETypeSizeBits = DL.getTypeSizeInBits(MaxBTC->getType());
3246 const SCEV *CastedStride = StrideExpr;
3247 const SCEV *CastedBECount = MaxBTC;
3248 ScalarEvolution *SE = PSE->getSE();
3249 if (BETypeSizeBits >= StrideTypeSizeBits)
3250 CastedStride = SE->getNoopOrSignExtend(StrideExpr, MaxBTC->getType());
3251 else
3252 CastedBECount = SE->getZeroExtendExpr(MaxBTC, StrideExpr->getType());
3253 const SCEV *StrideMinusBETaken = SE->getMinusSCEV(CastedStride, CastedBECount);
3254 // Since TripCount == BackEdgeTakenCount + 1, checking:
3255 // "Stride >= TripCount" is equivalent to checking:
3256 // Stride - MaxBTC> 0
3257 if (SE->isKnownPositive(StrideMinusBETaken)) {
3258 LLVM_DEBUG(
3259 dbgs() << "LAA: Stride>=TripCount; No point in versioning as the "
3260 "Stride==1 predicate will imply that the loop executes "
3261 "at most once.\n");
3262 return;
3263 }
3264 LLVM_DEBUG(dbgs() << "LAA: Found a strided access that we can version.\n");
3265
3266 // Strip back off the integer cast, and check that our result is a
3267 // SCEVUnknown as we expect.
3268 const SCEV *StrideBase = StrideExpr;
3269 if (const auto *C = dyn_cast<SCEVIntegralCastExpr>(StrideBase))
3270 StrideBase = C->getOperand();
3271 assert(SE->isLoopInvariant(StrideBase, TheLoop) &&
3272 "users of the map rely on the stride being loop invariant");
3273 SymbolicStrides[Ptr] = cast<SCEVUnknown>(StrideBase);
3274}
3275
3277 const TargetTransformInfo *TTI,
3278 const TargetLibraryInfo *TLI, AAResults *AA,
3279 DominatorTree *DT, LoopInfo *LI,
3280 AssumptionCache *AC, bool AllowPartial)
3281 : PSE(std::make_unique<PredicatedScalarEvolution>(*SE, *L)),
3282 PtrRtChecking(nullptr), TheLoop(L), AllowPartial(AllowPartial) {
3283 unsigned MaxTargetVectorWidthInBits = std::numeric_limits<unsigned>::max();
3284 if (TTI && !TTI->enableScalableVectorization())
3285 // Scale the vector width by 2 as rough estimate to also consider
3286 // interleaving.
3287 MaxTargetVectorWidthInBits =
3288 TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector) * 2;
3289
3290 DepChecker = std::make_unique<MemoryDepChecker>(
3291 *PSE, AC, DT, L, SymbolicStrides, MaxTargetVectorWidthInBits, LoopGuards);
3292 PtrRtChecking =
3293 std::make_unique<RuntimePointerChecking>(*DepChecker, SE, LoopGuards);
3294 if (canAnalyzeLoop())
3295 CanVecMem = analyzeLoop(AA, LI, TLI, DT);
3296}
3297
3298void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
3299 if (CanVecMem) {
3300 OS.indent(Depth) << "Memory dependences are safe";
3301 const MemoryDepChecker &DC = getDepChecker();
3302 if (!DC.isSafeForAnyVectorWidth())
3303 OS << " with a maximum safe vector width of "
3304 << DC.getMaxSafeVectorWidthInBits() << " bits";
3306 uint64_t SLDist = DC.getStoreLoadForwardSafeDistanceInBits();
3307 OS << ", with a maximum safe store-load forward width of " << SLDist
3308 << " bits";
3309 }
3310 if (PtrRtChecking->Need)
3311 OS << " with run-time checks";
3312 OS << "\n";
3313 }
3314
3315 if (HasConvergentOp)
3316 OS.indent(Depth) << "Has convergent operation in loop\n";
3317
3318 if (Report)
3319 OS.indent(Depth) << "Report: " << Report->getMsg() << "\n";
3320
3321 if (auto *Dependences = DepChecker->getDependences()) {
3322 OS.indent(Depth) << "Dependences:\n";
3323 for (const auto &Dep : *Dependences) {
3324 Dep.print(OS, Depth + 2, DepChecker->getMemoryInstructions());
3325 OS << "\n";
3326 }
3327 } else
3328 OS.indent(Depth) << "Too many dependences, not recorded\n";
3329
3330 // List the pair of accesses need run-time checks to prove independence.
3331 PtrRtChecking->print(OS, Depth);
3332 if (PtrRtChecking->Need && !HasCompletePtrRtChecking)
3333 OS.indent(Depth) << "Generated run-time checks are incomplete\n";
3334 OS << "\n";
3335
3336 OS.indent(Depth)
3337 << "Non vectorizable stores to invariant address were "
3338 << (HasStoreStoreDependenceInvolvingLoopInvariantAddress ||
3339 HasLoadStoreDependenceInvolvingLoopInvariantAddress
3340 ? ""
3341 : "not ")
3342 << "found in loop.\n";
3343
3344 OS.indent(Depth) << "SCEV assumptions:\n";
3345 PSE->getPredicate().print(OS, Depth);
3346
3347 OS << "\n";
3348
3349 OS.indent(Depth) << "Expressions re-written:\n";
3350 PSE->print(OS, Depth);
3351}
3352
3354 bool AllowPartial) {
3355 const auto &[It, Inserted] = LoopAccessInfoMap.try_emplace(&L);
3356
3357 // We need to create the LoopAccessInfo if either we don't already have one,
3358 // or if it was created with a different value of AllowPartial.
3359 if (Inserted || It->second->hasAllowPartial() != AllowPartial)
3360 It->second = std::make_unique<LoopAccessInfo>(&L, &SE, TTI, TLI, &AA, &DT,
3361 &LI, AC, AllowPartial);
3362
3363 return *It->second;
3364}
3366 // Collect LoopAccessInfo entries that may keep references to IR outside the
3367 // analyzed loop or SCEVs that may have been modified or invalidated. At the
3368 // moment, that is loops requiring memory or SCEV runtime checks, as those cache
3369 // SCEVs, e.g. for pointer expressions.
3370 LoopAccessInfoMap.remove_if([](const auto &Entry) {
3371 const auto &LAI = Entry.second;
3372 return !(LAI->getRuntimePointerChecking()->getChecks().empty() &&
3373 LAI->getPSE().getPredicate().isAlwaysTrue());
3374 });
3375}
3376
3378 Function &F, const PreservedAnalyses &PA,
3379 FunctionAnalysisManager::Invalidator &Inv) {
3380 // Check whether our analysis is preserved.
3381 auto PAC = PA.getChecker<LoopAccessAnalysis>();
3382 if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<Function>>())
3383 // If not, give up now.
3384 return true;
3385
3386 // Check whether the analyses we depend on became invalid for any reason.
3387 // Skip checking TargetLibraryAnalysis as it is immutable and can't become
3388 // invalid.
3389 return Inv.invalidate<AAManager>(F, PA) ||
3390 Inv.invalidate<ScalarEvolutionAnalysis>(F, PA) ||
3391 Inv.invalidate<LoopAnalysis>(F, PA) ||
3392 Inv.invalidate<DominatorTreeAnalysis>(F, PA);
3393}
3394
3397 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
3398 auto &AA = FAM.getResult<AAManager>(F);
3399 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
3400 auto &LI = FAM.getResult<LoopAnalysis>(F);
3401 auto &TTI = FAM.getResult<TargetIRAnalysis>(F);
3402 auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
3403 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
3404 return LoopAccessInfoManager(SE, AA, DT, LI, &TTI, &TLI, &AC);
3405}
3406
3407AnalysisKey LoopAccessAnalysis::Key;
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
This file implements a class to represent arbitrary precision integral constant values and operations...
@ Scaled
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
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< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
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...
DXIL Forward Handle Accesses
DXIL Resource Access
dxil translate DXIL Translate Metadata
This file defines the DenseMap class.
Generic implementation of equivalence classes through the use Tarjan's efficient union-find algorithm...
#define DEBUG_TYPE
Hexagon Common GEP
#define _
This header defines various interfaces for pass management in LLVM.
static cl::opt< unsigned > MaxDependences("max-dependences", cl::Hidden, cl::desc("Maximum number of dependences collected by " "loop-access analysis (default = 100)"), cl::init(100))
We collect dependences up to this threshold.
static cl::opt< bool > EnableForwardingConflictDetection("store-to-load-forwarding-conflict-detection", cl::Hidden, cl::desc("Enable conflict detection in loop-access analysis"), cl::init(true))
Enable store-to-load forwarding conflict detection.
static void findForkedSCEVs(ScalarEvolution *SE, const Loop *L, Value *Ptr, SmallVectorImpl< PointerIntPair< const SCEV *, 1, bool > > &ScevList, unsigned Depth)
static const SCEV * mulSCEVNoOverflow(const SCEV *A, const SCEV *B, ScalarEvolution &SE)
Returns A * B, if it is guaranteed not to unsigned wrap.
static bool isNoWrap(PredicatedScalarEvolution &PSE, const SCEVAddRecExpr *AR, Value *Ptr, Type *AccessTy, const Loop *L, const DominatorTree &DT, std::optional< int64_t > Stride=std::nullopt, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Check whether AR is a non-wrapping AddRec.
static cl::opt< unsigned > MemoryCheckMergeThreshold("memory-check-merge-threshold", cl::Hidden, cl::desc("Maximum number of comparisons done when trying to merge " "runtime memory checks. (default = 100)"), cl::init(100))
The maximum iterations used to merge memory checks.
static const SCEV * getStrideFromPointer(Value *Ptr, ScalarEvolution *SE, Loop *Lp)
Get the stride of a pointer access in a loop.
static bool isKnownNonDecreasingInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE)
Return true if S is known to be monotonically non-decreasing (in the unsigned sense,...
static cl::opt< ElementCount, true > VectorizationFactor("force-vector-width", cl::Hidden, cl::desc("Sets the SIMD width. Zero is autoselect."), cl::location(VectorizerParams::VectorizationFactor))
static bool evaluatePtrAddRecAtMaxBTCWillNotWrap(const SCEVAddRecExpr *AR, const SCEV *MaxBTC, const SCEV *EltSize, ScalarEvolution &SE, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC, std::optional< ScalarEvolution::LoopGuards > &LoopGuards)
Return true, if evaluating AR at MaxBTC cannot wrap, because AR at MaxBTC is guaranteed inbounds of t...
static cl::opt< unsigned, true > VectorizationInterleave("force-vector-interleave", cl::Hidden, cl::desc("Sets the vectorization interleave count. " "Zero is autoselect."), cl::location(VectorizerParams::VectorizationInterleave))
static cl::opt< bool, true > HoistRuntimeChecks("hoist-runtime-checks", cl::Hidden, cl::desc("Hoist inner loop runtime memory checks to outer loop if possible"), cl::location(VectorizerParams::HoistRuntimeChecks), cl::init(true))
static DenseMap< const RuntimeCheckingPtrGroup *, unsigned > getPtrToIdxMap(ArrayRef< RuntimeCheckingPtrGroup > CheckingGroups)
Assign each RuntimeCheckingPtrGroup pointer an index for stable UTC output.
static cl::opt< unsigned, true > RuntimeMemoryCheckThreshold("runtime-memory-check-threshold", cl::Hidden, cl::desc("When performing memory disambiguation checks at runtime do not " "generate more than this number of comparisons (default = 8)."), cl::location(VectorizerParams::RuntimeMemoryCheckThreshold), cl::init(8))
static void visitPointers(Value *StartPtr, const Loop &InnermostLoop, function_ref< void(Value *)> AddPointer)
static bool isSafeDependenceDistance(const DataLayout &DL, ScalarEvolution &SE, const SCEV &MaxBTC, const SCEV &Dist, uint64_t MaxStride)
Given a dependence-distance Dist between two memory accesses, that have strides in the same direction...
static bool areStridedAccessesIndependent(uint64_t Distance, uint64_t Stride, uint64_t TypeByteSize)
Check the dependence for two accesses with the same stride Stride.
static const SCEV * getMinFromExprs(const SCEV *I, const SCEV *J, ScalarEvolution *SE)
Compare I and J and return the minimum.
static std::pair< const SCEV *, const SCEV * > getNonAffineMonotonicBounds(const Loop *Lp, const SCEV *PtrExpr, const SCEV *EltSizeSCEV, ScalarEvolution *SE)
Try to bound a loop-variant pointer that is not an affine AddRec.
static Value * getLoopVariantGEPOperand(Value *Ptr, ScalarEvolution *SE, Loop *Lp)
If Ptr is a GEP, which has a loop-variant operand, return that operand.
static cl::opt< unsigned > MaxForkedSCEVDepth("max-forked-scev-depth", cl::Hidden, cl::desc("Maximum recursion depth when finding forked SCEVs (default = 5)"), cl::init(5))
static cl::opt< bool > SpeculateUnitStride("laa-speculate-unit-stride", cl::Hidden, cl::desc("Speculate that non-constant strides are unit in LAA"), cl::init(true))
static cl::opt< bool > EnableMemAccessVersioning("enable-mem-access-versioning", cl::init(true), cl::Hidden, cl::desc("Enable symbolic stride memory access versioning"))
This enables versioning on the strides of symbolically striding memory accesses in code like the foll...
static const SCEV * addSCEVNoOverflow(const SCEV *A, const SCEV *B, ScalarEvolution &SE)
Returns A + B, if it is guaranteed not to unsigned wrap.
This header provides classes for managing per-loop analyses.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file provides utility analysis objects describing memory locations.
#define P(N)
FunctionAnalysisManager FAM
This file defines the PointerIntPair class.
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallSet class.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This pass exposes codegen information to IR-level passes.
static const X86InstrFMA3Group Groups[]
A manager for alias analyses.
Class for arbitrary precision integers.
Definition APInt.h:78
std::optional< uint64_t > tryZExtValue() const
Get zero extended value if possible.
Definition APInt.h:1573
APInt abs() const
Get the absolute value.
Definition APInt.h:1816
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1086
std::optional< int64_t > trySExtValue() const
Get sign extended value if possible.
Definition APInt.h:1595
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
bool isNoBuiltin() const
Return true if the call should not be treated as a call to a builtin.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
bool isConvergent() const
Determine if the invoke is convergent.
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
static LLVM_ABI Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
bool isNegative() const
Definition Constants.h:214
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
A debug info location.
Definition DebugLoc.h:126
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:250
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
iterator end()
Definition DenseMap.h:141
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
iterator_range< member_iterator > members(const ECValue &ECV) const
bool contains(const ElemTy &V) const
Returns true if V is contained an equivalence class.
const ECValue & insert(const ElemTy &Data)
Insert a new value into the union/find set, ignoring the request if the value already exists.
member_iterator member_end() const
const ElemTy & getLeaderValue(const ElemTy &V) const
Return the leader for the specified value that is in the set.
member_iterator findLeader(const ElemTy &V) const
Given a value in the set, return a member iterator for the equivalence class it is in.
void eraseClass(const ElemTy &V)
Erase the class containing V, i.e.
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 ...
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
Definition Function.h:699
bool empty() const
Definition Function.h:844
PointerType * getType() const
Global values are always pointers.
An instruction for reading from memory.
Value * getPointerOperand()
static constexpr LocationSize beforeOrAfterPointer()
Any location before or after the base pointer (but still within the underlying object).
This analysis provides dependence information for the memory accesses of a loop.
LLVM_ABI Result run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
LLVM_ABI const LoopAccessInfo & getInfo(Loop &L, bool AllowPartial=false)
Drive the analysis of memory accesses in the loop.
const MemoryDepChecker & getDepChecker() const
the Memory Dependence Checker which can determine the loop-independent and loop-carried dependences b...
LLVM_ABI bool isInvariant(Value *V) const
Returns true if value V is loop invariant.
LLVM_ABI void print(raw_ostream &OS, unsigned Depth=0) const
Print the information about the memory accesses in the loop.
static LLVM_ABI bool blockNeedsPredication(const BasicBlock *BB, const Loop *TheLoop, const DominatorTree *DT)
Return true if the block BB needs to be predicated in order for the loop to be vectorized.
LLVM_ABI LoopAccessInfo(Loop *L, ScalarEvolution *SE, const TargetTransformInfo *TTI, const TargetLibraryInfo *TLI, AAResults *AA, DominatorTree *DT, LoopInfo *LI, AssumptionCache *AC, bool AllowPartial=false)
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:594
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
bool isInnermost() const
Return true if the loop does not contain any (natural) loops.
unsigned getNumBackEdges() const
Calculate the number of back edges to the loop header.
BlockT * getHeader() const
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
std::string getLocStr() const
Return a string containing the debug location of the loop (file name + line number if present,...
Definition LoopInfo.cpp:730
bool isAnnotatedParallel() const
Returns true if the loop is annotated parallel.
Definition LoopInfo.cpp:628
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
Definition LoopInfo.cpp:695
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1424
Checks memory dependences among accesses to the same underlying object to determine whether there vec...
ArrayRef< unsigned > getOrderForAccess(Value *Ptr, bool IsWrite) const
Return the program order indices for the access location (Ptr, IsWrite).
bool isSafeForAnyStoreLoadForwardDistances() const
Return true if there are no store-load forwarding dependencies.
LLVM_ABI bool areDepsSafe(const DepCandidates &AccessSets, ArrayRef< MemAccessInfo > CheckDeps)
Check whether the dependencies between the accesses are safe, and records the dependence information ...
bool isSafeForAnyVectorWidth() const
Return true if the number of elements that are safe to operate on simultaneously is not bounded.
static bool isStoreLoadForwardingConflict(uint64_t Distance, uint64_t VectorStoreSize, uint64_t TypeByteSize, uint64_t LoadElementSize=0)
Returns true if a memory dependence at byte distance Distance between a store (with element size Type...
PointerIntPair< Value *, 1, bool > MemAccessInfo
EquivalenceClasses< MemAccessInfo > DepCandidates
Set of potential dependent memory accesses.
bool shouldRetryWithRuntimeChecks() const
In same cases when the dependency check fails we can still vectorize the loop with a dynamic array ac...
const Loop * getInnermostLoop() const
uint64_t getMaxSafeVectorWidthInBits() const
Return the number of elements that are safe to operate on simultaneously, multiplied by the size of t...
bool isSafeForVectorization() const
No memory dependence was encountered that would inhibit vectorization.
const SmallVectorImpl< Dependence > * getDependences() const
Returns the memory dependences.
LLVM_ABI SmallVector< Instruction *, 4 > getInstructionsForAccess(Value *Ptr, bool isWrite) const
Find the set of instructions that read or write via Ptr.
VectorizationSafetyStatus
Type to keep track of the status of the dependence check.
LLVM_ABI void addAccess(StoreInst *SI)
Register the location (instructions are given increasing numbers) of a write access.
uint64_t getStoreLoadForwardSafeDistanceInBits() const
Return safe power-of-2 number of elements, which do not prevent store-load forwarding,...
Representation for a specific memory location.
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
LocationSize Size
The maximum size of the location, in address-units, or UnknownSize if the size is not known.
AAMDNodes AATags
The metadata nodes which describes the aliasing of the location (each member is null if that kind of ...
const Value * Ptr
The address of the start of the location.
Diagnostic information for optimization analysis remarks.
PointerIntPair - This class implements a pair of a pointer and small integer.
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
LLVM_ABI void addPredicate(const SCEVPredicate &Pred)
Adds a new predicate.
ScalarEvolution * getSE() const
Returns the ScalarEvolution analysis used.
LLVM_ABI bool hasNoOverflow(Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags)
Returns true if we've statically proved that V doesn't wrap.
LLVM_ABI const SCEVAddRecExpr * getAsAddRec(Value *V, SmallVectorImpl< const SCEVPredicate * > *WrapPredsAdded=nullptr)
Attempts to produce an AddRecExpr for V by adding additional SCEV predicates.
LLVM_ABI void addPredicates(ArrayRef< const SCEVPredicate * > Preds)
Adds all predicates in Preds.
LLVM_ABI const SCEV * getBackedgeTakenCount()
Get the (predicated) backedge count for the analyzed loop.
LLVM_ABI const SCEV * getSymbolicMaxBackedgeTakenCount()
Get the (predicated) symbolic max backedge count for the analyzed loop.
LLVM_ABI const SCEV * getSCEV(Value *V)
Returns the SCEV expression of V, in the context of the current SCEV predicate.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
Holds information about the memory runtime legality checks to verify that a group of pointers do not ...
bool Need
This flag indicates if we need to add the runtime check.
void reset()
Reset the state of the pointer runtime information.
unsigned getNumberOfChecks() const
Returns the number of run-time checks required according to needsChecking.
LLVM_ABI void printChecks(raw_ostream &OS, const SmallVectorImpl< RuntimePointerCheck > &Checks, unsigned Depth=0) const
Print Checks.
LLVM_ABI bool needsChecking(const RuntimeCheckingPtrGroup &M, const RuntimeCheckingPtrGroup &N) const
Decide if we need to add a check between two groups of pointers, according to needsChecking.
LLVM_ABI void print(raw_ostream &OS, unsigned Depth=0) const
Print the list run-time memory checks necessary.
SmallVector< RuntimeCheckingPtrGroup, 2 > CheckingGroups
Holds a partitioning of pointers into "check groups".
static LLVM_ABI bool arePointersInSamePartition(const SmallVectorImpl< int > &PtrToPartition, unsigned PtrIdx1, unsigned PtrIdx2)
Check if pointers are in the same partition.
LLVM_ABI bool insert(Loop *Lp, Value *Ptr, const SCEV *PtrExpr, Type *AccessTy, bool WritePtr, unsigned DepSetId, unsigned ASId, PredicatedScalarEvolution &PSE, bool NeedsFreeze)
Insert a pointer and calculate the start and end SCEVs.
LLVM_ABI void generateChecks(MemoryDepChecker::DepCandidates &DepCands)
Generate the checks and store it.
SmallVector< PointerInfo, 2 > Pointers
Information about the pointers that may require checking.
This node represents a polynomial recurrence on the trip count of the specified loop.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
SCEVUse getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
This class represents a constant integer value.
ConstantInt * getValue() const
const APInt & getAPInt() const
NoWrapFlags getNoWrapFlags(NoWrapFlags Mask=NoWrapMask) const
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
IncrementWrapFlags
Similar to SCEV::NoWrapFlags, but with slightly different semantics for FlagNUSW.
static SCEVWrapPredicate::IncrementWrapFlags clearFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OffFlags)
Convenient IncrementWrapFlags manipulation methods.
static SCEVWrapPredicate::IncrementWrapFlags getImpliedFlags(const SCEVAddRecExpr *AR, ScalarEvolution &SE)
Returns the set of SCEVWrapPredicate no wrap flags implied by a SCEVAddRecExpr.
This class represents an analyzed expression in the program.
static constexpr auto NoWrapMask
LLVM_ABI bool isZero() const
Return true if the expression is a constant zero.
Type * getType() const
Return the LLVM type of this SCEV expression.
SCEVTypes getSCEVType() const
Analysis pass that exposes the ScalarEvolution for a function.
static LLVM_ABI LoopGuards collect(const Loop *L, ScalarEvolution &SE)
Collect rewrite map for loop guards for loop L, together with flags indicating if NUW and NSW can be ...
The main scalar evolution driver.
const SCEV * getConstantMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEVConstant that is greater than or equal to (i.e.
LLVM_ABI bool isKnownNonNegative(const SCEV *S)
Test if the given expression is known to be non-negative.
LLVM_ABI const SCEV * getNegativeSCEV(const SCEV *V, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
Return the SCEV object corresponding to -V.
LLVM_ABI const SCEV * getZeroExtendExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI Type * getWiderType(Type *Ty1, Type *Ty2) const
LLVM_ABI const SCEV * getAbsExpr(const SCEV *Op, bool IsNSW)
LLVM_ABI bool isKnownNonPositive(const SCEV *S)
Test if the given expression is known to be non-positive.
LLVM_ABI bool isKnownNegative(const SCEV *S)
Test if the given expression is known to be negative.
LLVM_ABI bool willNotOverflow(Instruction::BinaryOps BinOp, bool Signed, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI=nullptr)
Is operation BinOp between LHS and RHS provably does not have a signed/unsigned overflow (Signed)?
LLVM_ABI const SCEVPredicate * getEqualPredicate(const SCEV *LHS, const SCEV *RHS)
LLVM_ABI SCEVUse getSCEVAtScope(const SCEV *S, const Loop *L)
Return a SCEV expression for the specified value at the specified scope in the program.
LLVM_ABI const SCEV * getConstant(ConstantInt *V)
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS.
LLVM_ABI const SCEV * getNoopOrSignExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI bool isKnownPositive(const SCEV *S)
Test if the given expression is known to be positive.
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
LLVM_ABI Type * getEffectiveSCEVType(Type *Ty) const
Return a type with the same bitwidth as the given type and which represents how SCEV will treat the g...
APInt getSignedRangeMin(const SCEV *S)
Determine the min of the signed range for a particular SCEV.
LLVM_ABI const SCEV * getUMaxExpr(SCEVUse LHS, SCEVUse RHS)
LLVM_ABI const SCEV * getStoreSizeOfExpr(Type *IntTy, Type *StoreTy)
Return an expression for the store size of StoreTy that is type IntTy.
LLVM_ABI const SCEVPredicate * getWrapPredicate(const SCEVAddRecExpr *AR, SCEVWrapPredicate::IncrementWrapFlags AddedFlags)
LLVM_ABI const SCEV * getNoopOrZeroExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI std::optional< MonotonicPredicateType > getMonotonicPredicateType(const SCEVAddRecExpr *LHS, ICmpInst::Predicate Pred)
If, for all loop invariant X, the predicate "LHS `Pred` X" is monotonically increasing or decreasing,...
LLVM_ABI const SCEV * getCouldNotCompute()
LLVM_ABI const SCEV * getMulExpr(SmallVectorImpl< SCEVUse > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
LLVM_ABI const SCEV * getPointerBase(const SCEV *V)
Transitively follow the chain of pointer-type operands until reaching a SCEV that does not have a sin...
LLVM_ABI const SCEV * getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
LLVM_ABI bool isKnownPredicate(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
LLVM_ABI const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
LLVM_ABI const SCEV * getPtrToAddrExpr(const SCEV *Op)
LLVM_ABI const SCEVAddRecExpr * convertSCEVToAddRecWithPredicates(const SCEV *S, const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Preds)
Tries to convert the S expression to an AddRec expression, adding additional predicates to Preds as r...
LLVM_ABI const SCEV * getSizeOfExpr(Type *IntTy, TypeSize Size)
Return an expression for a TypeSize.
LLVM_ABI std::optional< APInt > computeConstantDifference(const SCEV *LHS, const SCEV *RHS)
Compute LHS - RHS and returns the result as an APInt if it is a constant, and std::nullopt if it isn'...
LLVM_ABI std::pair< const SCEV *, const SCEV * > SplitIntoInitAndPostInc(const Loop *L, const SCEV *S)
Splits SCEV expression S into two SCEVs.
LLVM_ABI const SCEV * getUMinExpr(SCEVUse LHS, SCEVUse RHS, bool Sequential=false)
LLVM_ABI const SCEV * getTruncateOrSignExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
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.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
bool contains(const T &V) const
Check if the SmallSet contains the given element.
Definition SmallSet.h:229
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
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
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
static SmallVector< VFInfo, 8 > getMappings(const CallInst &CI)
Retrieve all the VFInfo instances associated to the CallInst CI.
Definition VectorUtils.h:76
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
LLVM_ABI uint64_t getPointerDereferenceableBytes(const DataLayout &DL, bool &CanBeNull, bool *CanBeFreed) const
Returns the number of bytes known to be dereferenceable for the pointer value.
Definition Value.cpp:918
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:165
bool match(Val *V, const Pattern &P)
bind_cst_ty m_scev_APInt(const APInt *&C)
Match an SCEV constant and bind it to an APInt.
is_undef_or_poison m_scev_UndefOrPoison()
Match an SCEVUnknown wrapping undef or poison.
specificloop_ty m_SpecificLoop(const Loop *L)
match_bind< const SCEVMulExpr > m_scev_Mul(const SCEVMulExpr *&V)
specificscev_ty m_scev_Specific(const SCEV *S)
Match if we have a specific specified SCEV.
SCEVAffineAddRec_match< Op0_t, Op1_t, match_isa< const Loop > > m_scev_AffineAddRec(const Op0_t &Op0, const Op1_t &Op1)
initializer< Ty > init(const Ty &Val)
LocationClass< Ty > location(Ty &L)
DiagnosticInfoOptimizationBase::Argument NV
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI std::pair< const SCEV *, const SCEV * > getStartAndEndForAccess(const Loop *Lp, const SCEV *PtrExpr, Type *AccessTy, const SCEV *BTC, const SCEV *MaxBTC, ScalarEvolution *SE, DenseMap< std::pair< const SCEV *, const SCEV * >, std::pair< const SCEV *, const SCEV * > > *PointerBounds, DominatorTree *DT, AssumptionCache *AC, std::optional< ScalarEvolution::LoopGuards > &LoopGuards)
Calculate Start and End points of memory access using exact backedge taken count BTC if computable or...
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
@ Offset
Definition DWP.cpp:577
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:830
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
LLVM_ABI RetainedKnowledge getKnowledgeForValue(const Value *V, ArrayRef< Attribute::AttrKind > AttrKinds, AssumptionCache &AC, function_ref< bool(RetainedKnowledge, Instruction *, const CallBase::BundleOpInfo *)> Filter=[](auto...) { return true;})
Return a valid Knowledge associated to the Value V if its Attribute kind is in AttrKinds and it match...
LLVM_ABI bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI, const DominatorTree *DT=nullptr, bool AllowEphemerals=false)
Return true if it is valid to use the assumptions provided by an assume intrinsic,...
LLVM_ABI bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name)
Returns true if Name is applied to TheLoop and enabled.
LLVM_ABI Intrinsic::ID getVectorIntrinsicIDForCall(const CallInst *CI, const TargetLibraryInfo *TLI)
Returns intrinsic ID for call.
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:2554
unsigned getPointerAddressSpace(const Type *T)
Definition SPIRVUtils.h:395
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.
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
LLVM_ABI const SCEV * replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE, const SymbolicStrideMap &PtrToStride, Value *Ptr)
Return the SCEV corresponding to a pointer with the symbolic stride replaced with constant one,...
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
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.
const Value * getPointerOperand(const Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
Definition STLExtras.h:2026
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
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
DenseMap< Value *, const SCEVUnknown * > SymbolicStrideMap
Maps a pointer to its symbolic (non-constant) stride.
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI std::optional< int64_t > getPointersDiff(Type *ElemTyA, Value *PtrA, Type *ElemTyB, Value *PtrB, const DataLayout &DL, ScalarEvolution &SE, bool StrictCheck=false, bool CheckType=true)
Returns the distance between the pointers PtrA and PtrB iff they are compatible and it is possible to...
LLVM_ABI bool sortPtrAccesses(ArrayRef< Value * > VL, Type *ElemTy, const DataLayout &DL, ScalarEvolution &SE, SmallVectorImpl< unsigned > &SortedIndices)
Attempt to sort the pointers in VL and return the sorted indices in SortedIndices,...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
TargetTransformInfo TTI
LLVM_ABI bool isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL, ScalarEvolution &SE, bool CheckType=true)
Returns true if the memory operations A and B are consecutive.
IntPtrTy
Definition InstrProf.h:82
DWARFExpression::Operation Op
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr U AbsoluteValue(T X)
Return the absolute value of a signed integer, converted to the corresponding unsigned integer type.
Definition MathExtras.h:587
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:1772
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI std::optional< int64_t > getStrideFromAddRec(const SCEVAddRecExpr *AR, const Loop *Lp, Type *AccessTy, Value *Ptr, PredicatedScalarEvolution &PSE)
If AR is an affine AddRec for Lp with a constant step, return the step in units of AccessTy's allocat...
T bit_floor(T Value)
Returns the largest integral power of two no greater than Value if Value is nonzero.
Definition bit.h:347
LLVM_ABI void getUnderlyingObjects(const Value *V, SmallVectorImpl< const Value * > &Objects, const LoopInfo *LI=nullptr, unsigned MaxLookup=MaxLookupSearchDepth)
This method is similar to getUnderlyingObject except that it can look through phi and select instruct...
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
IR Values for the lower and upper bounds of a pointer evolution.
MDNode * Scope
The tag for alias scope specification (used with noalias).
Definition Metadata.h:786
MDNode * TBAA
The tag for type-based alias analysis.
Definition Metadata.h:780
MDNode * NoAlias
The tag specifying the noalias scope.
Definition Metadata.h:789
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
Instruction * getDestination(const MemoryDepChecker &DepChecker) const
Return the destination instruction of the dependence.
DepType Type
The type of the dependence.
unsigned Destination
Index of the destination of the dependence in the InstMap vector.
LLVM_ABI bool isPossiblyBackward() const
May be a lexically backward dependence type (includes Unknown).
Instruction * getSource(const MemoryDepChecker &DepChecker) const
Return the source instruction of the dependence.
LLVM_ABI bool isForward() const
Lexically forward dependence.
LLVM_ABI bool isBackward() const
Lexically backward dependence.
LLVM_ABI void print(raw_ostream &OS, unsigned Depth, const SmallVectorImpl< Instruction * > &Instrs) const
Print the dependence.
unsigned Source
Index of the source of the dependence in the InstMap vector.
DepType
The type of the dependence.
static LLVM_ABI const char * DepName[]
String version of the types.
static LLVM_ABI VectorizationSafetyStatus isSafeForVectorization(DepType Type)
Dependence types that don't prevent vectorization.
Represent one information held inside an operand bundle of an llvm.assume.
unsigned AddressSpace
Address space of the involved pointers.
LLVM_ABI bool addPointer(unsigned Index, const RuntimePointerChecking &RtCheck)
Tries to add the pointer recorded in RtCheck at index Index to this pointer checking group.
bool NeedsFreeze
Whether the pointer needs to be frozen after expansion, e.g.
LLVM_ABI RuntimeCheckingPtrGroup(unsigned Index, const RuntimePointerChecking &RtCheck)
Create a new pointer checking group containing a single pointer, with index Index in RtCheck.
const SCEV * High
The SCEV expression which represents the upper bound of all the pointers in this group.
SmallVector< unsigned, 2 > Members
Indices of all the pointers that constitute this grouping.
const SCEV * Low
The SCEV expression which represents the lower bound of all the pointers in this group.
bool IsWritePtr
Holds the information if this pointer is used for writing to memory.
unsigned DependencySetId
Holds the id of the set of pointers that could be dependent because of a shared underlying object.
unsigned AliasSetId
Holds the id of the disjoint alias set to which this pointer belongs.
static LLVM_ABI const unsigned MaxVectorWidth
Maximum SIMD width.
static LLVM_ABI unsigned RuntimeMemoryCheckThreshold
\When performing memory disambiguation checks at runtime do not make more than this number of compari...
static LLVM_ABI bool isInterleaveForced()
True if force-vector-interleave was specified by the user.
static LLVM_ABI unsigned VectorizationInterleave
Interleave factor as overridden by the user.
static LLVM_ABI ElementCount VectorizationFactor
VF as overridden by the user.
static LLVM_ABI bool HoistRuntimeChecks
Function object to check whether the first component of a container supported by std::get (like std::...
Definition STLExtras.h:1439