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
328std::pair<const SCEV *, const SCEV *> llvm::getStartAndEndForAccess(
329 const Loop *Lp, const SCEV *PtrExpr, Type *AccessTy, const SCEV *BTC,
330 const SCEV *MaxBTC, ScalarEvolution *SE,
331 DenseMap<std::pair<const SCEV *, const SCEV *>,
332 std::pair<const SCEV *, const SCEV *>> *PointerBounds,
334 std::optional<ScalarEvolution::LoopGuards> &LoopGuards) {
335 auto &DL = Lp->getHeader()->getDataLayout();
336 Type *IdxTy = DL.getIndexType(PtrExpr->getType());
337 const SCEV *EltSizeSCEV = SE->getStoreSizeOfExpr(IdxTy, AccessTy);
338
339 // Delegate to the SCEV-based overload, passing through the cache.
340 return getStartAndEndForAccess(Lp, PtrExpr, EltSizeSCEV, BTC, MaxBTC, SE,
341 PointerBounds, DT, AC, LoopGuards);
342}
343
344std::pair<const SCEV *, const SCEV *> llvm::getStartAndEndForAccess(
345 const Loop *Lp, const SCEV *PtrExpr, const SCEV *EltSizeSCEV,
346 const SCEV *BTC, const SCEV *MaxBTC, ScalarEvolution *SE,
347 DenseMap<std::pair<const SCEV *, const SCEV *>,
348 std::pair<const SCEV *, const SCEV *>> *PointerBounds,
350 std::optional<ScalarEvolution::LoopGuards> &LoopGuards) {
351 std::pair<const SCEV *, const SCEV *> *PtrBoundsPair;
352 if (PointerBounds) {
353 auto [Iter, Ins] = PointerBounds->insert(
354 {{PtrExpr, EltSizeSCEV},
355 {SE->getCouldNotCompute(), SE->getCouldNotCompute()}});
356 if (!Ins)
357 return Iter->second;
358 PtrBoundsPair = &Iter->second;
359 }
360
361 const SCEV *ScStart;
362 const SCEV *ScEnd;
363
364 auto &DL = Lp->getHeader()->getDataLayout();
365 if (SE->isLoopInvariant(PtrExpr, Lp)) {
366 ScStart = ScEnd = PtrExpr;
367 } else if (auto *AR = dyn_cast<SCEVAddRecExpr>(PtrExpr)) {
368 ScStart = AR->getStart();
369 if (!isa<SCEVCouldNotCompute>(BTC))
370 // Evaluating AR at an exact BTC is safe: LAA separately checks that
371 // accesses cannot wrap in the loop. If evaluating AR at BTC wraps, then
372 // the loop either triggers UB when executing a memory access with a
373 // poison pointer or the wrapping/poisoned pointer is not used.
374 ScEnd = AR->evaluateAtIteration(BTC, *SE);
375 else {
376 // Evaluating AR at MaxBTC may wrap and create an expression that is less
377 // than the start of the AddRec due to wrapping (for example consider
378 // MaxBTC = -2). If that's the case, set ScEnd to -(EltSize + 1). ScEnd
379 // will get incremented by EltSize before returning, so this effectively
380 // sets ScEnd to the maximum unsigned value for the type. Note that LAA
381 // separately checks that accesses cannot not wrap, so unsigned max
382 // represents an upper bound.
383 if (evaluatePtrAddRecAtMaxBTCWillNotWrap(AR, MaxBTC, EltSizeSCEV, *SE, DL,
384 DT, AC, LoopGuards)) {
385 ScEnd = AR->evaluateAtIteration(MaxBTC, *SE);
386 } else {
387 ScEnd = SE->getAddExpr(
388 SE->getNegativeSCEV(EltSizeSCEV),
391 AR->getType())));
392 }
393 }
394 const SCEV *Step = AR->getStepRecurrence(*SE);
395
396 // For expressions with negative step, the upper bound is ScStart and the
397 // lower bound is ScEnd.
398 if (const auto *CStep = dyn_cast<SCEVConstant>(Step)) {
399 if (CStep->getValue()->isNegative())
400 std::swap(ScStart, ScEnd);
401 } else {
402 // Fallback case: the step is not constant, but we can still
403 // get the upper and lower bounds of the interval by using min/max
404 // expressions.
405 ScStart = SE->getUMinExpr(ScStart, ScEnd);
406 ScEnd = SE->getUMaxExpr(AR->getStart(), ScEnd);
407 }
408 } else
409 return {SE->getCouldNotCompute(), SE->getCouldNotCompute()};
410
411 assert(SE->isLoopInvariant(ScStart, Lp) && "ScStart needs to be invariant");
412 assert(SE->isLoopInvariant(ScEnd, Lp) && "ScEnd needs to be invariant");
413
414 // Add the size of the pointed element to ScEnd.
415 ScEnd = SE->getAddExpr(ScEnd, EltSizeSCEV);
416
417 std::pair<const SCEV *, const SCEV *> Res = {ScStart, ScEnd};
418 if (PointerBounds)
419 *PtrBoundsPair = Res;
420 return Res;
421}
422
423/// Calculate Start and End points of memory access using
424/// getStartAndEndForAccess.
425void RuntimePointerChecking::insert(Loop *Lp, Value *Ptr, const SCEV *PtrExpr,
426 Type *AccessTy, bool WritePtr,
427 unsigned DepSetId, unsigned ASId,
429 bool NeedsFreeze) {
430 const SCEV *SymbolicMaxBTC = PSE.getSymbolicMaxBackedgeTakenCount();
431 const SCEV *BTC = PSE.getBackedgeTakenCount();
432 const auto &[ScStart, ScEnd] = getStartAndEndForAccess(
433 Lp, PtrExpr, AccessTy, BTC, SymbolicMaxBTC, PSE.getSE(),
434 &DC.getPointerBounds(), DC.getDT(), DC.getAC(), LoopGuards);
436 !isa<SCEVCouldNotCompute>(ScEnd) &&
437 "must be able to compute both start and end expressions");
438 Pointers.emplace_back(Ptr, ScStart, ScEnd, WritePtr, DepSetId, ASId, PtrExpr,
439 NeedsFreeze);
440}
441
442bool RuntimePointerChecking::tryToCreateDiffCheck(
443 const RuntimeCheckingPtrGroup &CGI, const RuntimeCheckingPtrGroup &CGJ) {
444 // If either group contains multiple different pointers, bail out.
445 // TODO: Support multiple pointers by using the minimum or maximum pointer,
446 // depending on src & sink.
447 if (CGI.Members.size() != 1 || CGJ.Members.size() != 1)
448 return false;
449
450 const PointerInfo *Src = &Pointers[CGI.Members[0]];
451 const PointerInfo *Sink = &Pointers[CGJ.Members[0]];
452
453 // If either pointer is read and written, multiple checks may be needed. Bail
454 // out.
455 if (!DC.getOrderForAccess(Src->PointerValue, !Src->IsWritePtr).empty() ||
456 !DC.getOrderForAccess(Sink->PointerValue, !Sink->IsWritePtr).empty())
457 return false;
458
459 ArrayRef<unsigned> AccSrc =
460 DC.getOrderForAccess(Src->PointerValue, Src->IsWritePtr);
461 ArrayRef<unsigned> AccSink =
462 DC.getOrderForAccess(Sink->PointerValue, Sink->IsWritePtr);
463 // If either pointer is accessed multiple times, there may not be a clear
464 // src/sink relation. Bail out for now.
465 if (AccSrc.size() != 1 || AccSink.size() != 1)
466 return false;
467
468 // If the sink is accessed before src, swap src/sink.
469 if (AccSink[0] < AccSrc[0])
470 std::swap(Src, Sink);
471
472 const SCEVConstant *Step;
473 const SCEV *SrcStart;
474 const SCEV *SinkStart;
475 const Loop *InnerLoop = DC.getInnermostLoop();
476 if (!match(Src->Expr,
478 m_SpecificLoop(InnerLoop))) ||
479 !match(Sink->Expr,
481 m_SpecificLoop(InnerLoop))))
482 return false;
483
485 DC.getInstructionsForAccess(Src->PointerValue, Src->IsWritePtr);
487 DC.getInstructionsForAccess(Sink->PointerValue, Sink->IsWritePtr);
488 Type *SrcTy = getLoadStoreType(SrcInsts[0]);
489 Type *DstTy = getLoadStoreType(SinkInsts[0]);
491 return false;
492
493 const DataLayout &DL = InnerLoop->getHeader()->getDataLayout();
494 unsigned AllocSize =
495 std::max(DL.getTypeAllocSize(SrcTy), DL.getTypeAllocSize(DstTy));
496
497 // Only matching constant steps matching the AllocSize are supported at the
498 // moment. This simplifies the difference computation. Can be extended in the
499 // future.
500 if (Step->getAPInt().abs() != AllocSize)
501 return false;
502
503 // When counting down, the dependence distance needs to be swapped.
504 if (Step->getValue()->isNegative())
505 std::swap(SinkStart, SrcStart);
506
507 const SCEV *SinkStartInt = SE->getPtrToAddrExpr(SinkStart);
508 const SCEV *SrcStartInt = SE->getPtrToAddrExpr(SrcStart);
509 if (isa<SCEVCouldNotCompute>(SinkStartInt) ||
510 isa<SCEVCouldNotCompute>(SrcStartInt))
511 return false;
512
513 // If the start values for both Src and Sink also vary according to an outer
514 // loop, then it's probably better to avoid creating diff checks because
515 // they may not be hoisted. We should instead let llvm::addRuntimeChecks
516 // do the expanded full range overlap checks, which can be hoisted.
517 if (HoistRuntimeChecks && InnerLoop->getParentLoop() &&
518 isa<SCEVAddRecExpr>(SinkStartInt) && isa<SCEVAddRecExpr>(SrcStartInt)) {
519 auto *SrcStartAR = cast<SCEVAddRecExpr>(SrcStartInt);
520 auto *SinkStartAR = cast<SCEVAddRecExpr>(SinkStartInt);
521 const Loop *StartARLoop = SrcStartAR->getLoop();
522 if (StartARLoop == SinkStartAR->getLoop() &&
523 StartARLoop == InnerLoop->getParentLoop() &&
524 // If the diff check would already be loop invariant (due to the
525 // recurrences being the same), then we prefer to keep the diff checks
526 // because they are cheaper.
527 SrcStartAR->getStepRecurrence(*SE) !=
528 SinkStartAR->getStepRecurrence(*SE)) {
529 LLVM_DEBUG(dbgs() << "LAA: Not creating diff runtime check, since these "
530 "cannot be hoisted out of the outer loop\n");
531 return false;
532 }
533 }
534
535 LLVM_DEBUG(dbgs() << "LAA: Creating diff runtime check for:\n"
536 << "SrcStart: " << *SrcStartInt << '\n'
537 << "SinkStartInt: " << *SinkStartInt << '\n');
538 DiffChecks.emplace_back(SrcStartInt, SinkStartInt, AllocSize,
539 Src->NeedsFreeze || Sink->NeedsFreeze);
540 return true;
541}
542
544 SmallVector<RuntimePointerCheck, 4> Checks;
545
546 for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
547 for (unsigned J = I + 1; J < CheckingGroups.size(); ++J) {
550
551 if (needsChecking(CGI, CGJ)) {
552 CanUseDiffCheck = CanUseDiffCheck && tryToCreateDiffCheck(CGI, CGJ);
553 Checks.emplace_back(&CGI, &CGJ);
554 }
555 }
556 }
557 return Checks;
558}
559
562 assert(Checks.empty() && "Checks is not empty");
563 groupChecks(DepCands);
564 Checks = generateChecks();
565}
566
568 const RuntimeCheckingPtrGroup &M, const RuntimeCheckingPtrGroup &N) const {
569 for (const auto &I : M.Members)
570 for (const auto &J : N.Members)
571 if (needsChecking(I, J))
572 return true;
573 return false;
574}
575
576/// Compare \p I and \p J and return the minimum.
577/// Return nullptr in case we couldn't find an answer.
578static const SCEV *getMinFromExprs(const SCEV *I, const SCEV *J,
579 ScalarEvolution *SE) {
580 std::optional<APInt> Diff = SE->computeConstantDifference(J, I);
581 if (!Diff)
582 return nullptr;
583 return Diff->isNegative() ? J : I;
584}
585
587 unsigned Index, const RuntimePointerChecking &RtCheck) {
588 return addPointer(
589 Index, RtCheck.Pointers[Index].Start, RtCheck.Pointers[Index].End,
590 RtCheck.Pointers[Index].PointerValue->getType()->getPointerAddressSpace(),
591 RtCheck.Pointers[Index].NeedsFreeze, *RtCheck.SE);
592}
593
594bool RuntimeCheckingPtrGroup::addPointer(unsigned Index, const SCEV *Start,
595 const SCEV *End, unsigned AS,
596 bool NeedsFreeze,
597 ScalarEvolution &SE) {
598 assert(AddressSpace == AS &&
599 "all pointers in a checking group must be in the same address space");
600
601 // Compare the starts and ends with the known minimum and maximum
602 // of this set. We need to know how we compare against the min/max
603 // of the set in order to be able to emit memchecks.
604 const SCEV *Min0 = getMinFromExprs(Start, Low, &SE);
605 if (!Min0)
606 return false;
607
608 const SCEV *Min1 = getMinFromExprs(End, High, &SE);
609 if (!Min1)
610 return false;
611
612 // Update the low bound expression if we've found a new min value.
613 if (Min0 == Start)
614 Low = Start;
615
616 // Update the high bound expression if we've found a new max value.
617 if (Min1 != End)
618 High = End;
619
620 Members.push_back(Index);
621 this->NeedsFreeze |= NeedsFreeze;
622 return true;
623}
624
625void RuntimePointerChecking::groupChecks(
627 // We build the groups from dependency candidates equivalence classes
628 // because:
629 // - We know that pointers in the same equivalence class share
630 // the same underlying object and therefore there is a chance
631 // that we can compare pointers
632 // - We wouldn't be able to merge two pointers for which we need
633 // to emit a memcheck. The classes in DepCands are already
634 // conveniently built such that no two pointers in the same
635 // class need checking against each other.
636
637 // We use the following (greedy) algorithm to construct the groups
638 // For every pointer in the equivalence class:
639 // For each existing group:
640 // - if the difference between this pointer and the min/max bounds
641 // of the group is a constant, then make the pointer part of the
642 // group and update the min/max bounds of that group as required.
643
644 CheckingGroups.clear();
645
646 // If we need to check two pointers to the same underlying object
647 // with a non-constant difference, we shouldn't perform any pointer
648 // grouping with those pointers. This is because we can easily get
649 // into cases where the resulting check would return false, even when
650 // the accesses are safe.
651 //
652 // The following example shows this:
653 // for (i = 0; i < 1000; ++i)
654 // a[5000 + i * m] = a[i] + a[i + 9000]
655 //
656 // Here grouping gives a check of (5000, 5000 + 1000 * m) against
657 // (0, 10000) which is always false. However, if m is 1, there is no
658 // dependence. Not grouping the checks for a[i] and a[i + 9000] allows
659 // us to perform an accurate check in this case.
660 //
661 // In the above case, we have a non-constant distance and an Unknown
662 // dependence between accesses to the same underlying object, and could retry
663 // with runtime checks without dependency information being available. In this
664 // case we will use the fallback path and create separate checking groups for
665 // accesses not present in DepCands.
666
667 unsigned TotalComparisons = 0;
668
670 for (unsigned Index = 0; Index < Pointers.size(); ++Index)
671 PositionMap[Pointers[Index].PointerValue].push_back(Index);
672
673 // We need to keep track of what pointers we've already seen so we
674 // don't process them twice.
676
677 // Go through all equivalence classes, get the "pointer check groups"
678 // and add them to the overall solution. We use the order in which accesses
679 // appear in 'Pointers' to enforce determinism.
680 for (unsigned I = 0; I < Pointers.size(); ++I) {
681 // We've seen this pointer before, and therefore already processed
682 // its equivalence class.
683 if (Seen.contains(I))
684 continue;
685
687 Pointers[I].IsWritePtr);
688
689 // If there is no entry in the dependency partition, there are no potential
690 // accesses to merge; simply add a new pointer checking group.
691 if (!DepCands.contains(Access)) {
692 CheckingGroups.push_back(RuntimeCheckingPtrGroup(I, *this));
693 continue;
694 }
695
697
698 // Because DepCands is constructed by visiting accesses in the order in
699 // which they appear in alias sets (which is deterministic) and the
700 // iteration order within an equivalence class member is only dependent on
701 // the order in which unions and insertions are performed on the
702 // equivalence class, the iteration order is deterministic.
703 for (auto M : DepCands.members(Access)) {
704 auto PointerI = PositionMap.find(M.getPointer());
705 // If we can't find the pointer in PositionMap that means we can't
706 // generate a memcheck for it.
707 if (PointerI == PositionMap.end())
708 continue;
709 for (unsigned Pointer : PointerI->second) {
710 bool Merged = false;
711 // Mark this pointer as seen.
712 Seen.insert(Pointer);
713
714 // Go through all the existing sets and see if we can find one
715 // which can include this pointer.
716 for (RuntimeCheckingPtrGroup &Group : Groups) {
717 // Don't perform more than a certain amount of comparisons.
718 // This should limit the cost of grouping the pointers to something
719 // reasonable. If we do end up hitting this threshold, the algorithm
720 // will create separate groups for all remaining pointers.
721 if (TotalComparisons > MemoryCheckMergeThreshold)
722 break;
723
724 TotalComparisons++;
725
726 if (Group.addPointer(Pointer, *this)) {
727 Merged = true;
728 break;
729 }
730 }
731
732 if (!Merged)
733 // We couldn't add this pointer to any existing set or the threshold
734 // for the number of comparisons has been reached. Create a new group
735 // to hold the current pointer.
736 Groups.emplace_back(Pointer, *this);
737 }
738 }
739
740 // We've computed the grouped checks for this partition.
741 // Save the results and continue with the next one.
743 }
744}
745
747 const SmallVectorImpl<int> &PtrToPartition, unsigned PtrIdx1,
748 unsigned PtrIdx2) {
749 return (PtrToPartition[PtrIdx1] != -1 &&
750 PtrToPartition[PtrIdx1] == PtrToPartition[PtrIdx2]);
751}
752
753bool RuntimePointerChecking::needsChecking(unsigned I, unsigned J) const {
754 const PointerInfo &PointerI = Pointers[I];
755 const PointerInfo &PointerJ = Pointers[J];
756
757 // No need to check if two readonly pointers intersect.
758 if (!PointerI.IsWritePtr && !PointerJ.IsWritePtr)
759 return false;
760
761 // Only need to check pointers between two different dependency sets.
762 if (PointerI.DependencySetId == PointerJ.DependencySetId)
763 return false;
764
765 // Only need to check pointers in the same alias set.
766 return PointerI.AliasSetId == PointerJ.AliasSetId;
767}
768
769/// Assign each RuntimeCheckingPtrGroup pointer an index for stable UTC output.
773 for (const auto &[Idx, CG] : enumerate(CheckingGroups))
774 PtrIndices[&CG] = Idx;
775 return PtrIndices;
776}
777
780 unsigned Depth) const {
781 unsigned N = 0;
782 auto PtrIndices = getPtrToIdxMap(CheckingGroups);
783 for (const auto &[Check1, Check2] : Checks) {
784 const auto &First = Check1->Members, &Second = Check2->Members;
785 OS.indent(Depth) << "Check " << N++ << ":\n";
786 OS.indent(Depth + 2) << "Comparing group GRP" << PtrIndices.at(Check1)
787 << ":\n";
788 for (unsigned K : First)
789 OS.indent(Depth + 2) << *Pointers[K].PointerValue << "\n";
790 OS.indent(Depth + 2) << "Against group GRP" << PtrIndices.at(Check2)
791 << ":\n";
792 for (unsigned K : Second)
793 OS.indent(Depth + 2) << *Pointers[K].PointerValue << "\n";
794 }
795}
796
798
799 OS.indent(Depth) << "Run-time memory checks:\n";
800 printChecks(OS, Checks, Depth);
801
802 OS.indent(Depth) << "Grouped accesses:\n";
803 auto PtrIndices = getPtrToIdxMap(CheckingGroups);
804 for (const auto &CG : CheckingGroups) {
805 OS.indent(Depth + 2) << "Group GRP" << PtrIndices.at(&CG) << ":\n";
806 OS.indent(Depth + 4) << "(Low: " << *CG.Low << " High: " << *CG.High
807 << ")\n";
808 for (unsigned Member : CG.Members) {
809 OS.indent(Depth + 6) << "Member: " << *Pointers[Member].Expr << "\n";
810 }
811 }
812}
813
814namespace {
815
816/// Analyses memory accesses in a loop.
817///
818/// Checks whether run time pointer checks are needed and builds sets for data
819/// dependence checking.
820class AccessAnalysis {
821public:
822 using MemAccessInfo =
823 PointerIntPair<Value * /* AccessPtr */, 1, bool /* IsWrite */>;
824
825 AccessAnalysis(const Loop *TheLoop, AAResults *AA, const LoopInfo *LI,
828 SmallPtrSetImpl<MDNode *> &LoopAliasScopes)
829 : TheLoop(TheLoop), BAA(*AA), AST(BAA), LI(LI), DT(DT), DepCands(DA),
830 PSE(PSE), LoopAliasScopes(LoopAliasScopes) {
831 // We're analyzing dependences across loop iterations.
832 BAA.enableCrossIterationMode();
833 }
834
835 /// Register a load and whether it is only read from.
836 void addLoad(const MemoryLocation &Loc, Type *AccessTy, bool IsReadOnly) {
837 Value *Ptr = const_cast<Value *>(Loc.Ptr);
838 AST.add(adjustLoc(Loc));
839 Accesses[MemAccessInfo(Ptr, false)].insert(AccessTy);
840 if (IsReadOnly)
841 ReadOnlyPtr.insert(Ptr);
842 }
843
844 /// Register a store.
845 void addStore(const MemoryLocation &Loc, Type *AccessTy) {
846 Value *Ptr = const_cast<Value *>(Loc.Ptr);
847 AST.add(adjustLoc(Loc));
848 Accesses[MemAccessInfo(Ptr, true)].insert(AccessTy);
849 }
850
851 /// Check if we can emit a run-time no-alias check for \p Access.
852 ///
853 /// Returns true if we can emit a run-time no alias check for \p Access.
854 /// If we can check this access, this also adds it to a dependence set and
855 /// adds a run-time to check for it to \p RtCheck. If \p Assume is true,
856 /// we will attempt to use additional run-time checks in order to get
857 /// the bounds of the pointer.
858 bool createCheckForAccess(RuntimePointerChecking &RtCheck,
859 MemAccessInfo Access, Type *AccessTy,
860 const SymbolicStrideMap &Strides,
861 DenseMap<Value *, unsigned> &DepSetId,
862 Loop *TheLoop, unsigned &RunningDepId,
863 unsigned ASId, bool Assume);
864
865 /// Check whether we can check the pointers at runtime for
866 /// non-intersection.
867 ///
868 /// Returns true if we need no check or if we do and we can generate them
869 /// (i.e. the pointers have computable bounds). A return value of false means
870 /// we couldn't analyze and generate runtime checks for all pointers in the
871 /// loop, but if \p AllowPartial is set then we will have checks for those
872 /// pointers we could analyze. \p DepChecker is used to remove unknown
873 /// dependences from DepCands.
874 bool canCheckPtrAtRT(RuntimePointerChecking &RtCheck, Loop *TheLoop,
875 const SymbolicStrideMap &Strides,
876 Value *&UncomputablePtr, bool AllowPartial,
877 const MemoryDepChecker &DepChecker);
878
879 /// Goes over all memory accesses, checks whether a RT check is needed
880 /// and builds sets of dependent accesses.
881 void buildDependenceSets();
882
883 /// Initial processing of memory accesses determined that we need to
884 /// perform dependency checking.
885 ///
886 /// Note that this can later be cleared if we retry memcheck analysis without
887 /// dependency checking (i.e. ShouldRetryWithRuntimeChecks).
888 bool isDependencyCheckNeeded() const { return !CheckDeps.empty(); }
889
890 /// We decided that no dependence analysis would be used. Reset the state.
891 void resetDepChecks(MemoryDepChecker &DepChecker) {
892 CheckDeps.clear();
893 DepChecker.clearDependences();
894 }
895
896 ArrayRef<MemAccessInfo> getDependenciesToCheck() const { return CheckDeps; }
897
898private:
899 using PtrAccessMap = MapVector<MemAccessInfo, SmallSetVector<Type *, 1>>;
900
901 /// Adjust the MemoryLocation so that it represents accesses to this
902 /// location across all iterations, rather than a single one.
903 MemoryLocation adjustLoc(MemoryLocation Loc) const {
904 // The accessed location varies within the loop, but remains within the
905 // underlying object.
907 Loc.AATags.Scope = adjustAliasScopeList(Loc.AATags.Scope);
908 Loc.AATags.NoAlias = adjustAliasScopeList(Loc.AATags.NoAlias);
909 return Loc;
910 }
911
912 /// Drop alias scopes that are only valid within a single loop iteration.
913 MDNode *adjustAliasScopeList(MDNode *ScopeList) const {
914 if (!ScopeList)
915 return nullptr;
916
917 // For the sake of simplicity, drop the whole scope list if any scope is
918 // iteration-local.
919 if (any_of(ScopeList->operands(), [&](Metadata *Scope) {
920 return LoopAliasScopes.contains(cast<MDNode>(Scope));
921 }))
922 return nullptr;
923
924 return ScopeList;
925 }
926
927 /// Map of all accesses. Values are the types used to access memory pointed to
928 /// by the pointer.
929 PtrAccessMap Accesses;
930
931 /// The loop being checked.
932 const Loop *TheLoop;
933
934 /// List of accesses that need a further dependence check.
936
937 /// Set of pointers that are read only.
938 SmallPtrSet<Value*, 16> ReadOnlyPtr;
939
940 /// Batched alias analysis results.
941 BatchAAResults BAA;
942
943 /// An alias set tracker to partition the access set by underlying object and
944 //intrinsic property (such as TBAA metadata).
945 AliasSetTracker AST;
946
947 /// The LoopInfo of the loop being checked.
948 const LoopInfo *LI;
949
950 /// The dominator tree of the function.
951 DominatorTree &DT;
952
953 /// Sets of potentially dependent accesses - members of one set share an
954 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
955 /// dependence check.
957
958 /// Initial processing of memory accesses determined that we may need
959 /// to add memchecks. Perform the analysis to determine the necessary checks.
960 ///
961 /// Note that, this is different from isDependencyCheckNeeded. When we retry
962 /// memcheck analysis without dependency checking
963 /// (i.e. ShouldRetryWithRuntimeChecks), isDependencyCheckNeeded is
964 /// cleared while this remains set if we have potentially dependent accesses.
965 bool IsRTCheckAnalysisNeeded = false;
966
967 /// The SCEV predicate containing all the SCEV-related assumptions.
968 PredicatedScalarEvolution &PSE;
969
970 DenseMap<Value *, SmallVector<const Value *, 16>> UnderlyingObjects;
971
972 /// Alias scopes that are declared inside the loop, and as such not valid
973 /// across iterations.
974 SmallPtrSetImpl<MDNode *> &LoopAliasScopes;
975};
976
977} // end anonymous namespace
978
979std::optional<int64_t>
981 Type *AccessTy, Value *Ptr,
983 if (isa<ScalableVectorType>(AccessTy)) {
984 LLVM_DEBUG(dbgs() << "LAA: Bad stride - Scalable object: " << *AccessTy
985 << "\n");
986 return std::nullopt;
987 }
988
989 // The access function must stride over the innermost loop.
990 if (Lp != AR->getLoop()) {
991 LLVM_DEBUG({
992 dbgs() << "LAA: Bad stride - Not striding over innermost loop ";
993 if (Ptr)
994 dbgs() << *Ptr << " ";
995
996 dbgs() << "SCEV: " << *AR << "\n";
997 });
998 return std::nullopt;
999 }
1000
1001 // Check the step is constant.
1002 const SCEV *Step = AR->getStepRecurrence(*PSE.getSE());
1003
1004 // Calculate the pointer stride and check if it is constant.
1005 const APInt *APStepVal;
1006 if (!match(Step, m_scev_APInt(APStepVal))) {
1007 LLVM_DEBUG({
1008 dbgs() << "LAA: Bad stride - Not a constant strided ";
1009 if (Ptr)
1010 dbgs() << *Ptr << " ";
1011 dbgs() << "SCEV: " << *AR << "\n";
1012 });
1013 return std::nullopt;
1014 }
1015
1016 const auto &DL = Lp->getHeader()->getDataLayout();
1017 TypeSize AllocSize = DL.getTypeAllocSize(AccessTy);
1018 int64_t Size = AllocSize.getFixedValue();
1019
1020 // Huge step value - give up.
1021 std::optional<int64_t> StepVal = APStepVal->trySExtValue();
1022 if (!StepVal)
1023 return std::nullopt;
1024
1025 // Strided access.
1026 return *StepVal % Size ? std::nullopt : std::make_optional(*StepVal / Size);
1027}
1028
1029/// Check whether \p AR is a non-wrapping AddRec. If \p Ptr is not nullptr, use
1030/// information from the IR pointer value to determine no-wrap. If \p Predicates
1031/// is not nullptr add no-wrap assumptions if needed.
1032static bool
1034 Type *AccessTy, const Loop *L, const DominatorTree &DT,
1035 std::optional<int64_t> Stride = std::nullopt,
1036 SmallVectorImpl<const SCEVPredicate *> *Predicates = nullptr) {
1037 // FIXME: This should probably only return true for NUW.
1038 if (any(AR->getNoWrapFlags(SCEV::NoWrapMask)))
1039 return true;
1040
1042 return true;
1043
1044 // An nusw getelementptr that is an AddRec cannot wrap. If it would wrap,
1045 // the distance between the previously accessed location and the wrapped
1046 // location will be larger than half the pointer index type space. In that
1047 // case, the GEP would be poison and any memory access dependent on it would
1048 // be immediate UB when executed.
1050 GEP && GEP->hasNoUnsignedSignedWrap()) {
1051 // For the above reasoning to apply, the pointer must be dereferenced in
1052 // every iteration.
1053 if (L->getHeader() == L->getLoopLatch() ||
1054 any_of(GEP->users(), [L, &DT, GEP](User *U) {
1055 if (getLoadStorePointerOperand(U) != GEP)
1056 return false;
1057 BasicBlock *UserBB = cast<Instruction>(U)->getParent();
1058 if (!L->contains(UserBB))
1059 return false;
1060 return !LoopAccessInfo::blockNeedsPredication(UserBB, L, &DT);
1061 }))
1062 return true;
1063 }
1064
1065 if (!Stride)
1066 Stride = getStrideFromAddRec(AR, L, AccessTy, Ptr, PSE);
1067 if (Stride) {
1068 // If the null pointer is undefined, then a access sequence which would
1069 // otherwise access it can be assumed not to unsigned wrap. Note that this
1070 // assumes the object in memory is aligned to the natural alignment.
1071 unsigned AddrSpace = AR->getType()->getPointerAddressSpace();
1072 if (!NullPointerIsDefined(L->getHeader()->getParent(), AddrSpace) &&
1073 (Stride == 1 || Stride == -1))
1074 return true;
1075 }
1076
1077 if (Ptr && Predicates) {
1078 ScalarEvolution &SE = *PSE.getSE();
1082 Predicates->push_back(SE.getWrapPredicate(AR, Flags));
1083 LLVM_DEBUG(dbgs() << "LAA: Pointer may wrap:\n"
1084 << "LAA: Pointer: " << *Ptr << "\n"
1085 << "LAA: SCEV: " << *AR << "\n"
1086 << "LAA: Added an overflow assumption\n");
1087 return true;
1088 }
1089
1090 return false;
1091}
1092
1093static void visitPointers(Value *StartPtr, const Loop &InnermostLoop,
1094 function_ref<void(Value *)> AddPointer) {
1096 SmallVector<Value *> WorkList;
1097 WorkList.push_back(StartPtr);
1098
1099 while (!WorkList.empty()) {
1100 Value *Ptr = WorkList.pop_back_val();
1101 if (!Visited.insert(Ptr).second)
1102 continue;
1103 auto *PN = dyn_cast<PHINode>(Ptr);
1104 // SCEV does not look through non-header PHIs inside the loop. Such phis
1105 // can be analyzed by adding separate accesses for each incoming pointer
1106 // value.
1107 if (PN && InnermostLoop.contains(PN->getParent()) &&
1108 PN->getParent() != InnermostLoop.getHeader()) {
1109 llvm::append_range(WorkList, PN->incoming_values());
1110 } else
1111 AddPointer(Ptr);
1112 }
1113}
1114
1115// Walk back through the IR for a pointer, looking for a select like the
1116// following:
1117//
1118// %offset = select i1 %cmp, i64 %a, i64 %b
1119// %addr = getelementptr double, double* %base, i64 %offset
1120// %ld = load double, double* %addr, align 8
1121//
1122// We won't be able to form a single SCEVAddRecExpr from this since the
1123// address for each loop iteration depends on %cmp. We could potentially
1124// produce multiple valid SCEVAddRecExprs, though, and check all of them for
1125// memory safety/aliasing if needed.
1126//
1127// If we encounter some IR we don't yet handle, or something obviously fine
1128// like a constant, then we just add the SCEV for that term to the list passed
1129// in by the caller. If we have a node that may potentially yield a valid
1130// SCEVAddRecExpr then we decompose it into parts and build the SCEV terms
1131// ourselves before adding to the list.
1133 ScalarEvolution *SE, const Loop *L, Value *Ptr,
1135 unsigned Depth) {
1136 // If our Value is a SCEVAddRecExpr, loop invariant, not an instruction, or
1137 // we've exceeded our limit on recursion, just return whatever we have
1138 // regardless of whether it can be used for a forked pointer or not, along
1139 // with an indication of whether it might be a poison or undef value.
1140 const SCEV *Scev = SE->getSCEV(Ptr);
1141 if (isa<SCEVAddRecExpr>(Scev) || L->isLoopInvariant(Ptr) ||
1142 !isa<Instruction>(Ptr) || Depth == 0) {
1143 ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr));
1144 return;
1145 }
1146
1147 Depth--;
1148
1149 auto UndefPoisonCheck = [](PointerIntPair<const SCEV *, 1, bool> S) {
1150 return get<1>(S);
1151 };
1152
1153 auto GetBinOpExpr = [&SE](unsigned Opcode, const SCEV *L, const SCEV *R) {
1154 switch (Opcode) {
1155 case Instruction::Add:
1156 return SE->getAddExpr(L, R);
1157 case Instruction::Sub:
1158 return SE->getMinusSCEV(L, R);
1159 default:
1160 llvm_unreachable("Unexpected binary operator when walking ForkedPtrs");
1161 }
1162 };
1163
1165 unsigned Opcode = I->getOpcode();
1166 switch (Opcode) {
1167 case Instruction::GetElementPtr: {
1168 auto *GEP = cast<GetElementPtrInst>(I);
1169 Type *SourceTy = GEP->getSourceElementType();
1170 // We only handle base + single offset GEPs here for now.
1171 // Not dealing with preexisting gathers yet, so no vectors.
1172 if (I->getNumOperands() != 2 || SourceTy->isVectorTy()) {
1173 ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(GEP));
1174 break;
1175 }
1178 findForkedSCEVs(SE, L, I->getOperand(0), BaseScevs, Depth);
1179 findForkedSCEVs(SE, L, I->getOperand(1), OffsetScevs, Depth);
1180
1181 // See if we need to freeze our fork...
1182 bool NeedsFreeze = any_of(BaseScevs, UndefPoisonCheck) ||
1183 any_of(OffsetScevs, UndefPoisonCheck);
1184
1185 // Check that we only have a single fork, on either the base or the offset.
1186 // Copy the SCEV across for the one without a fork in order to generate
1187 // the full SCEV for both sides of the GEP.
1188 if (OffsetScevs.size() == 2 && BaseScevs.size() == 1)
1189 BaseScevs.push_back(BaseScevs[0]);
1190 else if (BaseScevs.size() == 2 && OffsetScevs.size() == 1)
1191 OffsetScevs.push_back(OffsetScevs[0]);
1192 else {
1193 ScevList.emplace_back(Scev, NeedsFreeze);
1194 break;
1195 }
1196
1197 Type *IntPtrTy = SE->getEffectiveSCEVType(GEP->getPointerOperandType());
1198
1199 // Find the size of the type being pointed to. We only have a single
1200 // index term (guarded above) so we don't need to index into arrays or
1201 // structures, just get the size of the scalar value.
1202 const SCEV *Size = SE->getSizeOfExpr(IntPtrTy, SourceTy);
1203
1204 for (auto [B, O] : zip(BaseScevs, OffsetScevs)) {
1205 const SCEV *Base = get<0>(B);
1206 const SCEV *Offset = get<0>(O);
1207
1208 // Scale up the offsets by the size of the type, then add to the bases.
1209 const SCEV *Scaled =
1211 ScevList.emplace_back(SE->getAddExpr(Base, Scaled), NeedsFreeze);
1212 }
1213 break;
1214 }
1215 case Instruction::Select: {
1217 // A select means we've found a forked pointer, but we currently only
1218 // support a single select per pointer so if there's another behind this
1219 // then we just bail out and return the generic SCEV.
1220 findForkedSCEVs(SE, L, I->getOperand(1), ChildScevs, Depth);
1221 findForkedSCEVs(SE, L, I->getOperand(2), ChildScevs, Depth);
1222 if (ChildScevs.size() == 2)
1223 append_range(ScevList, ChildScevs);
1224 else
1225 ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr));
1226 break;
1227 }
1228 case Instruction::PHI: {
1230 // A phi means we've found a forked pointer, but we currently only
1231 // support a single phi per pointer so if there's another behind this
1232 // then we just bail out and return the generic SCEV.
1233 if (I->getNumOperands() == 2) {
1234 findForkedSCEVs(SE, L, I->getOperand(0), ChildScevs, Depth);
1235 findForkedSCEVs(SE, L, I->getOperand(1), ChildScevs, Depth);
1236 }
1237 if (ChildScevs.size() == 2)
1238 append_range(ScevList, ChildScevs);
1239 else
1240 ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr));
1241 break;
1242 }
1243 case Instruction::Add:
1244 case Instruction::Sub: {
1247 findForkedSCEVs(SE, L, I->getOperand(0), LScevs, Depth);
1248 findForkedSCEVs(SE, L, I->getOperand(1), RScevs, Depth);
1249
1250 // See if we need to freeze our fork...
1251 bool NeedsFreeze =
1252 any_of(LScevs, UndefPoisonCheck) || any_of(RScevs, UndefPoisonCheck);
1253
1254 // Check that we only have a single fork, on either the left or right side.
1255 // Copy the SCEV across for the one without a fork in order to generate
1256 // the full SCEV for both sides of the BinOp.
1257 if (LScevs.size() == 2 && RScevs.size() == 1)
1258 RScevs.push_back(RScevs[0]);
1259 else if (RScevs.size() == 2 && LScevs.size() == 1)
1260 LScevs.push_back(LScevs[0]);
1261 else {
1262 ScevList.emplace_back(Scev, NeedsFreeze);
1263 break;
1264 }
1265
1266 for (auto [L, R] : zip(LScevs, RScevs))
1267 ScevList.emplace_back(GetBinOpExpr(Opcode, get<0>(L), get<0>(R)),
1268 NeedsFreeze);
1269 break;
1270 }
1271 default:
1272 // Just return the current SCEV if we haven't handled the instruction yet.
1273 LLVM_DEBUG(dbgs() << "ForkedPtr unhandled instruction: " << *I << "\n");
1274 ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr));
1275 break;
1276 }
1277}
1278
1279bool AccessAnalysis::createCheckForAccess(RuntimePointerChecking &RtCheck,
1280 MemAccessInfo Access, Type *AccessTy,
1281 const SymbolicStrideMap &StridesMap,
1283 Loop *TheLoop, unsigned &RunningDepId,
1284 unsigned ASId, bool Assume) {
1285 Value *Ptr = Access.getPointer();
1286 ScalarEvolution *SE = PSE.getSE();
1287 assert(SE->isSCEVable(Ptr->getType()) && "Value is not SCEVable!");
1288
1290 findForkedSCEVs(SE, TheLoop, Ptr, RTCheckPtrs, MaxForkedSCEVDepth);
1291 assert(!RTCheckPtrs.empty() &&
1292 "Must have some runtime-check pointer candidates");
1293
1294 // RTCheckPtrs must have size 2 if there are forked pointers. Otherwise, there
1295 // are no forked pointers; replaceSymbolicStridesSCEV in this case.
1296 auto IsLoopInvariantOrAR =
1297 [&SE, &TheLoop](const PointerIntPair<const SCEV *, 1, bool> &P) {
1298 return SE->isLoopInvariant(P.getPointer(), TheLoop) ||
1299 isa<SCEVAddRecExpr>(P.getPointer());
1300 };
1301 if (RTCheckPtrs.size() == 2 && all_of(RTCheckPtrs, IsLoopInvariantOrAR)) {
1302 LLVM_DEBUG(dbgs() << "LAA: Found forked pointer: " << *Ptr << "\n";
1303 for (const auto &[Idx, Q] : enumerate(RTCheckPtrs)) dbgs()
1304 << "\t(" << Idx << ") " << *Q.getPointer() << "\n");
1305 } else {
1306 RTCheckPtrs = {{replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr), false}};
1307 }
1308
1309 /// Check whether all pointers can participate in a runtime bounds check. They
1310 /// must either be invariant or non-wrapping affine AddRecs.
1312 for (auto &P : RTCheckPtrs) {
1313 // The bounds for loop-invariant pointer is trivial.
1314 if (SE->isLoopInvariant(P.getPointer(), TheLoop))
1315 continue;
1316
1317 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(P.getPointer());
1318 if (!AR && Assume)
1319 AR = PSE.getAsAddRec(Ptr, &Predicates);
1320 if (!AR || !AR->isAffine())
1321 return false;
1322
1323 // If there's only one option for Ptr, commit the predicates collected by
1324 // getAsAddRec and look Ptr up again afterwards: the lookup below reads the
1325 // assumptions back from PSE, so they need to be committed first.
1326 if (RTCheckPtrs.size() == 1) {
1327 PSE.addPredicates(Predicates);
1328 Predicates.clear();
1329 if (auto *StrideAR = dyn_cast<SCEVAddRecExpr>(
1330 replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr)))
1331 AR = StrideAR;
1332 P.setPointer(AR);
1333 }
1334
1335 if (!isNoWrap(PSE, AR, RTCheckPtrs.size() == 1 ? Ptr : nullptr, AccessTy,
1336 TheLoop, DT, /*Stride=*/std::nullopt,
1337 Assume ? &Predicates : nullptr))
1338 return false;
1339 }
1340 PSE.addPredicates(Predicates);
1341
1342 for (const auto &[PtrExpr, NeedsFreeze] : RTCheckPtrs) {
1343 // The id of the dependence set.
1344 unsigned DepId;
1345
1346 if (DepCands.contains(Access)) {
1347 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
1348 unsigned &LeaderId = DepSetId[Leader];
1349 if (!LeaderId)
1350 LeaderId = RunningDepId++;
1351 DepId = LeaderId;
1352 } else
1353 // Each access has its own dependence set.
1354 DepId = RunningDepId++;
1355
1356 bool IsWrite = Access.getInt();
1357 RtCheck.insert(TheLoop, Ptr, PtrExpr, AccessTy, IsWrite, DepId, ASId, PSE,
1358 NeedsFreeze);
1359 LLVM_DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
1360 }
1361
1362 return true;
1363}
1364
1365bool AccessAnalysis::canCheckPtrAtRT(RuntimePointerChecking &RtCheck,
1366 Loop *TheLoop,
1367 const SymbolicStrideMap &StridesMap,
1368 Value *&UncomputablePtr, bool AllowPartial,
1369 const MemoryDepChecker &DepChecker) {
1370 // Find pointers with computable bounds. We are going to use this information
1371 // to place a runtime bound check.
1372 bool CanDoRT = true;
1373
1374 bool MayNeedRTCheck = false;
1375 if (!IsRTCheckAnalysisNeeded) return true;
1376
1377 if (auto *Deps = DepChecker.getDependences()) {
1378 // If there are unknown dependences, this means runtime checks are needed to
1379 // ensure there's no overlap between accesses to the same underlying object.
1380 // Remove the equivalence classes containing both source and destination
1381 // accesses from DepCands. This ensures runtime checks will be generated
1382 // between those accesses and prevents them from being grouped together.
1383 for (const auto &Dep : *Deps) {
1384 if (Dep.Type != MemoryDepChecker::Dependence::Unknown) {
1387 "Should only skip safe dependences");
1388 continue;
1389 }
1390 Instruction *Src = Dep.getSource(DepChecker);
1391 Instruction *Dst = Dep.getDestination(DepChecker);
1392 DepCands.eraseClass({getPointerOperand(Src), Src->mayWriteToMemory()});
1393 DepCands.eraseClass({getPointerOperand(Dst), Dst->mayWriteToMemory()});
1394 }
1395 } else {
1396 CheckDeps.clear();
1397 DepCands = {};
1398 }
1399
1400 // We assign a consecutive id to access from different alias sets.
1401 // Accesses between different groups doesn't need to be checked.
1402 unsigned ASId = 0;
1403 for (const auto &AS : AST) {
1404 int NumReadPtrChecks = 0;
1405 int NumWritePtrChecks = 0;
1406 bool CanDoAliasSetRT = true;
1407 ++ASId;
1408 auto ASPointers = AS.getPointers();
1409
1410 // We assign consecutive id to access from different dependence sets.
1411 // Accesses within the same set don't need a runtime check.
1412 unsigned RunningDepId = 1;
1414
1416
1417 // First, count how many write and read accesses are in the alias set. Also
1418 // collect MemAccessInfos for later.
1420 for (const Value *ConstPtr : ASPointers) {
1421 Value *Ptr = const_cast<Value *>(ConstPtr);
1422 bool IsWrite = Accesses.contains(MemAccessInfo(Ptr, true));
1423 if (IsWrite)
1424 ++NumWritePtrChecks;
1425 else
1426 ++NumReadPtrChecks;
1427 AccessInfos.emplace_back(Ptr, IsWrite);
1428 }
1429
1430 // We do not need runtime checks for this alias set, if there are no writes
1431 // or a single write and no reads.
1432 if (NumWritePtrChecks == 0 ||
1433 (NumWritePtrChecks == 1 && NumReadPtrChecks == 0)) {
1434 assert((ASPointers.size() <= 1 ||
1435 all_of(ASPointers,
1436 [this](const Value *Ptr) {
1437 MemAccessInfo AccessWrite(const_cast<Value *>(Ptr),
1438 true);
1439 return !DepCands.contains(AccessWrite);
1440 })) &&
1441 "Can only skip updating CanDoRT below, if all entries in AS "
1442 "are reads or there is at most 1 entry");
1443 continue;
1444 }
1445
1446 for (auto &Access : AccessInfos) {
1447 for (const auto &AccessTy : Accesses[Access]) {
1448 if (!createCheckForAccess(RtCheck, Access, AccessTy, StridesMap,
1449 DepSetId, TheLoop, RunningDepId, ASId,
1450 false)) {
1451 LLVM_DEBUG(dbgs() << "LAA: Can't find bounds for ptr:"
1452 << *Access.getPointer() << '\n');
1453 Retries.emplace_back(Access, AccessTy);
1454 CanDoAliasSetRT = false;
1455 }
1456 }
1457 }
1458
1459 // Note that this function computes CanDoRT and MayNeedRTCheck
1460 // independently. For example CanDoRT=false, MayNeedRTCheck=false means that
1461 // we have a pointer for which we couldn't find the bounds but we don't
1462 // actually need to emit any checks so it does not matter.
1463 //
1464 // We need runtime checks for this alias set, if there are at least 2
1465 // dependence sets (in which case RunningDepId > 2) or if we need to re-try
1466 // any bound checks (because in that case the number of dependence sets is
1467 // incomplete).
1468 bool NeedsAliasSetRTCheck = RunningDepId > 2 || !Retries.empty();
1469
1470 // We need to perform run-time alias checks, but some pointers had bounds
1471 // that couldn't be checked.
1472 if (NeedsAliasSetRTCheck && !CanDoAliasSetRT) {
1473 // Reset the CanDoSetRt flag and retry all accesses that have failed.
1474 // We know that we need these checks, so we can now be more aggressive
1475 // and add further checks if required (overflow checks).
1476 CanDoAliasSetRT = true;
1477 for (const auto &[Access, AccessTy] : Retries) {
1478 if (!createCheckForAccess(RtCheck, Access, AccessTy, StridesMap,
1479 DepSetId, TheLoop, RunningDepId, ASId,
1480 /*Assume=*/true)) {
1481 CanDoAliasSetRT = false;
1482 UncomputablePtr = Access.getPointer();
1483 if (!AllowPartial)
1484 break;
1485 }
1486 }
1487 }
1488
1489 CanDoRT &= CanDoAliasSetRT;
1490 MayNeedRTCheck |= NeedsAliasSetRTCheck;
1491 ++ASId;
1492 }
1493
1494 // If the pointers that we would use for the bounds comparison have different
1495 // address spaces, assume the values aren't directly comparable, so we can't
1496 // use them for the runtime check. We also have to assume they could
1497 // overlap. In the future there should be metadata for whether address spaces
1498 // are disjoint.
1499 unsigned NumPointers = RtCheck.Pointers.size();
1500 for (unsigned i = 0; i < NumPointers; ++i) {
1501 for (unsigned j = i + 1; j < NumPointers; ++j) {
1502 // Only need to check pointers between two different dependency sets.
1503 if (RtCheck.Pointers[i].DependencySetId ==
1504 RtCheck.Pointers[j].DependencySetId)
1505 continue;
1506 // Only need to check pointers in the same alias set.
1507 if (RtCheck.Pointers[i].AliasSetId != RtCheck.Pointers[j].AliasSetId)
1508 continue;
1509
1510 Value *PtrI = RtCheck.Pointers[i].PointerValue;
1511 Value *PtrJ = RtCheck.Pointers[j].PointerValue;
1512
1513 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
1514 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
1515 if (ASi != ASj) {
1516 LLVM_DEBUG(
1517 dbgs() << "LAA: Runtime check would require comparison between"
1518 " different address spaces\n");
1519 return false;
1520 }
1521 }
1522 }
1523
1524 if (MayNeedRTCheck && (CanDoRT || AllowPartial))
1525 RtCheck.generateChecks(DepCands);
1526
1527 LLVM_DEBUG(dbgs() << "LAA: We need to do " << RtCheck.getNumberOfChecks()
1528 << " pointer comparisons.\n");
1529
1530 // If we can do run-time checks, but there are no checks, no runtime checks
1531 // are needed. This can happen when all pointers point to the same underlying
1532 // object for example.
1533 RtCheck.Need = CanDoRT ? RtCheck.getNumberOfChecks() != 0 : MayNeedRTCheck;
1534
1535 bool CanDoRTIfNeeded = !RtCheck.Need || CanDoRT;
1536 assert(CanDoRTIfNeeded == (CanDoRT || !MayNeedRTCheck) &&
1537 "CanDoRTIfNeeded depends on RtCheck.Need");
1538 if (!CanDoRTIfNeeded && !AllowPartial)
1539 RtCheck.reset();
1540 return CanDoRTIfNeeded;
1541}
1542
1543void AccessAnalysis::buildDependenceSets() {
1544 // We process the set twice: first we process read-write pointers, last we
1545 // process read-only pointers. This allows us to skip dependence tests for
1546 // read-only pointers.
1547
1548 LLVM_DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
1549 LLVM_DEBUG(dbgs() << " AST: "; AST.dump());
1550 LLVM_DEBUG(dbgs() << "LAA: Accesses(" << Accesses.size() << "):\n");
1551 LLVM_DEBUG({
1552 for (const auto &[A, _] : Accesses)
1553 dbgs() << "\t" << *A.getPointer() << " ("
1554 << (A.getInt()
1555 ? "write"
1556 : (ReadOnlyPtr.contains(A.getPointer()) ? "read-only"
1557 : "read"))
1558 << ")\n";
1559 });
1560
1561 // The AliasSetTracker has nicely partitioned our pointers by metadata
1562 // compatibility and potential for underlying-object overlap. As a result, we
1563 // only need to check for potential pointer dependencies within each alias
1564 // set.
1565 for (const auto &AS : AST) {
1566 bool AliasSetHasWrite = false;
1567
1568 // Map of (pointer to underlying objects, accessed address space) to last
1569 // access encountered.
1570 using UnderlyingObjToAccessMap =
1572 UnderlyingObjToAccessMap ObjToLastAccess;
1573
1574 // Set of access to check after all writes have been processed.
1575 PtrAccessMap DeferredAccesses;
1576
1577 // Iterate over each alias set twice, once to process read/write pointers,
1578 // and then to process read-only pointers.
1579
1580 auto ProcessAccesses = [&](bool UseDeferred) {
1581 PtrAccessMap &S = UseDeferred ? DeferredAccesses : Accesses;
1582
1583 // Note that both the alias-set tracker and the alias sets themselves used
1584 // ordered collections internally and so the iteration order here is
1585 // deterministic.
1586 for (const Value *ConstPtr : AS.getPointers()) {
1587 Value *Ptr = const_cast<Value *>(ConstPtr);
1588
1589 // For a single memory access in AliasSetTracker, Accesses may contain
1590 // both read and write, and they both need to be handled for CheckDeps.
1591 for (auto [AccessPtr, IsWrite] : S.keys()) {
1592 if (AccessPtr != Ptr)
1593 continue;
1594
1595 // If we're using the deferred access set, then it contains only
1596 // reads.
1597 bool IsReadOnlyPtr = ReadOnlyPtr.contains(Ptr) && !IsWrite;
1598 if (UseDeferred && !IsReadOnlyPtr)
1599 continue;
1600 // Otherwise, the pointer must be in the PtrAccessSet, either as a
1601 // read or a write.
1602 assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
1603 S.contains(MemAccessInfo(Ptr, false))) &&
1604 "Alias-set pointer not in the access set?");
1605
1606 MemAccessInfo Access(Ptr, IsWrite);
1607 DepCands.insert(Access);
1608
1609 // Memorize read-only pointers for later processing and skip them in
1610 // the first round (they need to be checked after we have seen all
1611 // write pointers). Note: we also mark pointer that are not
1612 // consecutive as "read-only" pointers (so that we check
1613 // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
1614 if (!UseDeferred && IsReadOnlyPtr) {
1615 // We only use the pointer keys, the types vector values don't
1616 // matter.
1617 DeferredAccesses.insert({Access, {}});
1618 continue;
1619 }
1620
1621 // If this is a write - check other reads and writes for conflicts. If
1622 // this is a read only check other writes for conflicts (but only if
1623 // there is no other write to the ptr - this is an optimization to
1624 // catch "a[i] = a[i] + " without having to do a dependence check).
1625 if ((IsWrite || IsReadOnlyPtr) && AliasSetHasWrite) {
1626 CheckDeps.push_back(Access);
1627 IsRTCheckAnalysisNeeded = true;
1628 }
1629
1630 if (IsWrite)
1631 AliasSetHasWrite = true;
1632
1633 // Create sets of pointers connected by a shared alias set and
1634 // underlying object.
1635 SmallVector<const Value *, 16> &UOs = UnderlyingObjects[Ptr];
1636 UOs = {};
1637 ::getUnderlyingObjects(Ptr, UOs, LI);
1639 << "Underlying objects for pointer " << *Ptr << "\n");
1640 for (const Value *UnderlyingObj : UOs) {
1641 // nullptr never alias, don't join sets for pointer that have "null"
1642 // in their UnderlyingObjects list.
1643 if (isa<ConstantPointerNull>(UnderlyingObj) &&
1645 TheLoop->getHeader()->getParent(),
1646 UnderlyingObj->getType()->getPointerAddressSpace()))
1647 continue;
1648
1649 auto [It, Inserted] = ObjToLastAccess.try_emplace(
1650 {UnderlyingObj,
1651 cast<PointerType>(Ptr->getType())->getAddressSpace()},
1652 Access);
1653 if (!Inserted) {
1654 DepCands.unionSets(Access, It->second);
1655 It->second = Access;
1656 }
1657
1658 LLVM_DEBUG(dbgs() << " " << *UnderlyingObj << "\n");
1659 }
1660 }
1661 }
1662 };
1663
1664 ProcessAccesses(false);
1665 ProcessAccesses(true);
1666 }
1667}
1668
1669/// Check whether the access through \p Ptr has a constant stride.
1670std::optional<int64_t>
1672 const Loop *Lp, const DominatorTree &DT,
1673 const SymbolicStrideMap &StridesMap, bool ShouldCheckWrap,
1675 const SCEV *PtrScev = replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr);
1676 if (PSE.getSE()->isLoopInvariant(PtrScev, Lp))
1677 return 0;
1678
1679 assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
1680
1681 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
1682 if (Predicates && !AR) {
1683 AR = PSE.getSE()->convertSCEVToAddRecWithPredicates(PtrScev, Lp,
1684 *Predicates);
1685 }
1686
1687 if (!AR) {
1688 LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer " << *Ptr
1689 << " SCEV: " << *PtrScev << "\n");
1690 return std::nullopt;
1691 }
1692
1693 std::optional<int64_t> Stride =
1694 getStrideFromAddRec(AR, Lp, AccessTy, Ptr, PSE);
1695 if (!ShouldCheckWrap || !Stride)
1696 return Stride;
1697
1698 if (isNoWrap(PSE, AR, Ptr, AccessTy, Lp, DT, Stride, Predicates))
1699 return Stride;
1700
1701 LLVM_DEBUG(
1702 dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
1703 << *Ptr << " SCEV: " << *AR << "\n");
1704 return std::nullopt;
1705}
1706
1707/// Check whether the access through \p Ptr has a constant stride.
1709 Type *AccessTy, Value *Ptr,
1710 const Loop *Lp,
1711 const DominatorTree &DT,
1712 const SymbolicStrideMap &StridesMap,
1713 bool Assume, bool ShouldCheckWrap) {
1715 std::optional<int64_t> Stride =
1716 getPtrStride(PSE, AccessTy, Ptr, Lp, DT, StridesMap, ShouldCheckWrap,
1717 Assume ? &Predicates : nullptr);
1718 PSE.addPredicates(Predicates);
1719 return Stride;
1720}
1721
1722std::optional<int64_t> llvm::getPointersDiff(Type *ElemTyA, Value *PtrA,
1723 Type *ElemTyB, Value *PtrB,
1724 const DataLayout &DL,
1725 ScalarEvolution &SE,
1726 bool StrictCheck, bool CheckType) {
1727 assert(PtrA && PtrB && "Expected non-nullptr pointers.");
1728
1729 // Make sure that A and B are different pointers.
1730 if (PtrA == PtrB)
1731 return 0;
1732
1733 // Make sure that the element types are the same if required.
1734 if (CheckType && ElemTyA != ElemTyB)
1735 return std::nullopt;
1736
1737 unsigned ASA = PtrA->getType()->getPointerAddressSpace();
1738 unsigned ASB = PtrB->getType()->getPointerAddressSpace();
1739
1740 // Check that the address spaces match.
1741 if (ASA != ASB)
1742 return std::nullopt;
1743 unsigned IdxWidth = DL.getIndexSizeInBits(ASA);
1744
1745 APInt OffsetA(IdxWidth, 0), OffsetB(IdxWidth, 0);
1746 const Value *PtrA1 = PtrA->stripAndAccumulateConstantOffsets(
1747 DL, OffsetA, /*AllowNonInbounds=*/true);
1748 const Value *PtrB1 = PtrB->stripAndAccumulateConstantOffsets(
1749 DL, OffsetB, /*AllowNonInbounds=*/true);
1750
1751 std::optional<int64_t> Val;
1752 if (PtrA1 == PtrB1) {
1753 // Retrieve the address space again as pointer stripping now tracks through
1754 // `addrspacecast`.
1755 ASA = cast<PointerType>(PtrA1->getType())->getAddressSpace();
1756 ASB = cast<PointerType>(PtrB1->getType())->getAddressSpace();
1757 // Check that the address spaces match and that the pointers are valid.
1758 if (ASA != ASB)
1759 return std::nullopt;
1760
1761 IdxWidth = DL.getIndexSizeInBits(ASA);
1762 OffsetA = OffsetA.sextOrTrunc(IdxWidth);
1763 OffsetB = OffsetB.sextOrTrunc(IdxWidth);
1764
1765 OffsetB -= OffsetA;
1766 Val = OffsetB.trySExtValue();
1767 } else {
1768 // Otherwise compute the distance with SCEV between the base pointers.
1769 const SCEV *PtrSCEVA = SE.getSCEV(PtrA);
1770 const SCEV *PtrSCEVB = SE.getSCEV(PtrB);
1771 std::optional<APInt> Diff =
1772 SE.computeConstantDifference(PtrSCEVB, PtrSCEVA);
1773 if (!Diff)
1774 return std::nullopt;
1775 Val = Diff->trySExtValue();
1776 }
1777
1778 if (!Val)
1779 return std::nullopt;
1780
1781 int64_t Size = DL.getTypeStoreSize(ElemTyA);
1782 int64_t Dist = *Val / Size;
1783
1784 // Ensure that the calculated distance matches the type-based one after all
1785 // the bitcasts removal in the provided pointers.
1786 if (!StrictCheck || Dist * Size == Val)
1787 return Dist;
1788 return std::nullopt;
1789}
1790
1792 const DataLayout &DL, ScalarEvolution &SE,
1793 SmallVectorImpl<unsigned> &SortedIndices) {
1795 VL, [](const Value *V) { return V->getType()->isPointerTy(); }) &&
1796 "Expected list of pointer operands.");
1797 // Walk over the pointers, and map each of them to an offset relative to
1798 // first pointer in the array.
1799 Value *Ptr0 = VL[0];
1800
1801 using DistOrdPair = std::pair<int64_t, unsigned>;
1802 auto Compare = llvm::less_first();
1803 std::set<DistOrdPair, decltype(Compare)> Offsets(Compare);
1804 Offsets.emplace(0, 0);
1805 bool IsConsecutive = true;
1806 for (auto [Idx, Ptr] : drop_begin(enumerate(VL))) {
1807 std::optional<int64_t> Diff =
1808 getPointersDiff(ElemTy, Ptr0, ElemTy, Ptr, DL, SE,
1809 /*StrictCheck=*/true);
1810 if (!Diff)
1811 return false;
1812
1813 // Check if the pointer with the same offset is found.
1814 int64_t Offset = *Diff;
1815 auto [It, IsInserted] = Offsets.emplace(Offset, Idx);
1816 if (!IsInserted)
1817 return false;
1818 // Consecutive order if the inserted element is the last one.
1819 IsConsecutive &= std::next(It) == Offsets.end();
1820 }
1821 SortedIndices.clear();
1822 if (!IsConsecutive) {
1823 // Fill SortedIndices array only if it is non-consecutive.
1824 SortedIndices.resize(VL.size());
1825 for (auto [Idx, Off] : enumerate(Offsets))
1826 SortedIndices[Idx] = Off.second;
1827 }
1828 return true;
1829}
1830
1831/// Returns true if the memory operations \p A and \p B are consecutive.
1833 ScalarEvolution &SE, bool CheckType) {
1836 if (!PtrA || !PtrB)
1837 return false;
1838 Type *ElemTyA = getLoadStoreType(A);
1839 Type *ElemTyB = getLoadStoreType(B);
1840 std::optional<int64_t> Diff =
1841 getPointersDiff(ElemTyA, PtrA, ElemTyB, PtrB, DL, SE,
1842 /*StrictCheck=*/true, CheckType);
1843 return Diff == 1;
1844}
1845
1847 visitPointers(SI->getPointerOperand(), *InnermostLoop,
1848 [this, SI](Value *Ptr) {
1849 Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
1850 InstMap.push_back(SI);
1851 ++AccessIdx;
1852 });
1853}
1854
1856 visitPointers(LI->getPointerOperand(), *InnermostLoop,
1857 [this, LI](Value *Ptr) {
1858 Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
1859 InstMap.push_back(LI);
1860 ++AccessIdx;
1861 });
1862}
1863
1883
1885 switch (Type) {
1886 case NoDep:
1887 case Forward:
1889 case Unknown:
1890 case IndirectUnsafe:
1891 case InvariantUnsafe:
1892 return false;
1893
1895 case Backward:
1897 return true;
1898 }
1899 llvm_unreachable("unexpected DepType!");
1900}
1901
1906
1908 switch (Type) {
1909 case Forward:
1911 return true;
1912
1913 case NoDep:
1914 case Unknown:
1916 case Backward:
1918 case IndirectUnsafe:
1919 case InvariantUnsafe:
1920 return false;
1921 }
1922 llvm_unreachable("unexpected DepType!");
1923}
1924
1925bool MemoryDepChecker::couldPreventStoreLoadForward(uint64_t Distance,
1926 uint64_t TypeByteSize,
1927 unsigned CommonStride) {
1928 // If loads occur at a distance that is not a multiple of a feasible vector
1929 // factor store-load forwarding does not take place.
1930 // Positive dependences might cause troubles because vectorizing them might
1931 // prevent store-load forwarding making vectorized code run a lot slower.
1932 // a[i] = a[i-3] ^ a[i-8];
1933 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
1934 // hence on your typical architecture store-load forwarding does not take
1935 // place. Vectorizing in such cases does not make sense.
1936 // Store-load forwarding distance.
1937
1938 // After this many iterations store-to-load forwarding conflicts should not
1939 // cause any slowdowns.
1940 const uint64_t NumItersForStoreLoadThroughMemory = 8 * TypeByteSize;
1941 // Maximum vector factor.
1942 uint64_t MaxVFWithoutSLForwardIssuesPowerOf2 =
1943 std::min(VectorizerParams::MaxVectorWidth * TypeByteSize,
1944 MaxStoreLoadForwardSafeDistanceInBits);
1945
1946 // Compute the smallest VF at which the store and load would be misaligned.
1947 for (uint64_t VF = 2 * TypeByteSize;
1948 VF <= MaxVFWithoutSLForwardIssuesPowerOf2; VF *= 2) {
1949 // If the number of vector iteration between the store and the load are
1950 // small we could incur conflicts.
1951 if (Distance % VF && Distance / VF < NumItersForStoreLoadThroughMemory) {
1952 MaxVFWithoutSLForwardIssuesPowerOf2 = (VF >> 1);
1953 break;
1954 }
1955 }
1956
1957 if (MaxVFWithoutSLForwardIssuesPowerOf2 < 2 * TypeByteSize) {
1958 LLVM_DEBUG(
1959 dbgs() << "LAA: Distance " << Distance
1960 << " that could cause a store-load forwarding conflict\n");
1961 return true;
1962 }
1963
1964 if (CommonStride &&
1965 MaxVFWithoutSLForwardIssuesPowerOf2 <
1966 MaxStoreLoadForwardSafeDistanceInBits &&
1967 MaxVFWithoutSLForwardIssuesPowerOf2 !=
1968 VectorizerParams::MaxVectorWidth * TypeByteSize) {
1969 uint64_t MaxVF =
1970 bit_floor(MaxVFWithoutSLForwardIssuesPowerOf2 / CommonStride);
1971 uint64_t MaxVFInBits = MaxVF * TypeByteSize * 8;
1972 MaxStoreLoadForwardSafeDistanceInBits =
1973 std::min(MaxStoreLoadForwardSafeDistanceInBits, MaxVFInBits);
1974
1975 if (MaxVF < 2) {
1976 LLVM_DEBUG(
1977 dbgs() << "LAA: strided access with Distance " << Distance
1978 << " that could cause a store-load forwarding conflict\n");
1979 return true;
1980 }
1981 }
1982 return false;
1983}
1984
1985void MemoryDepChecker::mergeInStatus(VectorizationSafetyStatus S) {
1986 if (Status < S)
1987 Status = S;
1988}
1989
1990/// Given a dependence-distance \p Dist between two memory accesses, that have
1991/// strides in the same direction whose absolute value of the maximum stride is
1992/// given in \p MaxStride, in a loop whose maximum backedge taken count is \p
1993/// MaxBTC, check if it is possible to prove statically that the dependence
1994/// distance is larger than the range that the accesses will travel through the
1995/// execution of the loop. If so, return true; false otherwise. This is useful
1996/// for example in loops such as the following (PR31098):
1997///
1998/// for (i = 0; i < D; ++i) {
1999/// = out[i];
2000/// out[i+D] =
2001/// }
2003 const SCEV &MaxBTC, const SCEV &Dist,
2004 uint64_t MaxStride) {
2005
2006 // If we can prove that
2007 // (**) |Dist| > MaxBTC * Step
2008 // where Step is the absolute stride of the memory accesses in bytes,
2009 // then there is no dependence.
2010 //
2011 // Rationale:
2012 // We basically want to check if the absolute distance (|Dist/Step|)
2013 // is >= the loop iteration count (or > MaxBTC).
2014 // This is equivalent to the Strong SIV Test (Practical Dependence Testing,
2015 // Section 4.2.1); Note, that for vectorization it is sufficient to prove
2016 // that the dependence distance is >= VF; This is checked elsewhere.
2017 // But in some cases we can prune dependence distances early, and
2018 // even before selecting the VF, and without a runtime test, by comparing
2019 // the distance against the loop iteration count. Since the vectorized code
2020 // will be executed only if LoopCount >= VF, proving distance >= LoopCount
2021 // also guarantees that distance >= VF.
2022 //
2023 const SCEV *Step = SE.getConstant(MaxBTC.getType(), MaxStride);
2024 const SCEV *Product = SE.getMulExpr(&MaxBTC, Step);
2025
2026 const SCEV *CastedDist = &Dist;
2027 const SCEV *CastedProduct = Product;
2028 uint64_t DistTypeSizeBits = DL.getTypeSizeInBits(Dist.getType());
2029 uint64_t ProductTypeSizeBits = DL.getTypeSizeInBits(Product->getType());
2030
2031 // The dependence distance can be positive/negative, so we sign extend Dist;
2032 // The multiplication of the absolute stride in bytes and the
2033 // backedgeTakenCount is non-negative, so we zero extend Product.
2034 if (DistTypeSizeBits > ProductTypeSizeBits)
2035 CastedProduct = SE.getZeroExtendExpr(Product, Dist.getType());
2036 else
2037 CastedDist = SE.getNoopOrSignExtend(&Dist, Product->getType());
2038
2039 // Is Dist - (MaxBTC * Step) > 0 ?
2040 // (If so, then we have proven (**) because |Dist| >= Dist)
2041 const SCEV *Minus = SE.getMinusSCEV(CastedDist, CastedProduct);
2042 if (SE.isKnownPositive(Minus))
2043 return true;
2044
2045 // Second try: Is -Dist - (MaxBTC * Step) > 0 ?
2046 // (If so, then we have proven (**) because |Dist| >= -1*Dist)
2047 const SCEV *NegDist = SE.getNegativeSCEV(CastedDist);
2048 Minus = SE.getMinusSCEV(NegDist, CastedProduct);
2049 return SE.isKnownPositive(Minus);
2050}
2051
2052/// Check the dependence for two accesses with the same stride \p Stride.
2053/// \p Distance is the positive distance in bytes, and \p TypeByteSize is type
2054/// size in bytes.
2055///
2056/// \returns true if they are independent.
2058 uint64_t TypeByteSize) {
2059 assert(Stride > 1 && "The stride must be greater than 1");
2060 assert(TypeByteSize > 0 && "The type size in byte must be non-zero");
2061 assert(Distance > 0 && "The distance must be non-zero");
2062
2063 // Skip if the distance is not multiple of type byte size.
2064 if (Distance % TypeByteSize)
2065 return false;
2066
2067 // No dependence if the distance is not multiple of the stride.
2068 // E.g.
2069 // for (i = 0; i < 1024 ; i += 4)
2070 // A[i+2] = A[i] + 1;
2071 //
2072 // Two accesses in memory (distance is 2, stride is 4):
2073 // | A[0] | | | | A[4] | | | |
2074 // | | | A[2] | | | | A[6] | |
2075 //
2076 // E.g.
2077 // for (i = 0; i < 1024 ; i += 3)
2078 // A[i+4] = A[i] + 1;
2079 //
2080 // Two accesses in memory (distance is 4, stride is 3):
2081 // | A[0] | | | A[3] | | | A[6] | | |
2082 // | | | | | A[4] | | | A[7] | |
2083 return Distance % Stride;
2084}
2085
2086bool MemoryDepChecker::areAccessesCompletelyBeforeOrAfter(const SCEV *Src,
2087 Type *SrcTy,
2088 const SCEV *Sink,
2089 Type *SinkTy) {
2090 const SCEV *BTC = PSE.getBackedgeTakenCount();
2091 const SCEV *SymbolicMaxBTC = PSE.getSymbolicMaxBackedgeTakenCount();
2092 ScalarEvolution &SE = *PSE.getSE();
2093 const auto &[SrcStart_, SrcEnd_] =
2094 getStartAndEndForAccess(InnermostLoop, Src, SrcTy, BTC, SymbolicMaxBTC,
2095 &SE, &PointerBounds, DT, AC, LoopGuards);
2096 if (isa<SCEVCouldNotCompute>(SrcStart_) || isa<SCEVCouldNotCompute>(SrcEnd_))
2097 return false;
2098
2099 const auto &[SinkStart_, SinkEnd_] =
2100 getStartAndEndForAccess(InnermostLoop, Sink, SinkTy, BTC, SymbolicMaxBTC,
2101 &SE, &PointerBounds, DT, AC, LoopGuards);
2102 if (isa<SCEVCouldNotCompute>(SinkStart_) ||
2103 isa<SCEVCouldNotCompute>(SinkEnd_))
2104 return false;
2105
2106 if (!LoopGuards)
2107 LoopGuards.emplace(ScalarEvolution::LoopGuards::collect(InnermostLoop, SE));
2108
2109 auto SrcEnd = SE.applyLoopGuards(SrcEnd_, *LoopGuards);
2110 auto SinkStart = SE.applyLoopGuards(SinkStart_, *LoopGuards);
2111 if (SE.isKnownPredicate(CmpInst::ICMP_ULE, SrcEnd, SinkStart))
2112 return true;
2113
2114 auto SinkEnd = SE.applyLoopGuards(SinkEnd_, *LoopGuards);
2115 auto SrcStart = SE.applyLoopGuards(SrcStart_, *LoopGuards);
2116 return SE.isKnownPredicate(CmpInst::ICMP_ULE, SinkEnd, SrcStart);
2117}
2118
2120 MemoryDepChecker::DepDistanceStrideAndSizeInfo>
2121MemoryDepChecker::getDependenceDistanceStrideAndSize(
2122 const AccessAnalysis::MemAccessInfo &A, Instruction *AInst,
2123 const AccessAnalysis::MemAccessInfo &B, Instruction *BInst) {
2124 const auto &DL = InnermostLoop->getHeader()->getDataLayout();
2125 auto &SE = *PSE.getSE();
2126 const auto &[APtr, AIsWrite] = A;
2127 const auto &[BPtr, BIsWrite] = B;
2128
2129 // Two reads are independent.
2130 if (!AIsWrite && !BIsWrite)
2132
2133 Type *ATy = getLoadStoreType(AInst);
2134 Type *BTy = getLoadStoreType(BInst);
2135
2136 // We cannot check pointers in different address spaces.
2137 if (APtr->getType()->getPointerAddressSpace() !=
2138 BPtr->getType()->getPointerAddressSpace())
2140
2142 std::optional<int64_t> StrideAPtr =
2143 getPtrStride(PSE, ATy, APtr, InnermostLoop, *DT, SymbolicStrides,
2144 /*ShouldCheckWrap=*/true, &Predicates);
2145 std::optional<int64_t> StrideBPtr =
2146 getPtrStride(PSE, BTy, BPtr, InnermostLoop, *DT, SymbolicStrides,
2147 /*ShouldCheckWrap=*/true, &Predicates);
2148 PSE.addPredicates(Predicates);
2149
2150 const SCEV *Src = PSE.getSCEV(APtr);
2151 const SCEV *Sink = PSE.getSCEV(BPtr);
2152
2153 // If the induction step is negative we have to invert source and sink of the
2154 // dependence when measuring the distance between them. We should not swap
2155 // AIsWrite with BIsWrite, as their uses expect them in program order.
2156 if (StrideAPtr && *StrideAPtr < 0) {
2157 std::swap(Src, Sink);
2158 std::swap(AInst, BInst);
2159 std::swap(ATy, BTy);
2160 std::swap(StrideAPtr, StrideBPtr);
2161 }
2162
2163 const SCEV *Dist = SE.getMinusSCEV(Sink, Src);
2164
2165 LLVM_DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
2166 << "\n");
2167 LLVM_DEBUG(dbgs() << "LAA: Distance for " << *AInst << " to " << *BInst
2168 << ": " << *Dist << "\n");
2169
2170 // Need accesses with constant strides and the same direction for further
2171 // dependence analysis. We don't want to vectorize "A[B[i]] += ..." and
2172 // similar code or pointer arithmetic that could wrap in the address space.
2173
2174 // If either Src or Sink are not strided (i.e. not a non-wrapping AddRec) and
2175 // not loop-invariant (stride will be 0 in that case), we cannot analyze the
2176 // dependence further and also cannot generate runtime checks.
2177 if (!StrideAPtr || !StrideBPtr) {
2178 LLVM_DEBUG(dbgs() << "Pointer access with non-constant stride\n");
2180 }
2181
2182 int64_t StrideAPtrInt = *StrideAPtr;
2183 int64_t StrideBPtrInt = *StrideBPtr;
2184 LLVM_DEBUG(dbgs() << "LAA: Src induction step: " << StrideAPtrInt
2185 << " Sink induction step: " << StrideBPtrInt << "\n");
2186 // At least Src or Sink are loop invariant and the other is strided or
2187 // invariant.
2188 if (!StrideAPtrInt || !StrideBPtrInt) {
2189 // If both are loop-invariant and access the same location, we cannot
2190 // vectorize.
2191 if (!StrideAPtrInt && !StrideBPtrInt && Dist->isZero())
2193 // Otherwise, we can generate a runtime check to disambiguate the accesses.
2195 }
2196
2197 // Both Src and Sink have a constant stride, check if they are in the same
2198 // direction.
2199 if ((StrideAPtrInt > 0) != (StrideBPtrInt > 0)) {
2200 LLVM_DEBUG(
2201 dbgs() << "Pointer access with strides in different directions\n");
2203 }
2204
2205 TypeSize AStoreSz = DL.getTypeStoreSize(ATy);
2206 TypeSize BStoreSz = DL.getTypeStoreSize(BTy);
2207
2208 // If store sizes are not the same, set TypeByteSize to zero, so we can check
2209 // it in the caller isDependent.
2210 uint64_t ASz = DL.getTypeAllocSize(ATy);
2211 uint64_t BSz = DL.getTypeAllocSize(BTy);
2212 uint64_t TypeByteSize = (AStoreSz == BStoreSz) ? BSz : 0;
2213
2214 uint64_t StrideAScaled = AbsoluteValue(StrideAPtrInt) * ASz;
2215 uint64_t StrideBScaled = AbsoluteValue(StrideBPtrInt) * BSz;
2216
2217 uint64_t MaxStride = std::max(StrideAScaled, StrideBScaled);
2218
2219 std::optional<uint64_t> CommonStride;
2220 if (StrideAScaled == StrideBScaled)
2221 CommonStride = StrideAScaled;
2222
2223 // TODO: Historically, we didn't retry with runtime checks when (unscaled)
2224 // strides were different but there is no inherent reason to.
2225 if (!isa<SCEVConstant>(Dist))
2226 ShouldRetryWithRuntimeChecks |= StrideAPtrInt == StrideBPtrInt;
2227
2228 // If distance is a SCEVCouldNotCompute, return Unknown immediately.
2229 if (isa<SCEVCouldNotCompute>(Dist)) {
2230 LLVM_DEBUG(dbgs() << "LAA: Uncomputable distance.\n");
2231 return Dependence::Unknown;
2232 }
2233
2234 return DepDistanceStrideAndSizeInfo(Dist, MaxStride, CommonStride,
2235 TypeByteSize, AIsWrite, BIsWrite);
2236}
2237
2239MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
2240 const MemAccessInfo &B, unsigned BIdx) {
2241 assert(AIdx < BIdx && "Must pass arguments in program order");
2242
2243 // Check if we can prove that Sink only accesses memory after Src's end or
2244 // vice versa. The helper is used to perform the checks only on the exit paths
2245 // where it helps to improve the analysis result.
2246 auto CheckCompletelyBeforeOrAfter = [&]() {
2247 auto *APtr = A.getPointer();
2248 auto *BPtr = B.getPointer();
2249 Type *ATy = getLoadStoreType(InstMap[AIdx]);
2250 Type *BTy = getLoadStoreType(InstMap[BIdx]);
2251 const SCEV *Src = PSE.getSCEV(APtr);
2252 const SCEV *Sink = PSE.getSCEV(BPtr);
2253 return areAccessesCompletelyBeforeOrAfter(Src, ATy, Sink, BTy);
2254 };
2255
2256 // Get the dependence distance, stride, type size and what access writes for
2257 // the dependence between A and B.
2258 auto Res =
2259 getDependenceDistanceStrideAndSize(A, InstMap[AIdx], B, InstMap[BIdx]);
2260 if (std::holds_alternative<Dependence::DepType>(Res)) {
2261 if (std::get<Dependence::DepType>(Res) == Dependence::Unknown &&
2262 CheckCompletelyBeforeOrAfter())
2263 return Dependence::NoDep;
2264 return std::get<Dependence::DepType>(Res);
2265 }
2266
2267 auto &[Dist, MaxStride, CommonStride, TypeByteSize, AIsWrite, BIsWrite] =
2268 std::get<DepDistanceStrideAndSizeInfo>(Res);
2269 bool HasSameSize = TypeByteSize > 0;
2270
2271 ScalarEvolution &SE = *PSE.getSE();
2272 auto &DL = InnermostLoop->getHeader()->getDataLayout();
2273
2274 // If the distance between the acecsses is larger than their maximum absolute
2275 // stride multiplied by the symbolic maximum backedge taken count (which is an
2276 // upper bound of the number of iterations), the accesses are independet, i.e.
2277 // they are far enough appart that accesses won't access the same location
2278 // across all loop ierations.
2279 if (HasSameSize &&
2281 DL, SE, *(PSE.getSymbolicMaxBackedgeTakenCount()), *Dist, MaxStride))
2282 return Dependence::NoDep;
2283
2284 const APInt *APDist = nullptr;
2285 uint64_t ConstDist = 0;
2286 if (match(Dist, m_scev_APInt(APDist))) {
2287 std::optional<uint64_t> Val = APDist->abs().tryZExtValue();
2288 if (!Val) {
2289 LLVM_DEBUG(dbgs() << "LAA: Constant distance does not fit in 64 bits.\n");
2290 return Dependence::Unknown;
2291 }
2292 ConstDist = *Val;
2293 }
2294
2295 // Attempt to prove strided accesses independent.
2296 if (APDist) {
2297 // If the distance between accesses and their strides are known constants,
2298 // check whether the accesses interlace each other.
2299 if (ConstDist > 0 && CommonStride && CommonStride > 1 && HasSameSize &&
2300 areStridedAccessesIndependent(ConstDist, *CommonStride, TypeByteSize)) {
2301 LLVM_DEBUG(dbgs() << "LAA: Strided accesses are independent\n");
2302 return Dependence::NoDep;
2303 }
2304 } else {
2305 if (!LoopGuards)
2306 LoopGuards.emplace(
2307 ScalarEvolution::LoopGuards::collect(InnermostLoop, SE));
2308 Dist = SE.applyLoopGuards(Dist, *LoopGuards);
2309 }
2310
2311 // Negative distances are not plausible dependencies.
2312 if (SE.isKnownNonPositive(Dist)) {
2313 if (SE.isKnownNonNegative(Dist)) {
2314 if (HasSameSize) {
2315 // Write to the same location with the same size.
2316 return Dependence::Forward;
2317 }
2318 LLVM_DEBUG(dbgs() << "LAA: possibly zero dependence difference but "
2319 "different type sizes\n");
2320 return Dependence::Unknown;
2321 }
2322
2323 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
2324 // Check if the first access writes to a location that is read in a later
2325 // iteration, where the distance between them is not a multiple of a vector
2326 // factor and relatively small.
2327 //
2328 // NOTE: There is no need to update MaxSafeVectorWidthInBits after call to
2329 // couldPreventStoreLoadForward, even if it changed MinDepDistBytes, since a
2330 // forward dependency will allow vectorization using any width.
2331
2332 if (IsTrueDataDependence && EnableForwardingConflictDetection) {
2333 if (!ConstDist) {
2334 return CheckCompletelyBeforeOrAfter() ? Dependence::NoDep
2336 }
2337 if (!HasSameSize ||
2338 couldPreventStoreLoadForward(ConstDist, TypeByteSize)) {
2339 LLVM_DEBUG(
2340 dbgs() << "LAA: Forward but may prevent st->ld forwarding\n");
2342 }
2343 }
2344
2345 LLVM_DEBUG(dbgs() << "LAA: Dependence is negative\n");
2346 return Dependence::Forward;
2347 }
2348
2349 std::optional<int64_t> MinDistanceOpt =
2351 if (!MinDistanceOpt) {
2352 LLVM_DEBUG(dbgs() << "LAA: Minimum distance does not fit in 64 bits.\n");
2353 return Dependence::Unknown;
2354 }
2355 int64_t MinDistance = *MinDistanceOpt;
2356 // Below we only handle strictly positive distances.
2357 if (MinDistance <= 0) {
2358 return CheckCompletelyBeforeOrAfter() ? Dependence::NoDep
2360 }
2361
2362 if (!HasSameSize) {
2363 if (CheckCompletelyBeforeOrAfter())
2364 return Dependence::NoDep;
2365 LLVM_DEBUG(dbgs() << "LAA: ReadWrite-Write positive dependency with "
2366 "different type sizes\n");
2367 return Dependence::Unknown;
2368 }
2369 // Bail out early if passed-in parameters make vectorization not feasible.
2370 unsigned MinForcedFactor =
2371 std::max(1U, VectorizerParams::VectorizationFactor.getKnownMinValue());
2372 unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
2374 // The minimum number of iterations for a vectorized/unrolled version.
2375 unsigned MinNumIter = std::max(MinForcedFactor * ForcedUnroll, 2U);
2376
2377 // It's not vectorizable if the distance is smaller than the minimum distance
2378 // needed for a vectroized/unrolled version. Vectorizing one iteration in
2379 // front needs MaxStride. Vectorizing the last iteration needs TypeByteSize.
2380 // (No need to plus the last gap distance).
2381 //
2382 // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
2383 // foo(int *A) {
2384 // int *B = (int *)((char *)A + 14);
2385 // for (i = 0 ; i < 1024 ; i += 2)
2386 // B[i] = A[i] + 1;
2387 // }
2388 //
2389 // Two accesses in memory (stride is 4 * 2):
2390 // | A[0] | | A[2] | | A[4] | | A[6] | |
2391 // | B[0] | | B[2] | | B[4] |
2392 //
2393 // MinDistance needs for vectorizing iterations except the last iteration:
2394 // 4 * 2 * (MinNumIter - 1). MinDistance needs for the last iteration: 4.
2395 // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4.
2396 //
2397 // If MinNumIter is 2, it is vectorizable as the minimum distance needed is
2398 // 12, which is less than distance.
2399 //
2400 // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4),
2401 // the minimum distance needed is 28, which is greater than distance. It is
2402 // not safe to do vectorization.
2403 //
2404 // We use MaxStride (maximum of src and sink strides) to get a conservative
2405 // lower bound on the MinDistanceNeeded in case of different strides.
2406
2407 // We know that Dist is positive, but it may not be constant. Use the signed
2408 // minimum for computations below, as this ensures we compute the closest
2409 // possible dependence distance.
2410 uint64_t MinDistanceNeeded = MaxStride * (MinNumIter - 1) + TypeByteSize;
2411 if (MinDistanceNeeded > static_cast<uint64_t>(MinDistance)) {
2412 if (!ConstDist) {
2413 // For non-constant distances, we checked the lower bound of the
2414 // dependence distance and the distance may be larger at runtime (and safe
2415 // for vectorization). Classify it as Unknown, so we re-try with runtime
2416 // checks, unless we can prove both accesses cannot overlap.
2417 return CheckCompletelyBeforeOrAfter() ? Dependence::NoDep
2419 }
2420 LLVM_DEBUG(dbgs() << "LAA: Failure because of positive minimum distance "
2421 << MinDistance << '\n');
2422 return Dependence::Backward;
2423 }
2424
2425 // Unsafe if the minimum distance needed is greater than smallest dependence
2426 // distance distance.
2427 if (MinDistanceNeeded > MinDepDistBytes) {
2428 LLVM_DEBUG(dbgs() << "LAA: Failure because it needs at least "
2429 << MinDistanceNeeded << " size in bytes\n");
2430 return Dependence::Backward;
2431 }
2432
2433 MinDepDistBytes =
2434 std::min(static_cast<uint64_t>(MinDistance), MinDepDistBytes);
2435
2436 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
2437 if (IsTrueDataDependence && EnableForwardingConflictDetection && ConstDist &&
2438 couldPreventStoreLoadForward(MinDistance, TypeByteSize, *CommonStride))
2440
2441 uint64_t MaxVF = MinDepDistBytes / MaxStride;
2442 LLVM_DEBUG(dbgs() << "LAA: Positive min distance " << MinDistance
2443 << " with max VF = " << MaxVF << '\n');
2444
2445 uint64_t MaxVFInBits = MaxVF * TypeByteSize * 8;
2446 if (!ConstDist && MaxVFInBits < MaxTargetVectorWidthInBits) {
2447 // For non-constant distances, we checked the lower bound of the dependence
2448 // distance and the distance may be larger at runtime (and safe for
2449 // vectorization). Classify it as Unknown, so we re-try with runtime checks,
2450 // unless we can prove both accesses cannot overlap.
2451 return CheckCompletelyBeforeOrAfter() ? Dependence::NoDep
2453 }
2454
2455 if (CheckCompletelyBeforeOrAfter())
2456 return Dependence::NoDep;
2457
2458 MaxSafeVectorWidthInBits = std::min(MaxSafeVectorWidthInBits, MaxVFInBits);
2460}
2461
2463 ArrayRef<MemAccessInfo> CheckDeps) {
2464
2465 MinDepDistBytes = -1;
2467 for (MemAccessInfo CurAccess : CheckDeps) {
2468 if (Visited.contains(CurAccess))
2469 continue;
2470
2471 // Check accesses within this set.
2473 DepCands.findLeader(CurAccess);
2475 DepCands.member_end();
2476
2477 // Check every access pair.
2478 while (AI != AE) {
2479 Visited.insert(*AI);
2480 bool AIIsWrite = AI->getInt();
2481 // Reads from the same pointer don't create extra hazards, but multiple
2482 // stores do (WAW), so start from AI for writes and next(AI) for reads.
2484 (AIIsWrite ? AI : std::next(AI));
2485 while (OI != AE) {
2486 // Check every accessing instruction pair in program order.
2487 auto &Acc = Accesses[*AI];
2488 for (std::vector<unsigned>::iterator I1 = Acc.begin(), I1E = Acc.end();
2489 I1 != I1E; ++I1)
2490 // When checking for WAW (OI == AI) caused by multiple writes to the
2491 // same pointer, start I2 at the next access past I1 to avoid
2492 // self-comparison.
2493 for (std::vector<unsigned>::iterator
2494 I2 = (OI == AI ? std::next(I1) : Accesses[*OI].begin()),
2495 I2E = (OI == AI ? I1E : Accesses[*OI].end());
2496 I2 != I2E; ++I2) {
2497 auto A = std::make_pair(&*AI, *I1);
2498 auto B = std::make_pair(&*OI, *I2);
2499
2500 assert(*I1 != *I2);
2501 if (*I1 > *I2)
2502 std::swap(A, B);
2503
2505 isDependent(*A.first, A.second, *B.first, B.second);
2507
2508 // Gather dependences unless we accumulated MaxDependences
2509 // dependences. In that case return as soon as we find the first
2510 // unsafe dependence. This puts a limit on this quadratic
2511 // algorithm.
2512 if (RecordDependences) {
2513 if (Type != Dependence::NoDep)
2514 Dependences.emplace_back(A.second, B.second, Type);
2515
2516 if (Dependences.size() >= MaxDependences) {
2517 RecordDependences = false;
2518 Dependences.clear();
2520 << "Too many dependences, stopped recording\n");
2521 }
2522 }
2523 if (!RecordDependences && !isSafeForVectorization())
2524 return false;
2525 }
2526 ++OI;
2527 }
2528 ++AI;
2529 }
2530 }
2531
2532 LLVM_DEBUG(dbgs() << "Total Dependences: " << Dependences.size() << "\n");
2533 return isSafeForVectorization();
2534}
2535
2538 MemAccessInfo Access(Ptr, IsWrite);
2539 auto I = Accesses.find(Access);
2541 if (I != Accesses.end()) {
2542 transform(I->second, std::back_inserter(Insts),
2543 [&](unsigned Idx) { return this->InstMap[Idx]; });
2544 }
2545
2546 return Insts;
2547}
2548
2550 "NoDep",
2551 "Unknown",
2552 "IndirectUnsafe",
2553 "InvariantUnsafe",
2554 "Forward",
2555 "ForwardButPreventsForwarding",
2556 "Backward",
2557 "BackwardVectorizable",
2558 "BackwardVectorizableButPreventsForwarding"};
2559
2561 raw_ostream &OS, unsigned Depth,
2562 const SmallVectorImpl<Instruction *> &Instrs) const {
2563 OS.indent(Depth) << DepName[Type] << ":\n";
2564 OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
2565 OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
2566}
2567
2568bool LoopAccessInfo::canAnalyzeLoop() {
2569 // We need to have a loop header.
2570 LLVM_DEBUG(dbgs() << "\nLAA: Checking a loop in '"
2571 << TheLoop->getHeader()->getParent()->getName() << "' from "
2572 << TheLoop->getLocStr() << "\n");
2573
2574 // We can only analyze innermost loops.
2575 if (!TheLoop->isInnermost()) {
2576 LLVM_DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
2577 recordAnalysis("NotInnerMostLoop") << "loop is not the innermost loop";
2578 return false;
2579 }
2580
2581 // We must have a single backedge.
2582 if (TheLoop->getNumBackEdges() != 1) {
2583 LLVM_DEBUG(
2584 dbgs() << "LAA: loop control flow is not understood by analyzer\n");
2585 recordAnalysis("CFGNotUnderstood")
2586 << "loop control flow is not understood by analyzer";
2587 return false;
2588 }
2589
2590 // ScalarEvolution needs to be able to find the symbolic max backedge taken
2591 // count, which is an upper bound on the number of loop iterations. The loop
2592 // may execute fewer iterations, if it exits via an uncountable exit.
2593 const SCEV *ExitCount = PSE->getSymbolicMaxBackedgeTakenCount();
2594 if (isa<SCEVCouldNotCompute>(ExitCount)) {
2595 recordAnalysis("CantComputeNumberOfIterations")
2596 << "could not determine number of loop iterations";
2597 LLVM_DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
2598 return false;
2599 }
2600
2601 LLVM_DEBUG(dbgs() << "LAA: Found an analyzable loop: "
2602 << TheLoop->getHeader()->getName() << "\n");
2603 return true;
2604}
2605
2606bool LoopAccessInfo::analyzeLoop(AAResults *AA, const LoopInfo *LI,
2607 const TargetLibraryInfo *TLI,
2608 DominatorTree *DT) {
2609 // Holds the Load and Store instructions.
2612 SmallPtrSet<MDNode *, 8> LoopAliasScopes;
2613
2614 // Holds all the different accesses in the loop.
2615 unsigned NumReads = 0;
2616 unsigned NumReadWrites = 0;
2617
2618 bool HasComplexMemInst = false;
2619
2620 // A runtime check is only legal to insert if there are no convergent calls.
2621 HasConvergentOp = false;
2622
2623 PtrRtChecking->Pointers.clear();
2624 PtrRtChecking->Need = false;
2625
2626 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
2627
2628 const bool EnableMemAccessVersioningOfLoop =
2630 !TheLoop->getHeader()->getParent()->hasOptSize();
2631
2632 // Traverse blocks in fixed RPOT order, regardless of their storage in the
2633 // loop info, as it may be arbitrary.
2634 LoopBlocksRPO RPOT(TheLoop);
2635 RPOT.perform(LI);
2636
2637 // Don't return early as soon as we found a memory access that cannot be
2638 // vectorize - HasConvergentOp must still be computed as it is part of LAI's
2639 // public API (used by LoopDistribute).
2640 for (BasicBlock *BB : RPOT) {
2641 // Scan the BB and collect legal loads and stores. Also detect any
2642 // convergent instructions.
2643 for (Instruction &I : *BB) {
2644 if (auto *Call = dyn_cast<CallBase>(&I)) {
2645 if (Call->isConvergent())
2646 HasConvergentOp = true;
2647 }
2648
2649 // Unsafe to vectorize and we already found a convergent operation, can
2650 // early return now.
2651 if (HasComplexMemInst && HasConvergentOp)
2652 return false;
2653
2654 // Already unsafe to vectorize; keep scanning for convergent ops.
2655 if (HasComplexMemInst)
2656 continue;
2657
2658 // Record alias scopes defined inside the loop.
2659 if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
2660 for (Metadata *Op : Decl->getScopeList()->operands())
2661 LoopAliasScopes.insert(cast<MDNode>(Op));
2662
2663 // Many math library functions read the rounding mode. We will only
2664 // vectorize a loop if it contains known function calls that don't set
2665 // the flag. Therefore, it is safe to ignore this read from memory.
2666 auto *Call = dyn_cast<CallInst>(&I);
2668 continue;
2669
2670 // If this is a load, save it. If this instruction can read from memory
2671 // but is not a load, we only allow it if it's a call to a function with a
2672 // vector mapping and no pointer arguments.
2673 if (I.mayReadFromMemory()) {
2674 auto hasPointerArgs = [](CallBase *CB) {
2675 return any_of(CB->args(), [](Value const *Arg) {
2676 return Arg->getType()->isPointerTy();
2677 });
2678 };
2679
2680 // If the function has an explicit vectorized counterpart, and does not
2681 // take output/input pointers, we can safely assume that it can be
2682 // vectorized.
2683 if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
2684 !hasPointerArgs(Call) && !VFDatabase::getMappings(*Call).empty())
2685 continue;
2686
2687 auto *Ld = dyn_cast<LoadInst>(&I);
2688 if (!Ld) {
2689 recordAnalysis("CantVectorizeInstruction", &I)
2690 << "instruction cannot be vectorized";
2691 HasComplexMemInst = true;
2692 continue;
2693 }
2694 if (!Ld->isSimple() && !IsAnnotatedParallel) {
2695 recordAnalysis("NonSimpleLoad", Ld)
2696 << "read with atomic ordering or volatile read";
2697 LLVM_DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
2698 HasComplexMemInst = true;
2699 continue;
2700 }
2701 NumLoads++;
2702 Loads.push_back(Ld);
2703 DepChecker->addAccess(Ld);
2704 if (EnableMemAccessVersioningOfLoop)
2705 collectStridedAccess(Ld);
2706 continue;
2707 }
2708
2709 // Save 'store' instructions. Abort if other instructions write to memory.
2710 if (I.mayWriteToMemory()) {
2711 auto *St = dyn_cast<StoreInst>(&I);
2712 if (!St) {
2713 recordAnalysis("CantVectorizeInstruction", &I)
2714 << "instruction cannot be vectorized";
2715 HasComplexMemInst = true;
2716 continue;
2717 }
2718 if (!St->isSimple() && !IsAnnotatedParallel) {
2719 recordAnalysis("NonSimpleStore", St)
2720 << "write with atomic ordering or volatile write";
2721 LLVM_DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
2722 HasComplexMemInst = true;
2723 continue;
2724 }
2725 NumStores++;
2726 Stores.push_back(St);
2727 DepChecker->addAccess(St);
2728 if (EnableMemAccessVersioningOfLoop)
2729 collectStridedAccess(St);
2730 }
2731 } // Next instr.
2732 } // Next block.
2733
2734 if (HasComplexMemInst)
2735 return false;
2736
2737 // Now we have two lists that hold the loads and the stores.
2738 // Next, we find the pointers that they use.
2739
2740 // Check if we see any stores. If there are no stores, then we don't
2741 // care if the pointers are *restrict*.
2742 if (!Stores.size()) {
2743 LLVM_DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
2744 return true;
2745 }
2746
2748 AccessAnalysis Accesses(TheLoop, AA, LI, *DT, DepCands, *PSE,
2749 LoopAliasScopes);
2750
2751 // Holds the analyzed pointers. We don't want to call getUnderlyingObjects
2752 // multiple times on the same object. If the ptr is accessed twice, once
2753 // for read and once for write, it will only appear once (on the write
2754 // list). This is okay, since we are going to check for conflicts between
2755 // writes and between reads and writes, but not between reads and reads.
2756 SmallSet<std::pair<Value *, Type *>, 16> Seen;
2757
2758 // Record uniform store addresses to identify if we have multiple stores
2759 // to the same address.
2760 SmallPtrSet<Value *, 16> UniformStores;
2761
2762 for (StoreInst *ST : Stores) {
2763 Value *Ptr = ST->getPointerOperand();
2764
2765 if (isInvariant(Ptr)) {
2766 // Record store instructions to loop invariant addresses
2767 StoresToInvariantAddresses.push_back(ST);
2768 HasStoreStoreDependenceInvolvingLoopInvariantAddress |=
2769 !UniformStores.insert(Ptr).second;
2770 }
2771
2772 // If we did *not* see this pointer before, insert it to the read-write
2773 // list. At this phase it is only a 'write' list.
2774 Type *AccessTy = getLoadStoreType(ST);
2775 if (Seen.insert({Ptr, AccessTy}).second) {
2776 ++NumReadWrites;
2777
2778 MemoryLocation Loc = MemoryLocation::get(ST);
2779 // The TBAA metadata could have a control dependency on the predication
2780 // condition, so we cannot rely on it when determining whether or not we
2781 // need runtime pointer checks.
2782 if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
2783 Loc.AATags.TBAA = nullptr;
2784
2785 // Expand forked pointers (i.e., a phi of multiple strided pointers) into
2786 // all alternatives.
2787 visitPointers(const_cast<Value *>(Loc.Ptr), *TheLoop,
2788 [&Accesses, AccessTy, Loc](Value *Ptr) {
2789 MemoryLocation NewLoc = Loc.getWithNewPtr(Ptr);
2790 Accesses.addStore(NewLoc, AccessTy);
2791 });
2792 }
2793 }
2794
2795 if (IsAnnotatedParallel) {
2796 LLVM_DEBUG(
2797 dbgs() << "LAA: A loop annotated parallel, ignore memory dependency "
2798 << "checks.\n");
2799 return true;
2800 }
2801
2802 for (LoadInst *LD : Loads) {
2803 Value *Ptr = LD->getPointerOperand();
2804 // If we did *not* see this pointer before, insert it to the read list. If
2805 // we *did* see it before, then it is already in the read-write list. This
2806 // allows us to vectorize expressions such as A[i] += x; Because the address
2807 // of A[i] is a read-write pointer. This only works if the index of A[i] is
2808 // strictly monotonic, which we approximate (conservatively) via
2809 // getPtrStride. If the address is unknown (e.g. A[B[i]]) then we may read,
2810 // modify, and write overlapping words. Note that "zero stride" is unsafe
2811 // and is being handled below.
2812 bool IsReadOnlyPtr = false;
2813 Type *AccessTy = getLoadStoreType(LD);
2814 if (Seen.insert({Ptr, AccessTy}).second ||
2815 !getPtrStride(*PSE, AccessTy, Ptr, TheLoop, *DT, SymbolicStrides, false,
2816 true)) {
2817 ++NumReads;
2818 IsReadOnlyPtr = true;
2819 }
2820
2821 // See if there is an unsafe dependency between a load to a uniform address and
2822 // store to the same uniform address.
2823 if (UniformStores.contains(Ptr)) {
2824 LLVM_DEBUG(dbgs() << "LAA: Found an unsafe dependency between a uniform "
2825 "load and uniform store to the same address!\n");
2826 HasLoadStoreDependenceInvolvingLoopInvariantAddress = true;
2827 }
2828
2829 MemoryLocation Loc = MemoryLocation::get(LD);
2830 // The TBAA metadata could have a control dependency on the predication
2831 // condition, so we cannot rely on it when determining whether or not we
2832 // need runtime pointer checks.
2833 if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
2834 Loc.AATags.TBAA = nullptr;
2835
2836 // Expand forked pointers (i.e., a phi of multiple strided pointers) into
2837 // all alternatives.
2838 visitPointers(const_cast<Value *>(Loc.Ptr), *TheLoop,
2839 [&Accesses, AccessTy, Loc, IsReadOnlyPtr](Value *Ptr) {
2840 MemoryLocation NewLoc = Loc.getWithNewPtr(Ptr);
2841 Accesses.addLoad(NewLoc, AccessTy, IsReadOnlyPtr);
2842 });
2843 }
2844
2845 // If we write (or read-write) to a single destination and there are no other
2846 // reads in this loop then is it safe to vectorize: the vectorized stores
2847 // preserve ordering via replication or order-preserving @llvm.masked.scatter.
2848 if (NumReadWrites == 1 && NumReads == 0) {
2849 LLVM_DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
2850 return true;
2851 }
2852
2853 // Build dependence sets and check whether we need a runtime pointer bounds
2854 // check.
2855 Accesses.buildDependenceSets();
2856
2857 // Find pointers with computable bounds. We are going to use this information
2858 // to place a runtime bound check.
2859 Value *UncomputablePtr = nullptr;
2860 HasCompletePtrRtChecking =
2861 Accesses.canCheckPtrAtRT(*PtrRtChecking, TheLoop, SymbolicStrides,
2862 UncomputablePtr, AllowPartial, getDepChecker());
2863 if (!HasCompletePtrRtChecking) {
2864 const auto *I = dyn_cast_or_null<Instruction>(UncomputablePtr);
2865 recordAnalysis("CantIdentifyArrayBounds", I)
2866 << "cannot identify array bounds";
2867 LLVM_DEBUG(dbgs() << "LAA: We can't vectorize because we can't find "
2868 << "the array bounds.\n");
2869 return false;
2870 }
2871
2872 LLVM_DEBUG(
2873 dbgs() << "LAA: May be able to perform a memory runtime check if needed.\n");
2874
2875 bool DepsAreSafe = true;
2876 if (Accesses.isDependencyCheckNeeded()) {
2877 LLVM_DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
2878 DepsAreSafe =
2879 DepChecker->areDepsSafe(DepCands, Accesses.getDependenciesToCheck());
2880
2881 if (!DepsAreSafe && DepChecker->shouldRetryWithRuntimeChecks()) {
2882 LLVM_DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
2883
2884 PtrRtChecking->reset();
2885 PtrRtChecking->Need = true;
2886
2887 UncomputablePtr = nullptr;
2888 HasCompletePtrRtChecking = Accesses.canCheckPtrAtRT(
2889 *PtrRtChecking, TheLoop, SymbolicStrides, UncomputablePtr,
2890 AllowPartial, getDepChecker());
2891
2892 // Check that we found the bounds for the pointer.
2893 if (!HasCompletePtrRtChecking) {
2894 auto *I = dyn_cast_or_null<Instruction>(UncomputablePtr);
2895 recordAnalysis("CantCheckMemDepsAtRunTime", I)
2896 << "cannot check memory dependencies at runtime";
2897 LLVM_DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
2898 return false;
2899 }
2900
2901 // Clear the dependency checks. They are no longer needed.
2902 Accesses.resetDepChecks(*DepChecker);
2903
2904 DepsAreSafe = true;
2905 }
2906 }
2907
2908 // Update the invariant address dependence flags based on dependences found
2909 // by the dep checker. Even if dependences were not recorded (too many to
2910 // track), any InvariantUnsafe dep would still have set the status to Unsafe
2911 if (const auto *Deps = DepChecker->getDependences()) {
2912 for (const auto &Dep : *Deps) {
2914 continue;
2915 Instruction *Src = Dep.getSource(*DepChecker);
2916 Instruction *Dst = Dep.getDestination(*DepChecker);
2917 if (isa<LoadInst>(Src) != isa<LoadInst>(Dst)) {
2918 HasLoadStoreDependenceInvolvingLoopInvariantAddress = true;
2919 } else {
2920 assert(isa<StoreInst>(Src) && isa<StoreInst>(Dst) &&
2921 "Expected both to be stores");
2922 HasStoreStoreDependenceInvolvingLoopInvariantAddress = true;
2923 }
2924 }
2925 }
2926
2927 if (HasConvergentOp) {
2928 recordAnalysis("CantInsertRuntimeCheckWithConvergent")
2929 << "cannot add control dependency to convergent operation";
2930 LLVM_DEBUG(dbgs() << "LAA: We can't vectorize because a runtime check "
2931 "would be needed with a convergent operation\n");
2932 return false;
2933 }
2934
2935 if (DepsAreSafe) {
2936 LLVM_DEBUG(
2937 dbgs() << "LAA: No unsafe dependent memory operations in loop. We"
2938 << (PtrRtChecking->Need ? "" : " don't")
2939 << " need runtime memory checks.\n");
2940 return true;
2941 }
2942
2943 emitUnsafeDependenceRemark();
2944 return false;
2945}
2946
2947void LoopAccessInfo::emitUnsafeDependenceRemark() {
2948 const auto *Deps = getDepChecker().getDependences();
2949 if (!Deps)
2950 return;
2951 const auto *Found =
2952 llvm::find_if(*Deps, [](const MemoryDepChecker::Dependence &D) {
2955 });
2956 if (Found == Deps->end())
2957 return;
2958 MemoryDepChecker::Dependence Dep = *Found;
2959
2960 LLVM_DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
2961
2962 // Emit remark for first unsafe dependence
2963 bool HasForcedDistribution =
2964 getBooleanLoopAttribute(TheLoop, "llvm.loop.distribute.enable");
2965
2966 const std::string Info =
2967 HasForcedDistribution
2968 ? "unsafe dependent memory operations in loop."
2969 : "unsafe dependent memory operations in loop. Use "
2970 "#pragma clang loop distribute(enable) to allow loop distribution "
2971 "to attempt to isolate the offending operations into a separate "
2972 "loop";
2973 OptimizationRemarkAnalysis &R =
2974 recordAnalysis("UnsafeDep", Dep.getDestination(getDepChecker())) << Info;
2975
2976 switch (Dep.Type) {
2980 llvm_unreachable("Unexpected dependence");
2982 R << "\nBackward loop carried data dependence.";
2983 break;
2985 R << "\nForward loop carried data dependence that prevents "
2986 "store-to-load forwarding.";
2987 break;
2989 R << "\nBackward loop carried data dependence that prevents "
2990 "store-to-load forwarding.";
2991 break;
2993 R << "\nUnsafe indirect dependence.";
2994 break;
2996 R << "\nUnsafe dependence on loop-invariant address.";
2997 break;
2999 R << "\nUnknown data dependence.";
3000 break;
3001 }
3002
3003 if (Instruction *I = Dep.getSource(getDepChecker())) {
3004 DebugLoc SourceLoc = I->getDebugLoc();
3006 SourceLoc = DD->getDebugLoc();
3007 if (SourceLoc)
3008 R << " Memory location is the same as accessed at "
3009 << ore::NV("Location", SourceLoc);
3010 }
3011}
3012
3014 const Loop *TheLoop,
3015 const DominatorTree *DT) {
3016 assert(TheLoop->contains(BB) && "Unknown block used");
3017
3018 // Blocks that do not dominate the latch need predication.
3019 const BasicBlock *Latch = TheLoop->getLoopLatch();
3020 assert(Latch && "Loop expected to have a single latch.");
3021 return !DT->dominates(BB, Latch);
3022}
3023
3025LoopAccessInfo::recordAnalysis(StringRef RemarkName, const Instruction *I) {
3026 assert(!Report && "Multiple reports generated");
3027
3028 const BasicBlock *CodeRegion = TheLoop->getHeader();
3029 DebugLoc DL = TheLoop->getStartLoc();
3030
3031 if (I) {
3032 CodeRegion = I->getParent();
3033 // If there is no debug location attached to the instruction, revert back to
3034 // using the loop's.
3035 if (I->getDebugLoc())
3036 DL = I->getDebugLoc();
3037 }
3038
3039 Report = std::make_unique<OptimizationRemarkAnalysis>(DEBUG_TYPE, RemarkName,
3040 DL, CodeRegion);
3041 return *Report;
3042}
3043
3045 auto *SE = PSE->getSE();
3046 if (TheLoop->isLoopInvariant(V))
3047 return true;
3048 if (!SE->isSCEVable(V->getType()))
3049 return false;
3050 const SCEV *S = SE->getSCEV(V);
3051 return SE->isLoopInvariant(S, TheLoop);
3052}
3053
3054/// If \p Ptr is a GEP, which has a loop-variant operand, return that operand.
3055/// Otherwise, return \p Ptr.
3057 Loop *Lp) {
3058 auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3059 if (!GEP)
3060 return Ptr;
3061
3062 Value *V = Ptr;
3063 for (const Use &U : GEP->operands()) {
3064 if (!SE->isLoopInvariant(SE->getSCEV(U), Lp)) {
3065 if (V == Ptr)
3066 V = U;
3067 else
3068 // There must be exactly one loop-variant operand.
3069 return Ptr;
3070 }
3071 }
3072 return V;
3073}
3074
3075/// Get the stride of a pointer access in a loop. Looks for symbolic
3076/// strides "a[i*stride]". Returns the symbolic stride, or null otherwise.
3077static const SCEV *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
3078 auto *PtrTy = dyn_cast<PointerType>(Ptr->getType());
3079 if (!PtrTy)
3080 return nullptr;
3081
3082 // Try to remove a gep instruction to make the pointer (actually index at this
3083 // point) easier analyzable. If OrigPtr is equal to Ptr we are analyzing the
3084 // pointer, otherwise, we are analyzing the index.
3085 Value *OrigPtr = Ptr;
3086
3087 Ptr = getLoopVariantGEPOperand(Ptr, SE, Lp);
3088 const SCEV *V = SE->getSCEV(Ptr);
3089
3090 if (Ptr != OrigPtr)
3091 // Strip off casts.
3092 while (auto *C = dyn_cast<SCEVIntegralCastExpr>(V))
3093 V = C->getOperand();
3094
3096 return nullptr;
3097
3098 // Note that the restriction after this loop invariant check are only
3099 // profitability restrictions.
3100 if (!SE->isLoopInvariant(V, Lp))
3101 return nullptr;
3102
3103 // Look for the loop invariant symbolic value.
3104 if (isa<SCEVUnknown>(V))
3105 return V;
3106
3107 // Look through multiplies that scale a stride by a constant.
3109 if (auto *C = dyn_cast<SCEVIntegralCastExpr>(V))
3110 if (isa<SCEVUnknown>(C->getOperand()))
3111 return V;
3112
3113 return nullptr;
3114}
3115
3116void LoopAccessInfo::collectStridedAccess(Value *MemAccess) {
3117 Value *Ptr = getLoadStorePointerOperand(MemAccess);
3118 if (!Ptr)
3119 return;
3120
3121 // Note: getStrideFromPointer is a *profitability* heuristic. We
3122 // could broaden the scope of values returned here - to anything
3123 // which happens to be loop invariant and contributes to the
3124 // computation of an interesting IV - but we chose not to as we
3125 // don't have a cost model here, and broadening the scope exposes
3126 // far too many unprofitable cases.
3127 const SCEV *StrideExpr = getStrideFromPointer(Ptr, PSE->getSE(), TheLoop);
3128 if (!StrideExpr)
3129 return;
3130
3131 if (match(StrideExpr, m_scev_UndefOrPoison()))
3132 return;
3133
3134 LLVM_DEBUG(dbgs() << "LAA: Found a strided access that is a candidate for "
3135 "versioning:");
3136 LLVM_DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *StrideExpr << "\n");
3137
3138 if (!SpeculateUnitStride) {
3139 LLVM_DEBUG(dbgs() << " Chose not to due to -laa-speculate-unit-stride\n");
3140 return;
3141 }
3142
3143 // Avoid adding the "Stride == 1" predicate when we know that
3144 // Stride >= Trip-Count. Such a predicate will effectively optimize a single
3145 // or zero iteration loop, as Trip-Count <= Stride == 1.
3146 //
3147 // TODO: We are currently not making a very informed decision on when it is
3148 // beneficial to apply stride versioning. It might make more sense that the
3149 // users of this analysis (such as the vectorizer) will trigger it, based on
3150 // their specific cost considerations; For example, in cases where stride
3151 // versioning does not help resolving memory accesses/dependences, the
3152 // vectorizer should evaluate the cost of the runtime test, and the benefit
3153 // of various possible stride specializations, considering the alternatives
3154 // of using gather/scatters (if available).
3155
3156 const SCEV *MaxBTC = PSE->getSymbolicMaxBackedgeTakenCount();
3157
3158 // Match the types so we can compare the stride and the MaxBTC.
3159 // The Stride can be positive/negative, so we sign extend Stride;
3160 // The backedgeTakenCount is non-negative, so we zero extend MaxBTC.
3161 const DataLayout &DL = TheLoop->getHeader()->getDataLayout();
3162 uint64_t StrideTypeSizeBits = DL.getTypeSizeInBits(StrideExpr->getType());
3163 uint64_t BETypeSizeBits = DL.getTypeSizeInBits(MaxBTC->getType());
3164 const SCEV *CastedStride = StrideExpr;
3165 const SCEV *CastedBECount = MaxBTC;
3166 ScalarEvolution *SE = PSE->getSE();
3167 if (BETypeSizeBits >= StrideTypeSizeBits)
3168 CastedStride = SE->getNoopOrSignExtend(StrideExpr, MaxBTC->getType());
3169 else
3170 CastedBECount = SE->getZeroExtendExpr(MaxBTC, StrideExpr->getType());
3171 const SCEV *StrideMinusBETaken = SE->getMinusSCEV(CastedStride, CastedBECount);
3172 // Since TripCount == BackEdgeTakenCount + 1, checking:
3173 // "Stride >= TripCount" is equivalent to checking:
3174 // Stride - MaxBTC> 0
3175 if (SE->isKnownPositive(StrideMinusBETaken)) {
3176 LLVM_DEBUG(
3177 dbgs() << "LAA: Stride>=TripCount; No point in versioning as the "
3178 "Stride==1 predicate will imply that the loop executes "
3179 "at most once.\n");
3180 return;
3181 }
3182 LLVM_DEBUG(dbgs() << "LAA: Found a strided access that we can version.\n");
3183
3184 // Strip back off the integer cast, and check that our result is a
3185 // SCEVUnknown as we expect.
3186 const SCEV *StrideBase = StrideExpr;
3187 if (const auto *C = dyn_cast<SCEVIntegralCastExpr>(StrideBase))
3188 StrideBase = C->getOperand();
3189 assert(SE->isLoopInvariant(StrideBase, TheLoop) &&
3190 "users of the map rely on the stride being loop invariant");
3191 SymbolicStrides[Ptr] = cast<SCEVUnknown>(StrideBase);
3192}
3193
3195 const TargetTransformInfo *TTI,
3196 const TargetLibraryInfo *TLI, AAResults *AA,
3197 DominatorTree *DT, LoopInfo *LI,
3198 AssumptionCache *AC, bool AllowPartial)
3199 : PSE(std::make_unique<PredicatedScalarEvolution>(*SE, *L)),
3200 PtrRtChecking(nullptr), TheLoop(L), AllowPartial(AllowPartial) {
3201 unsigned MaxTargetVectorWidthInBits = std::numeric_limits<unsigned>::max();
3202 if (TTI && !TTI->enableScalableVectorization())
3203 // Scale the vector width by 2 as rough estimate to also consider
3204 // interleaving.
3205 MaxTargetVectorWidthInBits =
3206 TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector) * 2;
3207
3208 DepChecker = std::make_unique<MemoryDepChecker>(
3209 *PSE, AC, DT, L, SymbolicStrides, MaxTargetVectorWidthInBits, LoopGuards);
3210 PtrRtChecking =
3211 std::make_unique<RuntimePointerChecking>(*DepChecker, SE, LoopGuards);
3212 if (canAnalyzeLoop())
3213 CanVecMem = analyzeLoop(AA, LI, TLI, DT);
3214}
3215
3216void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
3217 if (CanVecMem) {
3218 OS.indent(Depth) << "Memory dependences are safe";
3219 const MemoryDepChecker &DC = getDepChecker();
3220 if (!DC.isSafeForAnyVectorWidth())
3221 OS << " with a maximum safe vector width of "
3222 << DC.getMaxSafeVectorWidthInBits() << " bits";
3224 uint64_t SLDist = DC.getStoreLoadForwardSafeDistanceInBits();
3225 OS << ", with a maximum safe store-load forward width of " << SLDist
3226 << " bits";
3227 }
3228 if (PtrRtChecking->Need)
3229 OS << " with run-time checks";
3230 OS << "\n";
3231 }
3232
3233 if (HasConvergentOp)
3234 OS.indent(Depth) << "Has convergent operation in loop\n";
3235
3236 if (Report)
3237 OS.indent(Depth) << "Report: " << Report->getMsg() << "\n";
3238
3239 if (auto *Dependences = DepChecker->getDependences()) {
3240 OS.indent(Depth) << "Dependences:\n";
3241 for (const auto &Dep : *Dependences) {
3242 Dep.print(OS, Depth + 2, DepChecker->getMemoryInstructions());
3243 OS << "\n";
3244 }
3245 } else
3246 OS.indent(Depth) << "Too many dependences, not recorded\n";
3247
3248 // List the pair of accesses need run-time checks to prove independence.
3249 PtrRtChecking->print(OS, Depth);
3250 if (PtrRtChecking->Need && !HasCompletePtrRtChecking)
3251 OS.indent(Depth) << "Generated run-time checks are incomplete\n";
3252 OS << "\n";
3253
3254 OS.indent(Depth)
3255 << "Non vectorizable stores to invariant address were "
3256 << (HasStoreStoreDependenceInvolvingLoopInvariantAddress ||
3257 HasLoadStoreDependenceInvolvingLoopInvariantAddress
3258 ? ""
3259 : "not ")
3260 << "found in loop.\n";
3261
3262 OS.indent(Depth) << "SCEV assumptions:\n";
3263 PSE->getPredicate().print(OS, Depth);
3264
3265 OS << "\n";
3266
3267 OS.indent(Depth) << "Expressions re-written:\n";
3268 PSE->print(OS, Depth);
3269}
3270
3272 bool AllowPartial) {
3273 const auto &[It, Inserted] = LoopAccessInfoMap.try_emplace(&L);
3274
3275 // We need to create the LoopAccessInfo if either we don't already have one,
3276 // or if it was created with a different value of AllowPartial.
3277 if (Inserted || It->second->hasAllowPartial() != AllowPartial)
3278 It->second = std::make_unique<LoopAccessInfo>(&L, &SE, TTI, TLI, &AA, &DT,
3279 &LI, AC, AllowPartial);
3280
3281 return *It->second;
3282}
3284 // Collect LoopAccessInfo entries that may keep references to IR outside the
3285 // analyzed loop or SCEVs that may have been modified or invalidated. At the
3286 // moment, that is loops requiring memory or SCEV runtime checks, as those cache
3287 // SCEVs, e.g. for pointer expressions.
3288 LoopAccessInfoMap.remove_if([](const auto &Entry) {
3289 const auto &LAI = Entry.second;
3290 return !(LAI->getRuntimePointerChecking()->getChecks().empty() &&
3291 LAI->getPSE().getPredicate().isAlwaysTrue());
3292 });
3293}
3294
3296 Function &F, const PreservedAnalyses &PA,
3297 FunctionAnalysisManager::Invalidator &Inv) {
3298 // Check whether our analysis is preserved.
3299 auto PAC = PA.getChecker<LoopAccessAnalysis>();
3300 if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<Function>>())
3301 // If not, give up now.
3302 return true;
3303
3304 // Check whether the analyses we depend on became invalid for any reason.
3305 // Skip checking TargetLibraryAnalysis as it is immutable and can't become
3306 // invalid.
3307 return Inv.invalidate<AAManager>(F, PA) ||
3308 Inv.invalidate<ScalarEvolutionAnalysis>(F, PA) ||
3309 Inv.invalidate<LoopAnalysis>(F, PA) ||
3310 Inv.invalidate<DominatorTreeAnalysis>(F, PA);
3311}
3312
3315 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
3316 auto &AA = FAM.getResult<AAManager>(F);
3317 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
3318 auto &LI = FAM.getResult<LoopAnalysis>(F);
3319 auto &TTI = FAM.getResult<TargetIRAnalysis>(F);
3320 auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
3321 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
3322 return LoopAccessInfoManager(SE, AA, DT, LI, &TTI, &TLI, &AC);
3323}
3324
3325AnalysisKey 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 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 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:1085
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)
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:698
bool empty() const
Definition Function.h:843
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.
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 void generateChecks(MemoryDepChecker::DepCandidates &DepCands)
Generate the checks and store it.
SmallVector< PointerInfo, 2 > Pointers
Information about the pointers that may require checking.
LLVM_ABI void 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.
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.
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 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 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 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:578
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