xref: /src/contrib/llvm-project/llvm/lib/Analysis/LoopAccessAnalysis.cpp (revision 62987288060ff68c817b7056815aa9fb8ba8ecd7)
15a5ac124SDimitry Andric //===- LoopAccessAnalysis.cpp - Loop Access Analysis Implementation --------==//
25a5ac124SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
65a5ac124SDimitry Andric //
75a5ac124SDimitry Andric //===----------------------------------------------------------------------===//
85a5ac124SDimitry Andric //
95a5ac124SDimitry Andric // The implementation for the loop memory dependence that was originally
105a5ac124SDimitry Andric // developed for the loop vectorizer.
115a5ac124SDimitry Andric //
125a5ac124SDimitry Andric //===----------------------------------------------------------------------===//
135a5ac124SDimitry Andric 
14581a6d85SDimitry Andric #include "llvm/Analysis/LoopAccessAnalysis.h"
15b915e9e0SDimitry Andric #include "llvm/ADT/APInt.h"
16b915e9e0SDimitry Andric #include "llvm/ADT/DenseMap.h"
17b915e9e0SDimitry Andric #include "llvm/ADT/EquivalenceClasses.h"
18b915e9e0SDimitry Andric #include "llvm/ADT/PointerIntPair.h"
19581a6d85SDimitry Andric #include "llvm/ADT/STLExtras.h"
20b915e9e0SDimitry Andric #include "llvm/ADT/SetVector.h"
21b915e9e0SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
22b915e9e0SDimitry Andric #include "llvm/ADT/SmallSet.h"
23b915e9e0SDimitry Andric #include "llvm/ADT/SmallVector.h"
24b915e9e0SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
25b915e9e0SDimitry Andric #include "llvm/Analysis/AliasSetTracker.h"
26581a6d85SDimitry Andric #include "llvm/Analysis/LoopAnalysisManager.h"
275a5ac124SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
28e3b55780SDimitry Andric #include "llvm/Analysis/LoopIterator.h"
29b915e9e0SDimitry Andric #include "llvm/Analysis/MemoryLocation.h"
30044eb2f6SDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h"
31b915e9e0SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
32b915e9e0SDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpressions.h"
335a5ac124SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
34ac9a064cSDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
355a5ac124SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
3601095a5dSDimitry Andric #include "llvm/Analysis/VectorUtils.h"
37b915e9e0SDimitry Andric #include "llvm/IR/BasicBlock.h"
38b915e9e0SDimitry Andric #include "llvm/IR/Constants.h"
39b915e9e0SDimitry Andric #include "llvm/IR/DataLayout.h"
40b915e9e0SDimitry Andric #include "llvm/IR/DebugLoc.h"
41b915e9e0SDimitry Andric #include "llvm/IR/DerivedTypes.h"
425a5ac124SDimitry Andric #include "llvm/IR/DiagnosticInfo.h"
435a5ac124SDimitry Andric #include "llvm/IR/Dominators.h"
44b915e9e0SDimitry Andric #include "llvm/IR/Function.h"
457fa27ce4SDimitry Andric #include "llvm/IR/GetElementPtrTypeIterator.h"
46b915e9e0SDimitry Andric #include "llvm/IR/InstrTypes.h"
47b915e9e0SDimitry Andric #include "llvm/IR/Instruction.h"
48b915e9e0SDimitry Andric #include "llvm/IR/Instructions.h"
49b915e9e0SDimitry Andric #include "llvm/IR/Operator.h"
5001095a5dSDimitry Andric #include "llvm/IR/PassManager.h"
51145449b1SDimitry Andric #include "llvm/IR/PatternMatch.h"
52b915e9e0SDimitry Andric #include "llvm/IR/Type.h"
53b915e9e0SDimitry Andric #include "llvm/IR/Value.h"
54b915e9e0SDimitry Andric #include "llvm/IR/ValueHandle.h"
55b915e9e0SDimitry Andric #include "llvm/Support/Casting.h"
56b915e9e0SDimitry Andric #include "llvm/Support/CommandLine.h"
575a5ac124SDimitry Andric #include "llvm/Support/Debug.h"
58b915e9e0SDimitry Andric #include "llvm/Support/ErrorHandling.h"
595a5ac124SDimitry Andric #include "llvm/Support/raw_ostream.h"
60b915e9e0SDimitry Andric #include <algorithm>
61b915e9e0SDimitry Andric #include <cassert>
62b915e9e0SDimitry Andric #include <cstdint>
63b915e9e0SDimitry Andric #include <iterator>
64b915e9e0SDimitry Andric #include <utility>
65b1c73532SDimitry Andric #include <variant>
66b915e9e0SDimitry Andric #include <vector>
67b915e9e0SDimitry Andric 
685a5ac124SDimitry Andric using namespace llvm;
69145449b1SDimitry Andric using namespace llvm::PatternMatch;
705a5ac124SDimitry Andric 
715a5ac124SDimitry Andric #define DEBUG_TYPE "loop-accesses"
725a5ac124SDimitry Andric 
735a5ac124SDimitry Andric static cl::opt<unsigned, true>
745a5ac124SDimitry Andric VectorizationFactor("force-vector-width", cl::Hidden,
755a5ac124SDimitry Andric                     cl::desc("Sets the SIMD width. Zero is autoselect."),
765a5ac124SDimitry Andric                     cl::location(VectorizerParams::VectorizationFactor));
775a5ac124SDimitry Andric unsigned VectorizerParams::VectorizationFactor;
785a5ac124SDimitry Andric 
795a5ac124SDimitry Andric static cl::opt<unsigned, true>
805a5ac124SDimitry Andric VectorizationInterleave("force-vector-interleave", cl::Hidden,
815a5ac124SDimitry Andric                         cl::desc("Sets the vectorization interleave count. "
825a5ac124SDimitry Andric                                  "Zero is autoselect."),
835a5ac124SDimitry Andric                         cl::location(
845a5ac124SDimitry Andric                             VectorizerParams::VectorizationInterleave));
855a5ac124SDimitry Andric unsigned VectorizerParams::VectorizationInterleave;
865a5ac124SDimitry Andric 
875a5ac124SDimitry Andric static cl::opt<unsigned, true> RuntimeMemoryCheckThreshold(
885a5ac124SDimitry Andric     "runtime-memory-check-threshold", cl::Hidden,
895a5ac124SDimitry Andric     cl::desc("When performing memory disambiguation checks at runtime do not "
905a5ac124SDimitry Andric              "generate more than this number of comparisons (default = 8)."),
915a5ac124SDimitry Andric     cl::location(VectorizerParams::RuntimeMemoryCheckThreshold), cl::init(8));
925a5ac124SDimitry Andric unsigned VectorizerParams::RuntimeMemoryCheckThreshold;
935a5ac124SDimitry Andric 
94eb11fae6SDimitry Andric /// The maximum iterations used to merge memory checks
95ee8648bdSDimitry Andric static cl::opt<unsigned> MemoryCheckMergeThreshold(
96ee8648bdSDimitry Andric     "memory-check-merge-threshold", cl::Hidden,
97ee8648bdSDimitry Andric     cl::desc("Maximum number of comparisons done when trying to merge "
98ee8648bdSDimitry Andric              "runtime memory checks. (default = 100)"),
99ee8648bdSDimitry Andric     cl::init(100));
100ee8648bdSDimitry Andric 
1015a5ac124SDimitry Andric /// Maximum SIMD width.
1025a5ac124SDimitry Andric const unsigned VectorizerParams::MaxVectorWidth = 64;
1035a5ac124SDimitry Andric 
104eb11fae6SDimitry Andric /// We collect dependences up to this threshold.
105dd58ef01SDimitry Andric static cl::opt<unsigned>
106dd58ef01SDimitry Andric     MaxDependences("max-dependences", cl::Hidden,
107dd58ef01SDimitry Andric                    cl::desc("Maximum number of dependences collected by "
1085a5ac124SDimitry Andric                             "loop-access analysis (default = 100)"),
1095a5ac124SDimitry Andric                    cl::init(100));
1105a5ac124SDimitry Andric 
11101095a5dSDimitry Andric /// This enables versioning on the strides of symbolically striding memory
11201095a5dSDimitry Andric /// accesses in code like the following.
11301095a5dSDimitry Andric ///   for (i = 0; i < N; ++i)
11401095a5dSDimitry Andric ///     A[i * Stride1] += B[i * Stride2] ...
11501095a5dSDimitry Andric ///
11601095a5dSDimitry Andric /// Will be roughly translated to
11701095a5dSDimitry Andric ///    if (Stride1 == 1 && Stride2 == 1) {
11801095a5dSDimitry Andric ///      for (i = 0; i < N; i+=4)
11901095a5dSDimitry Andric ///       A[i:i+3] += ...
12001095a5dSDimitry Andric ///    } else
12101095a5dSDimitry Andric ///      ...
12201095a5dSDimitry Andric static cl::opt<bool> EnableMemAccessVersioning(
12301095a5dSDimitry Andric     "enable-mem-access-versioning", cl::init(true), cl::Hidden,
12401095a5dSDimitry Andric     cl::desc("Enable symbolic stride memory access versioning"));
12501095a5dSDimitry Andric 
126eb11fae6SDimitry Andric /// Enable store-to-load forwarding conflict detection. This option can
12701095a5dSDimitry Andric /// be disabled for correctness testing.
12801095a5dSDimitry Andric static cl::opt<bool> EnableForwardingConflictDetection(
12901095a5dSDimitry Andric     "store-to-load-forwarding-conflict-detection", cl::Hidden,
13001095a5dSDimitry Andric     cl::desc("Enable conflict detection in loop-access analysis"),
13101095a5dSDimitry Andric     cl::init(true));
13201095a5dSDimitry Andric 
1334b4fe385SDimitry Andric static cl::opt<unsigned> MaxForkedSCEVDepth(
1344b4fe385SDimitry Andric     "max-forked-scev-depth", cl::Hidden,
1354b4fe385SDimitry Andric     cl::desc("Maximum recursion depth when finding forked SCEVs (default = 5)"),
1364b4fe385SDimitry Andric     cl::init(5));
1374b4fe385SDimitry Andric 
1387fa27ce4SDimitry Andric static cl::opt<bool> SpeculateUnitStride(
1397fa27ce4SDimitry Andric     "laa-speculate-unit-stride", cl::Hidden,
1407fa27ce4SDimitry Andric     cl::desc("Speculate that non-constant strides are unit in LAA"),
1417fa27ce4SDimitry Andric     cl::init(true));
1427fa27ce4SDimitry Andric 
143b1c73532SDimitry Andric static cl::opt<bool, true> HoistRuntimeChecks(
144b1c73532SDimitry Andric     "hoist-runtime-checks", cl::Hidden,
145b1c73532SDimitry Andric     cl::desc(
146b1c73532SDimitry Andric         "Hoist inner loop runtime memory checks to outer loop if possible"),
14799aabd70SDimitry Andric     cl::location(VectorizerParams::HoistRuntimeChecks), cl::init(true));
148b1c73532SDimitry Andric bool VectorizerParams::HoistRuntimeChecks;
149b1c73532SDimitry Andric 
isInterleaveForced()1505a5ac124SDimitry Andric bool VectorizerParams::isInterleaveForced() {
1515a5ac124SDimitry Andric   return ::VectorizationInterleave.getNumOccurrences() > 0;
1525a5ac124SDimitry Andric }
1535a5ac124SDimitry Andric 
replaceSymbolicStrideSCEV(PredicatedScalarEvolution & PSE,const DenseMap<Value *,const SCEV * > & PtrToStride,Value * Ptr)154dd58ef01SDimitry Andric const SCEV *llvm::replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE,
1557fa27ce4SDimitry Andric                                             const DenseMap<Value *, const SCEV *> &PtrToStride,
156c0981da4SDimitry Andric                                             Value *Ptr) {
157dd58ef01SDimitry Andric   const SCEV *OrigSCEV = PSE.getSCEV(Ptr);
1585a5ac124SDimitry Andric 
1595a5ac124SDimitry Andric   // If there is an entry in the map return the SCEV of the pointer with the
1605a5ac124SDimitry Andric   // symbolic stride replaced by one.
1617fa27ce4SDimitry Andric   DenseMap<Value *, const SCEV *>::const_iterator SI = PtrToStride.find(Ptr);
162b60736ecSDimitry Andric   if (SI == PtrToStride.end())
163b60736ecSDimitry Andric     // For a non-symbolic stride, just return the original expression.
164b60736ecSDimitry Andric     return OrigSCEV;
1655a5ac124SDimitry Andric 
1667fa27ce4SDimitry Andric   const SCEV *StrideSCEV = SI->second;
1677fa27ce4SDimitry Andric   // Note: This assert is both overly strong and overly weak.  The actual
1687fa27ce4SDimitry Andric   // invariant here is that StrideSCEV should be loop invariant.  The only
1697fa27ce4SDimitry Andric   // such invariant strides we happen to speculate right now are unknowns
1707fa27ce4SDimitry Andric   // and thus this is a reasonable proxy of the actual invariant.
1717fa27ce4SDimitry Andric   assert(isa<SCEVUnknown>(StrideSCEV) && "shouldn't be in map");
1725a5ac124SDimitry Andric 
173dd58ef01SDimitry Andric   ScalarEvolution *SE = PSE.getSE();
1747fa27ce4SDimitry Andric   const auto *CT = SE->getOne(StrideSCEV->getType());
1757fa27ce4SDimitry Andric   PSE.addPredicate(*SE->getEqualPredicate(StrideSCEV, CT));
176dd58ef01SDimitry Andric   auto *Expr = PSE.getSCEV(Ptr);
177dd58ef01SDimitry Andric 
178eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV
179eb11fae6SDimitry Andric 	     << " by: " << *Expr << "\n");
180dd58ef01SDimitry Andric   return Expr;
1815a5ac124SDimitry Andric }
1825a5ac124SDimitry Andric 
RuntimeCheckingPtrGroup(unsigned Index,RuntimePointerChecking & RtCheck)183cfca06d7SDimitry Andric RuntimeCheckingPtrGroup::RuntimeCheckingPtrGroup(
184cfca06d7SDimitry Andric     unsigned Index, RuntimePointerChecking &RtCheck)
185344a3780SDimitry Andric     : High(RtCheck.Pointers[Index].End), Low(RtCheck.Pointers[Index].Start),
186344a3780SDimitry Andric       AddressSpace(RtCheck.Pointers[Index]
187344a3780SDimitry Andric                        .PointerValue->getType()
188145449b1SDimitry Andric                        ->getPointerAddressSpace()),
189145449b1SDimitry Andric       NeedsFreeze(RtCheck.Pointers[Index].NeedsFreeze) {
190cfca06d7SDimitry Andric   Members.push_back(Index);
191cfca06d7SDimitry Andric }
192cfca06d7SDimitry Andric 
1936449741fSDimitry Andric /// Calculate Start and End points of memory access.
1946449741fSDimitry Andric /// Let's assume A is the first access and B is a memory access on N-th loop
1956449741fSDimitry Andric /// iteration. Then B is calculated as:
1966449741fSDimitry Andric ///   B = A + Step*N .
1976449741fSDimitry Andric /// Step value may be positive or negative.
1986449741fSDimitry Andric /// N is a calculated back-edge taken count:
1996449741fSDimitry Andric ///     N = (TripCount > 0) ? RoundDown(TripCount -1 , VF) : 0
2006449741fSDimitry Andric /// Start and End points are calculated in the following way:
2016449741fSDimitry Andric /// Start = UMIN(A, B) ; End = UMAX(A, B) + SizeOfElt,
2026449741fSDimitry Andric /// where SizeOfElt is the size of single memory access in bytes.
2036449741fSDimitry Andric ///
2046449741fSDimitry Andric /// There is no conflict when the intervals are disjoint:
2056449741fSDimitry Andric /// NoConflict = (P2.Start >= P1.End) || (P1.Start >= P2.End)
getStartAndEndForAccess(const Loop * Lp,const SCEV * PtrExpr,Type * AccessTy,PredicatedScalarEvolution & PSE,DenseMap<std::pair<const SCEV *,Type * >,std::pair<const SCEV *,const SCEV * >> & PointerBounds)206ac9a064cSDimitry Andric static std::pair<const SCEV *, const SCEV *> getStartAndEndForAccess(
207ac9a064cSDimitry Andric     const Loop *Lp, const SCEV *PtrExpr, Type *AccessTy,
208145449b1SDimitry Andric     PredicatedScalarEvolution &PSE,
209ac9a064cSDimitry Andric     DenseMap<std::pair<const SCEV *, Type *>,
210ac9a064cSDimitry Andric              std::pair<const SCEV *, const SCEV *>> &PointerBounds) {
21101095a5dSDimitry Andric   ScalarEvolution *SE = PSE.getSE();
21201095a5dSDimitry Andric 
213ac9a064cSDimitry Andric   auto [Iter, Ins] = PointerBounds.insert(
214ac9a064cSDimitry Andric       {{PtrExpr, AccessTy},
215ac9a064cSDimitry Andric        {SE->getCouldNotCompute(), SE->getCouldNotCompute()}});
216ac9a064cSDimitry Andric   if (!Ins)
217ac9a064cSDimitry Andric     return Iter->second;
218ac9a064cSDimitry Andric 
21901095a5dSDimitry Andric   const SCEV *ScStart;
22001095a5dSDimitry Andric   const SCEV *ScEnd;
22101095a5dSDimitry Andric 
222145449b1SDimitry Andric   if (SE->isLoopInvariant(PtrExpr, Lp)) {
223145449b1SDimitry Andric     ScStart = ScEnd = PtrExpr;
224ac9a064cSDimitry Andric   } else if (auto *AR = dyn_cast<SCEVAddRecExpr>(PtrExpr)) {
225ac9a064cSDimitry Andric     const SCEV *Ex = PSE.getSymbolicMaxBackedgeTakenCount();
226dd58ef01SDimitry Andric 
22701095a5dSDimitry Andric     ScStart = AR->getStart();
22801095a5dSDimitry Andric     ScEnd = AR->evaluateAtIteration(Ex, *SE);
229dd58ef01SDimitry Andric     const SCEV *Step = AR->getStepRecurrence(*SE);
230dd58ef01SDimitry Andric 
231dd58ef01SDimitry Andric     // For expressions with negative step, the upper bound is ScStart and the
232dd58ef01SDimitry Andric     // lower bound is ScEnd.
23301095a5dSDimitry Andric     if (const auto *CStep = dyn_cast<SCEVConstant>(Step)) {
234dd58ef01SDimitry Andric       if (CStep->getValue()->isNegative())
235dd58ef01SDimitry Andric         std::swap(ScStart, ScEnd);
236dd58ef01SDimitry Andric     } else {
2376449741fSDimitry Andric       // Fallback case: the step is not constant, but we can still
238dd58ef01SDimitry Andric       // get the upper and lower bounds of the interval by using min/max
239dd58ef01SDimitry Andric       // expressions.
240dd58ef01SDimitry Andric       ScStart = SE->getUMinExpr(ScStart, ScEnd);
241dd58ef01SDimitry Andric       ScEnd = SE->getUMaxExpr(AR->getStart(), ScEnd);
2425a5ac124SDimitry Andric     }
243ac9a064cSDimitry Andric   } else
244ac9a064cSDimitry Andric     return {SE->getCouldNotCompute(), SE->getCouldNotCompute()};
245ac9a064cSDimitry Andric 
2467fa27ce4SDimitry Andric   assert(SE->isLoopInvariant(ScStart, Lp) && "ScStart needs to be invariant");
2477fa27ce4SDimitry Andric   assert(SE->isLoopInvariant(ScEnd, Lp)&& "ScEnd needs to be invariant");
2487fa27ce4SDimitry Andric 
2496449741fSDimitry Andric   // Add the size of the pointed element to ScEnd.
250ac9a064cSDimitry Andric   auto &DL = Lp->getHeader()->getDataLayout();
251ac9a064cSDimitry Andric   Type *IdxTy = DL.getIndexType(PtrExpr->getType());
252145449b1SDimitry Andric   const SCEV *EltSizeSCEV = SE->getStoreSizeOfExpr(IdxTy, AccessTy);
2536449741fSDimitry Andric   ScEnd = SE->getAddExpr(ScEnd, EltSizeSCEV);
2545a5ac124SDimitry Andric 
255ac9a064cSDimitry Andric   Iter->second = {ScStart, ScEnd};
256ac9a064cSDimitry Andric   return Iter->second;
257ac9a064cSDimitry Andric }
258ac9a064cSDimitry Andric 
259ac9a064cSDimitry Andric /// Calculate Start and End points of memory access using
260ac9a064cSDimitry Andric /// getStartAndEndForAccess.
insert(Loop * Lp,Value * Ptr,const SCEV * PtrExpr,Type * AccessTy,bool WritePtr,unsigned DepSetId,unsigned ASId,PredicatedScalarEvolution & PSE,bool NeedsFreeze)261ac9a064cSDimitry Andric void RuntimePointerChecking::insert(Loop *Lp, Value *Ptr, const SCEV *PtrExpr,
262ac9a064cSDimitry Andric                                     Type *AccessTy, bool WritePtr,
263ac9a064cSDimitry Andric                                     unsigned DepSetId, unsigned ASId,
264ac9a064cSDimitry Andric                                     PredicatedScalarEvolution &PSE,
265ac9a064cSDimitry Andric                                     bool NeedsFreeze) {
266ac9a064cSDimitry Andric   const auto &[ScStart, ScEnd] = getStartAndEndForAccess(
267ac9a064cSDimitry Andric       Lp, PtrExpr, AccessTy, PSE, DC.getPointerBounds());
268ac9a064cSDimitry Andric   assert(!isa<SCEVCouldNotCompute>(ScStart) &&
269ac9a064cSDimitry Andric          !isa<SCEVCouldNotCompute>(ScEnd) &&
270ac9a064cSDimitry Andric          "must be able to compute both start and end expressions");
271145449b1SDimitry Andric   Pointers.emplace_back(Ptr, ScStart, ScEnd, WritePtr, DepSetId, ASId, PtrExpr,
272145449b1SDimitry Andric                         NeedsFreeze);
273dd58ef01SDimitry Andric }
274dd58ef01SDimitry Andric 
tryToCreateDiffCheck(const RuntimeCheckingPtrGroup & CGI,const RuntimeCheckingPtrGroup & CGJ)275ac9a064cSDimitry Andric bool RuntimePointerChecking::tryToCreateDiffCheck(
276145449b1SDimitry Andric     const RuntimeCheckingPtrGroup &CGI, const RuntimeCheckingPtrGroup &CGJ) {
277145449b1SDimitry Andric   // If either group contains multiple different pointers, bail out.
278145449b1SDimitry Andric   // TODO: Support multiple pointers by using the minimum or maximum pointer,
279145449b1SDimitry Andric   // depending on src & sink.
280ac9a064cSDimitry Andric   if (CGI.Members.size() != 1 || CGJ.Members.size() != 1)
281ac9a064cSDimitry Andric     return false;
282145449b1SDimitry Andric 
283145449b1SDimitry Andric   PointerInfo *Src = &Pointers[CGI.Members[0]];
284145449b1SDimitry Andric   PointerInfo *Sink = &Pointers[CGJ.Members[0]];
285145449b1SDimitry Andric 
286145449b1SDimitry Andric   // If either pointer is read and written, multiple checks may be needed. Bail
287145449b1SDimitry Andric   // out.
288145449b1SDimitry Andric   if (!DC.getOrderForAccess(Src->PointerValue, !Src->IsWritePtr).empty() ||
289ac9a064cSDimitry Andric       !DC.getOrderForAccess(Sink->PointerValue, !Sink->IsWritePtr).empty())
290ac9a064cSDimitry Andric     return false;
291145449b1SDimitry Andric 
292145449b1SDimitry Andric   ArrayRef<unsigned> AccSrc =
293145449b1SDimitry Andric       DC.getOrderForAccess(Src->PointerValue, Src->IsWritePtr);
294145449b1SDimitry Andric   ArrayRef<unsigned> AccSink =
295145449b1SDimitry Andric       DC.getOrderForAccess(Sink->PointerValue, Sink->IsWritePtr);
296145449b1SDimitry Andric   // If either pointer is accessed multiple times, there may not be a clear
297145449b1SDimitry Andric   // src/sink relation. Bail out for now.
298ac9a064cSDimitry Andric   if (AccSrc.size() != 1 || AccSink.size() != 1)
299ac9a064cSDimitry Andric     return false;
300ac9a064cSDimitry Andric 
301145449b1SDimitry Andric   // If the sink is accessed before src, swap src/sink.
302145449b1SDimitry Andric   if (AccSink[0] < AccSrc[0])
303145449b1SDimitry Andric     std::swap(Src, Sink);
304145449b1SDimitry Andric 
305145449b1SDimitry Andric   auto *SrcAR = dyn_cast<SCEVAddRecExpr>(Src->Expr);
306145449b1SDimitry Andric   auto *SinkAR = dyn_cast<SCEVAddRecExpr>(Sink->Expr);
307e3b55780SDimitry Andric   if (!SrcAR || !SinkAR || SrcAR->getLoop() != DC.getInnermostLoop() ||
308ac9a064cSDimitry Andric       SinkAR->getLoop() != DC.getInnermostLoop())
309ac9a064cSDimitry Andric     return false;
310145449b1SDimitry Andric 
311145449b1SDimitry Andric   SmallVector<Instruction *, 4> SrcInsts =
312145449b1SDimitry Andric       DC.getInstructionsForAccess(Src->PointerValue, Src->IsWritePtr);
313145449b1SDimitry Andric   SmallVector<Instruction *, 4> SinkInsts =
314145449b1SDimitry Andric       DC.getInstructionsForAccess(Sink->PointerValue, Sink->IsWritePtr);
315145449b1SDimitry Andric   Type *SrcTy = getLoadStoreType(SrcInsts[0]);
316145449b1SDimitry Andric   Type *DstTy = getLoadStoreType(SinkInsts[0]);
317ac9a064cSDimitry Andric   if (isa<ScalableVectorType>(SrcTy) || isa<ScalableVectorType>(DstTy))
318ac9a064cSDimitry Andric     return false;
319ac9a064cSDimitry Andric 
320e3b55780SDimitry Andric   const DataLayout &DL =
321ac9a064cSDimitry Andric       SinkAR->getLoop()->getHeader()->getDataLayout();
322145449b1SDimitry Andric   unsigned AllocSize =
323145449b1SDimitry Andric       std::max(DL.getTypeAllocSize(SrcTy), DL.getTypeAllocSize(DstTy));
324145449b1SDimitry Andric 
325145449b1SDimitry Andric   // Only matching constant steps matching the AllocSize are supported at the
326145449b1SDimitry Andric   // moment. This simplifies the difference computation. Can be extended in the
327145449b1SDimitry Andric   // future.
328145449b1SDimitry Andric   auto *Step = dyn_cast<SCEVConstant>(SinkAR->getStepRecurrence(*SE));
329145449b1SDimitry Andric   if (!Step || Step != SrcAR->getStepRecurrence(*SE) ||
330ac9a064cSDimitry Andric       Step->getAPInt().abs() != AllocSize)
331ac9a064cSDimitry Andric     return false;
332145449b1SDimitry Andric 
333e3b55780SDimitry Andric   IntegerType *IntTy =
334e3b55780SDimitry Andric       IntegerType::get(Src->PointerValue->getContext(),
335e3b55780SDimitry Andric                        DL.getPointerSizeInBits(CGI.AddressSpace));
336e3b55780SDimitry Andric 
337145449b1SDimitry Andric   // When counting down, the dependence distance needs to be swapped.
338145449b1SDimitry Andric   if (Step->getValue()->isNegative())
339145449b1SDimitry Andric     std::swap(SinkAR, SrcAR);
340145449b1SDimitry Andric 
341145449b1SDimitry Andric   const SCEV *SinkStartInt = SE->getPtrToIntExpr(SinkAR->getStart(), IntTy);
342145449b1SDimitry Andric   const SCEV *SrcStartInt = SE->getPtrToIntExpr(SrcAR->getStart(), IntTy);
343145449b1SDimitry Andric   if (isa<SCEVCouldNotCompute>(SinkStartInt) ||
344ac9a064cSDimitry Andric       isa<SCEVCouldNotCompute>(SrcStartInt))
345ac9a064cSDimitry Andric     return false;
346b1c73532SDimitry Andric 
347b1c73532SDimitry Andric   const Loop *InnerLoop = SrcAR->getLoop();
348b1c73532SDimitry Andric   // If the start values for both Src and Sink also vary according to an outer
349b1c73532SDimitry Andric   // loop, then it's probably better to avoid creating diff checks because
350b1c73532SDimitry Andric   // they may not be hoisted. We should instead let llvm::addRuntimeChecks
351b1c73532SDimitry Andric   // do the expanded full range overlap checks, which can be hoisted.
352b1c73532SDimitry Andric   if (HoistRuntimeChecks && InnerLoop->getParentLoop() &&
353b1c73532SDimitry Andric       isa<SCEVAddRecExpr>(SinkStartInt) && isa<SCEVAddRecExpr>(SrcStartInt)) {
354b1c73532SDimitry Andric     auto *SrcStartAR = cast<SCEVAddRecExpr>(SrcStartInt);
355b1c73532SDimitry Andric     auto *SinkStartAR = cast<SCEVAddRecExpr>(SinkStartInt);
356b1c73532SDimitry Andric     const Loop *StartARLoop = SrcStartAR->getLoop();
357b1c73532SDimitry Andric     if (StartARLoop == SinkStartAR->getLoop() &&
358312c0ed1SDimitry Andric         StartARLoop == InnerLoop->getParentLoop() &&
359312c0ed1SDimitry Andric         // If the diff check would already be loop invariant (due to the
360312c0ed1SDimitry Andric         // recurrences being the same), then we prefer to keep the diff checks
361312c0ed1SDimitry Andric         // because they are cheaper.
362312c0ed1SDimitry Andric         SrcStartAR->getStepRecurrence(*SE) !=
363312c0ed1SDimitry Andric             SinkStartAR->getStepRecurrence(*SE)) {
364b1c73532SDimitry Andric       LLVM_DEBUG(dbgs() << "LAA: Not creating diff runtime check, since these "
365b1c73532SDimitry Andric                            "cannot be hoisted out of the outer loop\n");
366ac9a064cSDimitry Andric       return false;
367b1c73532SDimitry Andric     }
368b1c73532SDimitry Andric   }
369b1c73532SDimitry Andric 
370b1c73532SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: Creating diff runtime check for:\n"
371b1c73532SDimitry Andric                     << "SrcStart: " << *SrcStartInt << '\n'
372b1c73532SDimitry Andric                     << "SinkStartInt: " << *SinkStartInt << '\n');
373145449b1SDimitry Andric   DiffChecks.emplace_back(SrcStartInt, SinkStartInt, AllocSize,
374145449b1SDimitry Andric                           Src->NeedsFreeze || Sink->NeedsFreeze);
375ac9a064cSDimitry Andric   return true;
376145449b1SDimitry Andric }
377145449b1SDimitry Andric 
generateChecks()378145449b1SDimitry Andric SmallVector<RuntimePointerCheck, 4> RuntimePointerChecking::generateChecks() {
379cfca06d7SDimitry Andric   SmallVector<RuntimePointerCheck, 4> Checks;
380dd58ef01SDimitry Andric 
381dd58ef01SDimitry Andric   for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
382dd58ef01SDimitry Andric     for (unsigned J = I + 1; J < CheckingGroups.size(); ++J) {
383cfca06d7SDimitry Andric       const RuntimeCheckingPtrGroup &CGI = CheckingGroups[I];
384cfca06d7SDimitry Andric       const RuntimeCheckingPtrGroup &CGJ = CheckingGroups[J];
385dd58ef01SDimitry Andric 
386145449b1SDimitry Andric       if (needsChecking(CGI, CGJ)) {
387ac9a064cSDimitry Andric         CanUseDiffCheck = CanUseDiffCheck && tryToCreateDiffCheck(CGI, CGJ);
388dd58ef01SDimitry Andric         Checks.push_back(std::make_pair(&CGI, &CGJ));
389dd58ef01SDimitry Andric       }
390dd58ef01SDimitry Andric     }
391145449b1SDimitry Andric   }
392dd58ef01SDimitry Andric   return Checks;
393dd58ef01SDimitry Andric }
394dd58ef01SDimitry Andric 
generateChecks(MemoryDepChecker::DepCandidates & DepCands,bool UseDependencies)395dd58ef01SDimitry Andric void RuntimePointerChecking::generateChecks(
396dd58ef01SDimitry Andric     MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
397dd58ef01SDimitry Andric   assert(Checks.empty() && "Checks is not empty");
398dd58ef01SDimitry Andric   groupChecks(DepCands, UseDependencies);
399dd58ef01SDimitry Andric   Checks = generateChecks();
400dd58ef01SDimitry Andric }
401dd58ef01SDimitry Andric 
needsChecking(const RuntimeCheckingPtrGroup & M,const RuntimeCheckingPtrGroup & N) const402cfca06d7SDimitry Andric bool RuntimePointerChecking::needsChecking(
403cfca06d7SDimitry Andric     const RuntimeCheckingPtrGroup &M, const RuntimeCheckingPtrGroup &N) const {
404ac9a064cSDimitry Andric   for (const auto &I : M.Members)
405ac9a064cSDimitry Andric     for (const auto &J : N.Members)
406ac9a064cSDimitry Andric       if (needsChecking(I, J))
407ee8648bdSDimitry Andric         return true;
408ee8648bdSDimitry Andric   return false;
409ee8648bdSDimitry Andric }
410ee8648bdSDimitry Andric 
411ee8648bdSDimitry Andric /// Compare \p I and \p J and return the minimum.
412ee8648bdSDimitry Andric /// Return nullptr in case we couldn't find an answer.
getMinFromExprs(const SCEV * I,const SCEV * J,ScalarEvolution * SE)413ee8648bdSDimitry Andric static const SCEV *getMinFromExprs(const SCEV *I, const SCEV *J,
414ee8648bdSDimitry Andric                                    ScalarEvolution *SE) {
415ee8648bdSDimitry Andric   const SCEV *Diff = SE->getMinusSCEV(J, I);
416ee8648bdSDimitry Andric   const SCEVConstant *C = dyn_cast<const SCEVConstant>(Diff);
417ee8648bdSDimitry Andric 
418ee8648bdSDimitry Andric   if (!C)
419ee8648bdSDimitry Andric     return nullptr;
420ac9a064cSDimitry Andric   return C->getValue()->isNegative() ? J : I;
421ee8648bdSDimitry Andric }
422ee8648bdSDimitry Andric 
addPointer(unsigned Index,RuntimePointerChecking & RtCheck)423344a3780SDimitry Andric bool RuntimeCheckingPtrGroup::addPointer(unsigned Index,
424344a3780SDimitry Andric                                          RuntimePointerChecking &RtCheck) {
425344a3780SDimitry Andric   return addPointer(
426344a3780SDimitry Andric       Index, RtCheck.Pointers[Index].Start, RtCheck.Pointers[Index].End,
427344a3780SDimitry Andric       RtCheck.Pointers[Index].PointerValue->getType()->getPointerAddressSpace(),
428145449b1SDimitry Andric       RtCheck.Pointers[Index].NeedsFreeze, *RtCheck.SE);
429344a3780SDimitry Andric }
430344a3780SDimitry Andric 
addPointer(unsigned Index,const SCEV * Start,const SCEV * End,unsigned AS,bool NeedsFreeze,ScalarEvolution & SE)431344a3780SDimitry Andric bool RuntimeCheckingPtrGroup::addPointer(unsigned Index, const SCEV *Start,
432344a3780SDimitry Andric                                          const SCEV *End, unsigned AS,
433145449b1SDimitry Andric                                          bool NeedsFreeze,
434344a3780SDimitry Andric                                          ScalarEvolution &SE) {
435344a3780SDimitry Andric   assert(AddressSpace == AS &&
436344a3780SDimitry Andric          "all pointers in a checking group must be in the same address space");
437ee8648bdSDimitry Andric 
438ee8648bdSDimitry Andric   // Compare the starts and ends with the known minimum and maximum
439ee8648bdSDimitry Andric   // of this set. We need to know how we compare against the min/max
440ee8648bdSDimitry Andric   // of the set in order to be able to emit memchecks.
441344a3780SDimitry Andric   const SCEV *Min0 = getMinFromExprs(Start, Low, &SE);
442ee8648bdSDimitry Andric   if (!Min0)
443ee8648bdSDimitry Andric     return false;
444ee8648bdSDimitry Andric 
445344a3780SDimitry Andric   const SCEV *Min1 = getMinFromExprs(End, High, &SE);
446ee8648bdSDimitry Andric   if (!Min1)
447ee8648bdSDimitry Andric     return false;
448ee8648bdSDimitry Andric 
449ee8648bdSDimitry Andric   // Update the low bound  expression if we've found a new min value.
450ee8648bdSDimitry Andric   if (Min0 == Start)
451ee8648bdSDimitry Andric     Low = Start;
452ee8648bdSDimitry Andric 
453ee8648bdSDimitry Andric   // Update the high bound expression if we've found a new max value.
454ee8648bdSDimitry Andric   if (Min1 != End)
455ee8648bdSDimitry Andric     High = End;
456ee8648bdSDimitry Andric 
457ee8648bdSDimitry Andric   Members.push_back(Index);
458145449b1SDimitry Andric   this->NeedsFreeze |= NeedsFreeze;
459ee8648bdSDimitry Andric   return true;
460ee8648bdSDimitry Andric }
461ee8648bdSDimitry Andric 
groupChecks(MemoryDepChecker::DepCandidates & DepCands,bool UseDependencies)462ee8648bdSDimitry Andric void RuntimePointerChecking::groupChecks(
463ee8648bdSDimitry Andric     MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
464ee8648bdSDimitry Andric   // We build the groups from dependency candidates equivalence classes
465ee8648bdSDimitry Andric   // because:
466ee8648bdSDimitry Andric   //    - We know that pointers in the same equivalence class share
467ee8648bdSDimitry Andric   //      the same underlying object and therefore there is a chance
468ee8648bdSDimitry Andric   //      that we can compare pointers
469ee8648bdSDimitry Andric   //    - We wouldn't be able to merge two pointers for which we need
470ee8648bdSDimitry Andric   //      to emit a memcheck. The classes in DepCands are already
471ee8648bdSDimitry Andric   //      conveniently built such that no two pointers in the same
472ee8648bdSDimitry Andric   //      class need checking against each other.
473ee8648bdSDimitry Andric 
474ee8648bdSDimitry Andric   // We use the following (greedy) algorithm to construct the groups
475ee8648bdSDimitry Andric   // For every pointer in the equivalence class:
476ee8648bdSDimitry Andric   //   For each existing group:
477ee8648bdSDimitry Andric   //   - if the difference between this pointer and the min/max bounds
478ee8648bdSDimitry Andric   //     of the group is a constant, then make the pointer part of the
479ee8648bdSDimitry Andric   //     group and update the min/max bounds of that group as required.
480ee8648bdSDimitry Andric 
481ee8648bdSDimitry Andric   CheckingGroups.clear();
482ee8648bdSDimitry Andric 
483dd58ef01SDimitry Andric   // If we need to check two pointers to the same underlying object
484dd58ef01SDimitry Andric   // with a non-constant difference, we shouldn't perform any pointer
485dd58ef01SDimitry Andric   // grouping with those pointers. This is because we can easily get
486dd58ef01SDimitry Andric   // into cases where the resulting check would return false, even when
487dd58ef01SDimitry Andric   // the accesses are safe.
488dd58ef01SDimitry Andric   //
489dd58ef01SDimitry Andric   // The following example shows this:
490dd58ef01SDimitry Andric   // for (i = 0; i < 1000; ++i)
491dd58ef01SDimitry Andric   //   a[5000 + i * m] = a[i] + a[i + 9000]
492dd58ef01SDimitry Andric   //
493dd58ef01SDimitry Andric   // Here grouping gives a check of (5000, 5000 + 1000 * m) against
494dd58ef01SDimitry Andric   // (0, 10000) which is always false. However, if m is 1, there is no
495dd58ef01SDimitry Andric   // dependence. Not grouping the checks for a[i] and a[i + 9000] allows
496dd58ef01SDimitry Andric   // us to perform an accurate check in this case.
497dd58ef01SDimitry Andric   //
498dd58ef01SDimitry Andric   // The above case requires that we have an UnknownDependence between
499dd58ef01SDimitry Andric   // accesses to the same underlying object. This cannot happen unless
500d8e91e46SDimitry Andric   // FoundNonConstantDistanceDependence is set, and therefore UseDependencies
501dd58ef01SDimitry Andric   // is also false. In this case we will use the fallback path and create
502dd58ef01SDimitry Andric   // separate checking groups for all pointers.
503dd58ef01SDimitry Andric 
504ee8648bdSDimitry Andric   // If we don't have the dependency partitions, construct a new
505dd58ef01SDimitry Andric   // checking pointer group for each pointer. This is also required
506dd58ef01SDimitry Andric   // for correctness, because in this case we can have checking between
507dd58ef01SDimitry Andric   // pointers to the same underlying object.
508ee8648bdSDimitry Andric   if (!UseDependencies) {
509ee8648bdSDimitry Andric     for (unsigned I = 0; I < Pointers.size(); ++I)
510cfca06d7SDimitry Andric       CheckingGroups.push_back(RuntimeCheckingPtrGroup(I, *this));
511ee8648bdSDimitry Andric     return;
512ee8648bdSDimitry Andric   }
513ee8648bdSDimitry Andric 
514ee8648bdSDimitry Andric   unsigned TotalComparisons = 0;
515ee8648bdSDimitry Andric 
516145449b1SDimitry Andric   DenseMap<Value *, SmallVector<unsigned>> PositionMap;
517145449b1SDimitry Andric   for (unsigned Index = 0; Index < Pointers.size(); ++Index) {
518ac9a064cSDimitry Andric     auto [It, _] = PositionMap.insert({Pointers[Index].PointerValue, {}});
519ac9a064cSDimitry Andric     It->second.push_back(Index);
520145449b1SDimitry Andric   }
521ee8648bdSDimitry Andric 
522ee8648bdSDimitry Andric   // We need to keep track of what pointers we've already seen so we
523ee8648bdSDimitry Andric   // don't process them twice.
524ee8648bdSDimitry Andric   SmallSet<unsigned, 2> Seen;
525ee8648bdSDimitry Andric 
526dd58ef01SDimitry Andric   // Go through all equivalence classes, get the "pointer check groups"
527ee8648bdSDimitry Andric   // and add them to the overall solution. We use the order in which accesses
528ee8648bdSDimitry Andric   // appear in 'Pointers' to enforce determinism.
529ee8648bdSDimitry Andric   for (unsigned I = 0; I < Pointers.size(); ++I) {
530ee8648bdSDimitry Andric     // We've seen this pointer before, and therefore already processed
531ee8648bdSDimitry Andric     // its equivalence class.
532ee8648bdSDimitry Andric     if (Seen.count(I))
533ee8648bdSDimitry Andric       continue;
534ee8648bdSDimitry Andric 
535ee8648bdSDimitry Andric     MemoryDepChecker::MemAccessInfo Access(Pointers[I].PointerValue,
536ee8648bdSDimitry Andric                                            Pointers[I].IsWritePtr);
537ee8648bdSDimitry Andric 
538cfca06d7SDimitry Andric     SmallVector<RuntimeCheckingPtrGroup, 2> Groups;
539ee8648bdSDimitry Andric     auto LeaderI = DepCands.findValue(DepCands.getLeaderValue(Access));
540ee8648bdSDimitry Andric 
541ee8648bdSDimitry Andric     // Because DepCands is constructed by visiting accesses in the order in
542ee8648bdSDimitry Andric     // which they appear in alias sets (which is deterministic) and the
543ee8648bdSDimitry Andric     // iteration order within an equivalence class member is only dependent on
544ee8648bdSDimitry Andric     // the order in which unions and insertions are performed on the
545ee8648bdSDimitry Andric     // equivalence class, the iteration order is deterministic.
546ee8648bdSDimitry Andric     for (auto MI = DepCands.member_begin(LeaderI), ME = DepCands.member_end();
547ee8648bdSDimitry Andric          MI != ME; ++MI) {
548b60736ecSDimitry Andric       auto PointerI = PositionMap.find(MI->getPointer());
549b60736ecSDimitry Andric       assert(PointerI != PositionMap.end() &&
550b60736ecSDimitry Andric              "pointer in equivalence class not found in PositionMap");
551145449b1SDimitry Andric       for (unsigned Pointer : PointerI->second) {
552ee8648bdSDimitry Andric         bool Merged = false;
553ee8648bdSDimitry Andric         // Mark this pointer as seen.
554ee8648bdSDimitry Andric         Seen.insert(Pointer);
555ee8648bdSDimitry Andric 
556ee8648bdSDimitry Andric         // Go through all the existing sets and see if we can find one
557ee8648bdSDimitry Andric         // which can include this pointer.
558cfca06d7SDimitry Andric         for (RuntimeCheckingPtrGroup &Group : Groups) {
559ee8648bdSDimitry Andric           // Don't perform more than a certain amount of comparisons.
560ee8648bdSDimitry Andric           // This should limit the cost of grouping the pointers to something
561ee8648bdSDimitry Andric           // reasonable.  If we do end up hitting this threshold, the algorithm
562ee8648bdSDimitry Andric           // will create separate groups for all remaining pointers.
563ee8648bdSDimitry Andric           if (TotalComparisons > MemoryCheckMergeThreshold)
564ee8648bdSDimitry Andric             break;
565ee8648bdSDimitry Andric 
566ee8648bdSDimitry Andric           TotalComparisons++;
567ee8648bdSDimitry Andric 
568344a3780SDimitry Andric           if (Group.addPointer(Pointer, *this)) {
569ee8648bdSDimitry Andric             Merged = true;
570ee8648bdSDimitry Andric             break;
571ee8648bdSDimitry Andric           }
572ee8648bdSDimitry Andric         }
573ee8648bdSDimitry Andric 
574ee8648bdSDimitry Andric         if (!Merged)
575ee8648bdSDimitry Andric           // We couldn't add this pointer to any existing set or the threshold
576ee8648bdSDimitry Andric           // for the number of comparisons has been reached. Create a new group
577ee8648bdSDimitry Andric           // to hold the current pointer.
578cfca06d7SDimitry Andric           Groups.push_back(RuntimeCheckingPtrGroup(Pointer, *this));
579ee8648bdSDimitry Andric       }
580145449b1SDimitry Andric     }
581ee8648bdSDimitry Andric 
582ee8648bdSDimitry Andric     // We've computed the grouped checks for this partition.
583ee8648bdSDimitry Andric     // Save the results and continue with the next one.
584d8e91e46SDimitry Andric     llvm::copy(Groups, std::back_inserter(CheckingGroups));
585ee8648bdSDimitry Andric   }
586ee8648bdSDimitry Andric }
587ee8648bdSDimitry Andric 
arePointersInSamePartition(const SmallVectorImpl<int> & PtrToPartition,unsigned PtrIdx1,unsigned PtrIdx2)588dd58ef01SDimitry Andric bool RuntimePointerChecking::arePointersInSamePartition(
589dd58ef01SDimitry Andric     const SmallVectorImpl<int> &PtrToPartition, unsigned PtrIdx1,
590dd58ef01SDimitry Andric     unsigned PtrIdx2) {
591dd58ef01SDimitry Andric   return (PtrToPartition[PtrIdx1] != -1 &&
592dd58ef01SDimitry Andric           PtrToPartition[PtrIdx1] == PtrToPartition[PtrIdx2]);
593dd58ef01SDimitry Andric }
594dd58ef01SDimitry Andric 
needsChecking(unsigned I,unsigned J) const595dd58ef01SDimitry Andric bool RuntimePointerChecking::needsChecking(unsigned I, unsigned J) const {
596ee8648bdSDimitry Andric   const PointerInfo &PointerI = Pointers[I];
597ee8648bdSDimitry Andric   const PointerInfo &PointerJ = Pointers[J];
598ee8648bdSDimitry Andric 
5995a5ac124SDimitry Andric   // No need to check if two readonly pointers intersect.
600ee8648bdSDimitry Andric   if (!PointerI.IsWritePtr && !PointerJ.IsWritePtr)
6015a5ac124SDimitry Andric     return false;
6025a5ac124SDimitry Andric 
6035a5ac124SDimitry Andric   // Only need to check pointers between two different dependency sets.
604ee8648bdSDimitry Andric   if (PointerI.DependencySetId == PointerJ.DependencySetId)
6055a5ac124SDimitry Andric     return false;
6065a5ac124SDimitry Andric 
6075a5ac124SDimitry Andric   // Only need to check pointers in the same alias set.
608ee8648bdSDimitry Andric   if (PointerI.AliasSetId != PointerJ.AliasSetId)
6095a5ac124SDimitry Andric     return false;
6105a5ac124SDimitry Andric 
6115a5ac124SDimitry Andric   return true;
6125a5ac124SDimitry Andric }
6135a5ac124SDimitry Andric 
printChecks(raw_ostream & OS,const SmallVectorImpl<RuntimePointerCheck> & Checks,unsigned Depth) const614dd58ef01SDimitry Andric void RuntimePointerChecking::printChecks(
615cfca06d7SDimitry Andric     raw_ostream &OS, const SmallVectorImpl<RuntimePointerCheck> &Checks,
616dd58ef01SDimitry Andric     unsigned Depth) const {
617dd58ef01SDimitry Andric   unsigned N = 0;
618ac9a064cSDimitry Andric   for (const auto &[Check1, Check2] : Checks) {
619ac9a064cSDimitry Andric     const auto &First = Check1->Members, &Second = Check2->Members;
620dd58ef01SDimitry Andric 
621dd58ef01SDimitry Andric     OS.indent(Depth) << "Check " << N++ << ":\n";
622dd58ef01SDimitry Andric 
623ac9a064cSDimitry Andric     OS.indent(Depth + 2) << "Comparing group (" << Check1 << "):\n";
624ac9a064cSDimitry Andric     for (unsigned K : First)
625ac9a064cSDimitry Andric       OS.indent(Depth + 2) << *Pointers[K].PointerValue << "\n";
626dd58ef01SDimitry Andric 
627ac9a064cSDimitry Andric     OS.indent(Depth + 2) << "Against group (" << Check2 << "):\n";
628ac9a064cSDimitry Andric     for (unsigned K : Second)
629ac9a064cSDimitry Andric       OS.indent(Depth + 2) << *Pointers[K].PointerValue << "\n";
630dd58ef01SDimitry Andric   }
631dd58ef01SDimitry Andric }
632dd58ef01SDimitry Andric 
print(raw_ostream & OS,unsigned Depth) const633dd58ef01SDimitry Andric void RuntimePointerChecking::print(raw_ostream &OS, unsigned Depth) const {
6345a5ac124SDimitry Andric 
6355a5ac124SDimitry Andric   OS.indent(Depth) << "Run-time memory checks:\n";
636dd58ef01SDimitry Andric   printChecks(OS, Checks, Depth);
6375a5ac124SDimitry Andric 
638ee8648bdSDimitry Andric   OS.indent(Depth) << "Grouped accesses:\n";
639ac9a064cSDimitry Andric   for (const auto &CG : CheckingGroups) {
640dd58ef01SDimitry Andric     OS.indent(Depth + 2) << "Group " << &CG << ":\n";
641dd58ef01SDimitry Andric     OS.indent(Depth + 4) << "(Low: " << *CG.Low << " High: " << *CG.High
642dd58ef01SDimitry Andric                          << ")\n";
643ac9a064cSDimitry Andric     for (unsigned Member : CG.Members) {
644ac9a064cSDimitry Andric       OS.indent(Depth + 6) << "Member: " << *Pointers[Member].Expr << "\n";
645ee8648bdSDimitry Andric     }
646ee8648bdSDimitry Andric   }
647ee8648bdSDimitry Andric }
648ee8648bdSDimitry Andric 
6495a5ac124SDimitry Andric namespace {
650b915e9e0SDimitry Andric 
651eb11fae6SDimitry Andric /// Analyses memory accesses in a loop.
6525a5ac124SDimitry Andric ///
6535a5ac124SDimitry Andric /// Checks whether run time pointer checks are needed and builds sets for data
6545a5ac124SDimitry Andric /// dependence checking.
6555a5ac124SDimitry Andric class AccessAnalysis {
6565a5ac124SDimitry Andric public:
657eb11fae6SDimitry Andric   /// Read or write access location.
6585a5ac124SDimitry Andric   typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
65971d5a254SDimitry Andric   typedef SmallVector<MemAccessInfo, 8> MemAccessInfoList;
6605a5ac124SDimitry Andric 
AccessAnalysis(Loop * TheLoop,AAResults * AA,LoopInfo * LI,MemoryDepChecker::DepCandidates & DA,PredicatedScalarEvolution & PSE,SmallPtrSetImpl<MDNode * > & LoopAliasScopes)661b60736ecSDimitry Andric   AccessAnalysis(Loop *TheLoop, AAResults *AA, LoopInfo *LI,
662b60736ecSDimitry Andric                  MemoryDepChecker::DepCandidates &DA,
663ac9a064cSDimitry Andric                  PredicatedScalarEvolution &PSE,
664ac9a064cSDimitry Andric                  SmallPtrSetImpl<MDNode *> &LoopAliasScopes)
665ac9a064cSDimitry Andric       : TheLoop(TheLoop), BAA(*AA), AST(BAA), LI(LI), DepCands(DA), PSE(PSE),
666ac9a064cSDimitry Andric         LoopAliasScopes(LoopAliasScopes) {
667e3b55780SDimitry Andric     // We're analyzing dependences across loop iterations.
668e3b55780SDimitry Andric     BAA.enableCrossIterationMode();
669e3b55780SDimitry Andric   }
6705a5ac124SDimitry Andric 
671eb11fae6SDimitry Andric   /// Register a load  and whether it is only read from.
addLoad(MemoryLocation & Loc,Type * AccessTy,bool IsReadOnly)672145449b1SDimitry Andric   void addLoad(MemoryLocation &Loc, Type *AccessTy, bool IsReadOnly) {
6735a5ac124SDimitry Andric     Value *Ptr = const_cast<Value *>(Loc.Ptr);
674ac9a064cSDimitry Andric     AST.add(adjustLoc(Loc));
675145449b1SDimitry Andric     Accesses[MemAccessInfo(Ptr, false)].insert(AccessTy);
6765a5ac124SDimitry Andric     if (IsReadOnly)
6775a5ac124SDimitry Andric       ReadOnlyPtr.insert(Ptr);
6785a5ac124SDimitry Andric   }
6795a5ac124SDimitry Andric 
680eb11fae6SDimitry Andric   /// Register a store.
addStore(MemoryLocation & Loc,Type * AccessTy)681145449b1SDimitry Andric   void addStore(MemoryLocation &Loc, Type *AccessTy) {
6825a5ac124SDimitry Andric     Value *Ptr = const_cast<Value *>(Loc.Ptr);
683ac9a064cSDimitry Andric     AST.add(adjustLoc(Loc));
684145449b1SDimitry Andric     Accesses[MemAccessInfo(Ptr, true)].insert(AccessTy);
6855a5ac124SDimitry Andric   }
6865a5ac124SDimitry Andric 
687eb11fae6SDimitry Andric   /// Check if we can emit a run-time no-alias check for \p Access.
688044eb2f6SDimitry Andric   ///
689044eb2f6SDimitry Andric   /// Returns true if we can emit a run-time no alias check for \p Access.
690044eb2f6SDimitry Andric   /// If we can check this access, this also adds it to a dependence set and
691044eb2f6SDimitry Andric   /// adds a run-time to check for it to \p RtCheck. If \p Assume is true,
692044eb2f6SDimitry Andric   /// we will attempt to use additional run-time checks in order to get
693044eb2f6SDimitry Andric   /// the bounds of the pointer.
694044eb2f6SDimitry Andric   bool createCheckForAccess(RuntimePointerChecking &RtCheck,
695145449b1SDimitry Andric                             MemAccessInfo Access, Type *AccessTy,
6967fa27ce4SDimitry Andric                             const DenseMap<Value *, const SCEV *> &Strides,
697044eb2f6SDimitry Andric                             DenseMap<Value *, unsigned> &DepSetId,
698044eb2f6SDimitry Andric                             Loop *TheLoop, unsigned &RunningDepId,
699145449b1SDimitry Andric                             unsigned ASId, bool ShouldCheckStride, bool Assume);
700044eb2f6SDimitry Andric 
701eb11fae6SDimitry Andric   /// Check whether we can check the pointers at runtime for
702ee8648bdSDimitry Andric   /// non-intersection.
703ee8648bdSDimitry Andric   ///
704ee8648bdSDimitry Andric   /// Returns true if we need no check or if we do and we can generate them
705ee8648bdSDimitry Andric   /// (i.e. the pointers have computable bounds).
706ee8648bdSDimitry Andric   bool canCheckPtrAtRT(RuntimePointerChecking &RtCheck, ScalarEvolution *SE,
7077fa27ce4SDimitry Andric                        Loop *TheLoop, const DenseMap<Value *, const SCEV *> &Strides,
708145449b1SDimitry Andric                        Value *&UncomputablePtr, bool ShouldCheckWrap = false);
7095a5ac124SDimitry Andric 
710eb11fae6SDimitry Andric   /// Goes over all memory accesses, checks whether a RT check is needed
7115a5ac124SDimitry Andric   /// and builds sets of dependent accesses.
buildDependenceSets()7125a5ac124SDimitry Andric   void buildDependenceSets() {
7135a5ac124SDimitry Andric     processMemAccesses();
7145a5ac124SDimitry Andric   }
7155a5ac124SDimitry Andric 
716eb11fae6SDimitry Andric   /// Initial processing of memory accesses determined that we need to
717ee8648bdSDimitry Andric   /// perform dependency checking.
718ee8648bdSDimitry Andric   ///
719ee8648bdSDimitry Andric   /// Note that this can later be cleared if we retry memcheck analysis without
720d8e91e46SDimitry Andric   /// dependency checking (i.e. FoundNonConstantDistanceDependence).
isDependencyCheckNeeded()7215a5ac124SDimitry Andric   bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
7225a5ac124SDimitry Andric 
7235a5ac124SDimitry Andric   /// We decided that no dependence analysis would be used.  Reset the state.
resetDepChecks(MemoryDepChecker & DepChecker)7245a5ac124SDimitry Andric   void resetDepChecks(MemoryDepChecker &DepChecker) {
7255a5ac124SDimitry Andric     CheckDeps.clear();
726dd58ef01SDimitry Andric     DepChecker.clearDependences();
7275a5ac124SDimitry Andric   }
7285a5ac124SDimitry Andric 
getDependenciesToCheck()72971d5a254SDimitry Andric   MemAccessInfoList &getDependenciesToCheck() { return CheckDeps; }
7305a5ac124SDimitry Andric 
7315a5ac124SDimitry Andric private:
732145449b1SDimitry Andric   typedef MapVector<MemAccessInfo, SmallSetVector<Type *, 1>> PtrAccessMap;
7335a5ac124SDimitry Andric 
734ac9a064cSDimitry Andric   /// Adjust the MemoryLocation so that it represents accesses to this
735ac9a064cSDimitry Andric   /// location across all iterations, rather than a single one.
adjustLoc(MemoryLocation Loc) const736ac9a064cSDimitry Andric   MemoryLocation adjustLoc(MemoryLocation Loc) const {
737ac9a064cSDimitry Andric     // The accessed location varies within the loop, but remains within the
738ac9a064cSDimitry Andric     // underlying object.
739ac9a064cSDimitry Andric     Loc.Size = LocationSize::beforeOrAfterPointer();
740ac9a064cSDimitry Andric     Loc.AATags.Scope = adjustAliasScopeList(Loc.AATags.Scope);
741ac9a064cSDimitry Andric     Loc.AATags.NoAlias = adjustAliasScopeList(Loc.AATags.NoAlias);
742ac9a064cSDimitry Andric     return Loc;
743ac9a064cSDimitry Andric   }
744ac9a064cSDimitry Andric 
745ac9a064cSDimitry Andric   /// Drop alias scopes that are only valid within a single loop iteration.
adjustAliasScopeList(MDNode * ScopeList) const746ac9a064cSDimitry Andric   MDNode *adjustAliasScopeList(MDNode *ScopeList) const {
747ac9a064cSDimitry Andric     if (!ScopeList)
748ac9a064cSDimitry Andric       return nullptr;
749ac9a064cSDimitry Andric 
750ac9a064cSDimitry Andric     // For the sake of simplicity, drop the whole scope list if any scope is
751ac9a064cSDimitry Andric     // iteration-local.
752ac9a064cSDimitry Andric     if (any_of(ScopeList->operands(), [&](Metadata *Scope) {
753ac9a064cSDimitry Andric           return LoopAliasScopes.contains(cast<MDNode>(Scope));
754ac9a064cSDimitry Andric         }))
755ac9a064cSDimitry Andric       return nullptr;
756ac9a064cSDimitry Andric 
757ac9a064cSDimitry Andric     return ScopeList;
758ac9a064cSDimitry Andric   }
759ac9a064cSDimitry Andric 
760eb11fae6SDimitry Andric   /// Go over all memory access and check whether runtime pointer checks
761ee8648bdSDimitry Andric   /// are needed and build sets of dependency check candidates.
7625a5ac124SDimitry Andric   void processMemAccesses();
7635a5ac124SDimitry Andric 
764145449b1SDimitry Andric   /// Map of all accesses. Values are the types used to access memory pointed to
765145449b1SDimitry Andric   /// by the pointer.
766145449b1SDimitry Andric   PtrAccessMap Accesses;
7675a5ac124SDimitry Andric 
768eb11fae6SDimitry Andric   /// The loop being checked.
769eb11fae6SDimitry Andric   const Loop *TheLoop;
770eb11fae6SDimitry Andric 
77171d5a254SDimitry Andric   /// List of accesses that need a further dependence check.
77271d5a254SDimitry Andric   MemAccessInfoList CheckDeps;
7735a5ac124SDimitry Andric 
7745a5ac124SDimitry Andric   /// Set of pointers that are read only.
7755a5ac124SDimitry Andric   SmallPtrSet<Value*, 16> ReadOnlyPtr;
7765a5ac124SDimitry Andric 
777e3b55780SDimitry Andric   /// Batched alias analysis results.
778e3b55780SDimitry Andric   BatchAAResults BAA;
779e3b55780SDimitry Andric 
7805a5ac124SDimitry Andric   /// An alias set tracker to partition the access set by underlying object and
7815a5ac124SDimitry Andric   //intrinsic property (such as TBAA metadata).
7825a5ac124SDimitry Andric   AliasSetTracker AST;
7835a5ac124SDimitry Andric 
7845a5ac124SDimitry Andric   LoopInfo *LI;
7855a5ac124SDimitry Andric 
7865a5ac124SDimitry Andric   /// Sets of potentially dependent accesses - members of one set share an
7875a5ac124SDimitry Andric   /// underlying pointer. The set "CheckDeps" identfies which sets really need a
7885a5ac124SDimitry Andric   /// dependence check.
7895a5ac124SDimitry Andric   MemoryDepChecker::DepCandidates &DepCands;
7905a5ac124SDimitry Andric 
791eb11fae6SDimitry Andric   /// Initial processing of memory accesses determined that we may need
792ee8648bdSDimitry Andric   /// to add memchecks.  Perform the analysis to determine the necessary checks.
793ee8648bdSDimitry Andric   ///
794ee8648bdSDimitry Andric   /// Note that, this is different from isDependencyCheckNeeded.  When we retry
795ee8648bdSDimitry Andric   /// memcheck analysis without dependency checking
796d8e91e46SDimitry Andric   /// (i.e. FoundNonConstantDistanceDependence), isDependencyCheckNeeded is
797d8e91e46SDimitry Andric   /// cleared while this remains set if we have potentially dependent accesses.
7986f8fc217SDimitry Andric   bool IsRTCheckAnalysisNeeded = false;
799dd58ef01SDimitry Andric 
800dd58ef01SDimitry Andric   /// The SCEV predicate containing all the SCEV-related assumptions.
801dd58ef01SDimitry Andric   PredicatedScalarEvolution &PSE;
802b1c73532SDimitry Andric 
803b1c73532SDimitry Andric   DenseMap<Value *, SmallVector<const Value *, 16>> UnderlyingObjects;
804ac9a064cSDimitry Andric 
805ac9a064cSDimitry Andric   /// Alias scopes that are declared inside the loop, and as such not valid
806ac9a064cSDimitry Andric   /// across iterations.
807ac9a064cSDimitry Andric   SmallPtrSetImpl<MDNode *> &LoopAliasScopes;
8085a5ac124SDimitry Andric };
8095a5ac124SDimitry Andric 
8105a5ac124SDimitry Andric } // end anonymous namespace
8115a5ac124SDimitry Andric 
812eb11fae6SDimitry Andric /// Check whether a pointer can participate in a runtime bounds check.
813044eb2f6SDimitry Andric /// If \p Assume, try harder to prove that we can compute the bounds of \p Ptr
814044eb2f6SDimitry Andric /// by adding run-time checks (overflow checks) if necessary.
hasComputableBounds(PredicatedScalarEvolution & PSE,Value * Ptr,const SCEV * PtrScev,Loop * L,bool Assume)815145449b1SDimitry Andric static bool hasComputableBounds(PredicatedScalarEvolution &PSE, Value *Ptr,
816145449b1SDimitry Andric                                 const SCEV *PtrScev, Loop *L, bool Assume) {
81701095a5dSDimitry Andric   // The bounds for loop-invariant pointer is trivial.
81801095a5dSDimitry Andric   if (PSE.getSE()->isLoopInvariant(PtrScev, L))
81901095a5dSDimitry Andric     return true;
82001095a5dSDimitry Andric 
8215a5ac124SDimitry Andric   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
822044eb2f6SDimitry Andric 
823044eb2f6SDimitry Andric   if (!AR && Assume)
824044eb2f6SDimitry Andric     AR = PSE.getAsAddRec(Ptr);
825044eb2f6SDimitry Andric 
8265a5ac124SDimitry Andric   if (!AR)
8275a5ac124SDimitry Andric     return false;
8285a5ac124SDimitry Andric 
8295a5ac124SDimitry Andric   return AR->isAffine();
8305a5ac124SDimitry Andric }
8315a5ac124SDimitry Andric 
832eb11fae6SDimitry Andric /// Check whether a pointer address cannot wrap.
isNoWrap(PredicatedScalarEvolution & PSE,const DenseMap<Value *,const SCEV * > & Strides,Value * Ptr,Type * AccessTy,Loop * L)83301095a5dSDimitry Andric static bool isNoWrap(PredicatedScalarEvolution &PSE,
8347fa27ce4SDimitry Andric                      const DenseMap<Value *, const SCEV *> &Strides, Value *Ptr, Type *AccessTy,
835145449b1SDimitry Andric                      Loop *L) {
83601095a5dSDimitry Andric   const SCEV *PtrScev = PSE.getSCEV(Ptr);
83701095a5dSDimitry Andric   if (PSE.getSE()->isLoopInvariant(PtrScev, L))
83801095a5dSDimitry Andric     return true;
83901095a5dSDimitry Andric 
840e3b55780SDimitry Andric   int64_t Stride = getPtrStride(PSE, AccessTy, Ptr, L, Strides).value_or(0);
841044eb2f6SDimitry Andric   if (Stride == 1 || PSE.hasNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW))
842044eb2f6SDimitry Andric     return true;
843044eb2f6SDimitry Andric 
844044eb2f6SDimitry Andric   return false;
845044eb2f6SDimitry Andric }
846044eb2f6SDimitry Andric 
visitPointers(Value * StartPtr,const Loop & InnermostLoop,function_ref<void (Value *)> AddPointer)847f65dcba8SDimitry Andric static void visitPointers(Value *StartPtr, const Loop &InnermostLoop,
848f65dcba8SDimitry Andric                           function_ref<void(Value *)> AddPointer) {
849f65dcba8SDimitry Andric   SmallPtrSet<Value *, 8> Visited;
850f65dcba8SDimitry Andric   SmallVector<Value *> WorkList;
851f65dcba8SDimitry Andric   WorkList.push_back(StartPtr);
852f65dcba8SDimitry Andric 
853f65dcba8SDimitry Andric   while (!WorkList.empty()) {
854f65dcba8SDimitry Andric     Value *Ptr = WorkList.pop_back_val();
855f65dcba8SDimitry Andric     if (!Visited.insert(Ptr).second)
856f65dcba8SDimitry Andric       continue;
857f65dcba8SDimitry Andric     auto *PN = dyn_cast<PHINode>(Ptr);
858f65dcba8SDimitry Andric     // SCEV does not look through non-header PHIs inside the loop. Such phis
859f65dcba8SDimitry Andric     // can be analyzed by adding separate accesses for each incoming pointer
860f65dcba8SDimitry Andric     // value.
861f65dcba8SDimitry Andric     if (PN && InnermostLoop.contains(PN->getParent()) &&
862f65dcba8SDimitry Andric         PN->getParent() != InnermostLoop.getHeader()) {
863f65dcba8SDimitry Andric       for (const Use &Inc : PN->incoming_values())
864f65dcba8SDimitry Andric         WorkList.push_back(Inc);
865f65dcba8SDimitry Andric     } else
866f65dcba8SDimitry Andric       AddPointer(Ptr);
867f65dcba8SDimitry Andric   }
868f65dcba8SDimitry Andric }
869f65dcba8SDimitry Andric 
8704b4fe385SDimitry Andric // Walk back through the IR for a pointer, looking for a select like the
8714b4fe385SDimitry Andric // following:
8724b4fe385SDimitry Andric //
8734b4fe385SDimitry Andric //  %offset = select i1 %cmp, i64 %a, i64 %b
8744b4fe385SDimitry Andric //  %addr = getelementptr double, double* %base, i64 %offset
8754b4fe385SDimitry Andric //  %ld = load double, double* %addr, align 8
8764b4fe385SDimitry Andric //
8774b4fe385SDimitry Andric // We won't be able to form a single SCEVAddRecExpr from this since the
8784b4fe385SDimitry Andric // address for each loop iteration depends on %cmp. We could potentially
8794b4fe385SDimitry Andric // produce multiple valid SCEVAddRecExprs, though, and check all of them for
8804b4fe385SDimitry Andric // memory safety/aliasing if needed.
8814b4fe385SDimitry Andric //
8824b4fe385SDimitry Andric // If we encounter some IR we don't yet handle, or something obviously fine
8834b4fe385SDimitry Andric // like a constant, then we just add the SCEV for that term to the list passed
8844b4fe385SDimitry Andric // in by the caller. If we have a node that may potentially yield a valid
8854b4fe385SDimitry Andric // SCEVAddRecExpr then we decompose it into parts and build the SCEV terms
8864b4fe385SDimitry Andric // ourselves before adding to the list.
findForkedSCEVs(ScalarEvolution * SE,const Loop * L,Value * Ptr,SmallVectorImpl<PointerIntPair<const SCEV *,1,bool>> & ScevList,unsigned Depth)887e3b55780SDimitry Andric static void findForkedSCEVs(
888e3b55780SDimitry Andric     ScalarEvolution *SE, const Loop *L, Value *Ptr,
889e3b55780SDimitry Andric     SmallVectorImpl<PointerIntPair<const SCEV *, 1, bool>> &ScevList,
8904b4fe385SDimitry Andric     unsigned Depth) {
8914b4fe385SDimitry Andric   // If our Value is a SCEVAddRecExpr, loop invariant, not an instruction, or
8924b4fe385SDimitry Andric   // we've exceeded our limit on recursion, just return whatever we have
8934b4fe385SDimitry Andric   // regardless of whether it can be used for a forked pointer or not, along
8944b4fe385SDimitry Andric   // with an indication of whether it might be a poison or undef value.
8954b4fe385SDimitry Andric   const SCEV *Scev = SE->getSCEV(Ptr);
8964b4fe385SDimitry Andric   if (isa<SCEVAddRecExpr>(Scev) || L->isLoopInvariant(Ptr) ||
8974b4fe385SDimitry Andric       !isa<Instruction>(Ptr) || Depth == 0) {
898e3b55780SDimitry Andric     ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr));
8994b4fe385SDimitry Andric     return;
9004b4fe385SDimitry Andric   }
9014b4fe385SDimitry Andric 
9024b4fe385SDimitry Andric   Depth--;
9034b4fe385SDimitry Andric 
904e3b55780SDimitry Andric   auto UndefPoisonCheck = [](PointerIntPair<const SCEV *, 1, bool> S) {
905e3b55780SDimitry Andric     return get<1>(S);
906e3b55780SDimitry Andric   };
907e3b55780SDimitry Andric 
908e3b55780SDimitry Andric   auto GetBinOpExpr = [&SE](unsigned Opcode, const SCEV *L, const SCEV *R) {
909e3b55780SDimitry Andric     switch (Opcode) {
910e3b55780SDimitry Andric     case Instruction::Add:
911e3b55780SDimitry Andric       return SE->getAddExpr(L, R);
912e3b55780SDimitry Andric     case Instruction::Sub:
913e3b55780SDimitry Andric       return SE->getMinusSCEV(L, R);
914e3b55780SDimitry Andric     default:
915e3b55780SDimitry Andric       llvm_unreachable("Unexpected binary operator when walking ForkedPtrs");
916e3b55780SDimitry Andric     }
9174b4fe385SDimitry Andric   };
9184b4fe385SDimitry Andric 
9194b4fe385SDimitry Andric   Instruction *I = cast<Instruction>(Ptr);
9204b4fe385SDimitry Andric   unsigned Opcode = I->getOpcode();
9214b4fe385SDimitry Andric   switch (Opcode) {
9224b4fe385SDimitry Andric   case Instruction::GetElementPtr: {
9234b4fe385SDimitry Andric     GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
9244b4fe385SDimitry Andric     Type *SourceTy = GEP->getSourceElementType();
9254b4fe385SDimitry Andric     // We only handle base + single offset GEPs here for now.
9264b4fe385SDimitry Andric     // Not dealing with preexisting gathers yet, so no vectors.
9274b4fe385SDimitry Andric     if (I->getNumOperands() != 2 || SourceTy->isVectorTy()) {
928e3b55780SDimitry Andric       ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(GEP));
9294b4fe385SDimitry Andric       break;
9304b4fe385SDimitry Andric     }
931e3b55780SDimitry Andric     SmallVector<PointerIntPair<const SCEV *, 1, bool>, 2> BaseScevs;
932e3b55780SDimitry Andric     SmallVector<PointerIntPair<const SCEV *, 1, bool>, 2> OffsetScevs;
9334b4fe385SDimitry Andric     findForkedSCEVs(SE, L, I->getOperand(0), BaseScevs, Depth);
9344b4fe385SDimitry Andric     findForkedSCEVs(SE, L, I->getOperand(1), OffsetScevs, Depth);
9354b4fe385SDimitry Andric 
9364b4fe385SDimitry Andric     // See if we need to freeze our fork...
9374b4fe385SDimitry Andric     bool NeedsFreeze = any_of(BaseScevs, UndefPoisonCheck) ||
9384b4fe385SDimitry Andric                        any_of(OffsetScevs, UndefPoisonCheck);
9394b4fe385SDimitry Andric 
9404b4fe385SDimitry Andric     // Check that we only have a single fork, on either the base or the offset.
9414b4fe385SDimitry Andric     // Copy the SCEV across for the one without a fork in order to generate
9424b4fe385SDimitry Andric     // the full SCEV for both sides of the GEP.
9434b4fe385SDimitry Andric     if (OffsetScevs.size() == 2 && BaseScevs.size() == 1)
9444b4fe385SDimitry Andric       BaseScevs.push_back(BaseScevs[0]);
9454b4fe385SDimitry Andric     else if (BaseScevs.size() == 2 && OffsetScevs.size() == 1)
9464b4fe385SDimitry Andric       OffsetScevs.push_back(OffsetScevs[0]);
9474b4fe385SDimitry Andric     else {
948e3b55780SDimitry Andric       ScevList.emplace_back(Scev, NeedsFreeze);
9494b4fe385SDimitry Andric       break;
9504b4fe385SDimitry Andric     }
9514b4fe385SDimitry Andric 
9524b4fe385SDimitry Andric     // Find the pointer type we need to extend to.
9534b4fe385SDimitry Andric     Type *IntPtrTy = SE->getEffectiveSCEVType(
9544b4fe385SDimitry Andric         SE->getSCEV(GEP->getPointerOperand())->getType());
9554b4fe385SDimitry Andric 
9564b4fe385SDimitry Andric     // Find the size of the type being pointed to. We only have a single
9574b4fe385SDimitry Andric     // index term (guarded above) so we don't need to index into arrays or
9584b4fe385SDimitry Andric     // structures, just get the size of the scalar value.
9594b4fe385SDimitry Andric     const SCEV *Size = SE->getSizeOfExpr(IntPtrTy, SourceTy);
9604b4fe385SDimitry Andric 
9614b4fe385SDimitry Andric     // Scale up the offsets by the size of the type, then add to the bases.
9624b4fe385SDimitry Andric     const SCEV *Scaled1 = SE->getMulExpr(
963e3b55780SDimitry Andric         Size, SE->getTruncateOrSignExtend(get<0>(OffsetScevs[0]), IntPtrTy));
9644b4fe385SDimitry Andric     const SCEV *Scaled2 = SE->getMulExpr(
965e3b55780SDimitry Andric         Size, SE->getTruncateOrSignExtend(get<0>(OffsetScevs[1]), IntPtrTy));
966e3b55780SDimitry Andric     ScevList.emplace_back(SE->getAddExpr(get<0>(BaseScevs[0]), Scaled1),
967e3b55780SDimitry Andric                           NeedsFreeze);
968e3b55780SDimitry Andric     ScevList.emplace_back(SE->getAddExpr(get<0>(BaseScevs[1]), Scaled2),
969e3b55780SDimitry Andric                           NeedsFreeze);
9704b4fe385SDimitry Andric     break;
9714b4fe385SDimitry Andric   }
9724b4fe385SDimitry Andric   case Instruction::Select: {
973e3b55780SDimitry Andric     SmallVector<PointerIntPair<const SCEV *, 1, bool>, 2> ChildScevs;
9744b4fe385SDimitry Andric     // A select means we've found a forked pointer, but we currently only
9754b4fe385SDimitry Andric     // support a single select per pointer so if there's another behind this
9764b4fe385SDimitry Andric     // then we just bail out and return the generic SCEV.
9774b4fe385SDimitry Andric     findForkedSCEVs(SE, L, I->getOperand(1), ChildScevs, Depth);
9784b4fe385SDimitry Andric     findForkedSCEVs(SE, L, I->getOperand(2), ChildScevs, Depth);
9794b4fe385SDimitry Andric     if (ChildScevs.size() == 2) {
9804b4fe385SDimitry Andric       ScevList.push_back(ChildScevs[0]);
9814b4fe385SDimitry Andric       ScevList.push_back(ChildScevs[1]);
9824b4fe385SDimitry Andric     } else
983e3b55780SDimitry Andric       ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr));
984e3b55780SDimitry Andric     break;
985e3b55780SDimitry Andric   }
986b1c73532SDimitry Andric   case Instruction::PHI: {
987b1c73532SDimitry Andric     SmallVector<PointerIntPair<const SCEV *, 1, bool>, 2> ChildScevs;
988b1c73532SDimitry Andric     // A phi means we've found a forked pointer, but we currently only
989b1c73532SDimitry Andric     // support a single phi per pointer so if there's another behind this
990b1c73532SDimitry Andric     // then we just bail out and return the generic SCEV.
991b1c73532SDimitry Andric     if (I->getNumOperands() == 2) {
992b1c73532SDimitry Andric       findForkedSCEVs(SE, L, I->getOperand(0), ChildScevs, Depth);
993b1c73532SDimitry Andric       findForkedSCEVs(SE, L, I->getOperand(1), ChildScevs, Depth);
994b1c73532SDimitry Andric     }
995b1c73532SDimitry Andric     if (ChildScevs.size() == 2) {
996b1c73532SDimitry Andric       ScevList.push_back(ChildScevs[0]);
997b1c73532SDimitry Andric       ScevList.push_back(ChildScevs[1]);
998b1c73532SDimitry Andric     } else
999b1c73532SDimitry Andric       ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr));
1000b1c73532SDimitry Andric     break;
1001b1c73532SDimitry Andric   }
1002e3b55780SDimitry Andric   case Instruction::Add:
1003e3b55780SDimitry Andric   case Instruction::Sub: {
1004e3b55780SDimitry Andric     SmallVector<PointerIntPair<const SCEV *, 1, bool>> LScevs;
1005e3b55780SDimitry Andric     SmallVector<PointerIntPair<const SCEV *, 1, bool>> RScevs;
1006e3b55780SDimitry Andric     findForkedSCEVs(SE, L, I->getOperand(0), LScevs, Depth);
1007e3b55780SDimitry Andric     findForkedSCEVs(SE, L, I->getOperand(1), RScevs, Depth);
1008e3b55780SDimitry Andric 
1009e3b55780SDimitry Andric     // See if we need to freeze our fork...
1010e3b55780SDimitry Andric     bool NeedsFreeze =
1011e3b55780SDimitry Andric         any_of(LScevs, UndefPoisonCheck) || any_of(RScevs, UndefPoisonCheck);
1012e3b55780SDimitry Andric 
1013e3b55780SDimitry Andric     // Check that we only have a single fork, on either the left or right side.
1014e3b55780SDimitry Andric     // Copy the SCEV across for the one without a fork in order to generate
1015e3b55780SDimitry Andric     // the full SCEV for both sides of the BinOp.
1016e3b55780SDimitry Andric     if (LScevs.size() == 2 && RScevs.size() == 1)
1017e3b55780SDimitry Andric       RScevs.push_back(RScevs[0]);
1018e3b55780SDimitry Andric     else if (RScevs.size() == 2 && LScevs.size() == 1)
1019e3b55780SDimitry Andric       LScevs.push_back(LScevs[0]);
1020e3b55780SDimitry Andric     else {
1021e3b55780SDimitry Andric       ScevList.emplace_back(Scev, NeedsFreeze);
1022e3b55780SDimitry Andric       break;
1023e3b55780SDimitry Andric     }
1024e3b55780SDimitry Andric 
1025e3b55780SDimitry Andric     ScevList.emplace_back(
1026e3b55780SDimitry Andric         GetBinOpExpr(Opcode, get<0>(LScevs[0]), get<0>(RScevs[0])),
1027e3b55780SDimitry Andric         NeedsFreeze);
1028e3b55780SDimitry Andric     ScevList.emplace_back(
1029e3b55780SDimitry Andric         GetBinOpExpr(Opcode, get<0>(LScevs[1]), get<0>(RScevs[1])),
1030e3b55780SDimitry Andric         NeedsFreeze);
10314b4fe385SDimitry Andric     break;
10324b4fe385SDimitry Andric   }
10334b4fe385SDimitry Andric   default:
10344b4fe385SDimitry Andric     // Just return the current SCEV if we haven't handled the instruction yet.
10354b4fe385SDimitry Andric     LLVM_DEBUG(dbgs() << "ForkedPtr unhandled instruction: " << *I << "\n");
1036e3b55780SDimitry Andric     ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr));
10374b4fe385SDimitry Andric     break;
10384b4fe385SDimitry Andric   }
10394b4fe385SDimitry Andric }
10404b4fe385SDimitry Andric 
1041e3b55780SDimitry Andric static SmallVector<PointerIntPair<const SCEV *, 1, bool>>
findForkedPointer(PredicatedScalarEvolution & PSE,const DenseMap<Value *,const SCEV * > & StridesMap,Value * Ptr,const Loop * L)10424b4fe385SDimitry Andric findForkedPointer(PredicatedScalarEvolution &PSE,
10437fa27ce4SDimitry Andric                   const DenseMap<Value *, const SCEV *> &StridesMap, Value *Ptr,
10444b4fe385SDimitry Andric                   const Loop *L) {
10454b4fe385SDimitry Andric   ScalarEvolution *SE = PSE.getSE();
10464b4fe385SDimitry Andric   assert(SE->isSCEVable(Ptr->getType()) && "Value is not SCEVable!");
1047e3b55780SDimitry Andric   SmallVector<PointerIntPair<const SCEV *, 1, bool>> Scevs;
10484b4fe385SDimitry Andric   findForkedSCEVs(SE, L, Ptr, Scevs, MaxForkedSCEVDepth);
10494b4fe385SDimitry Andric 
1050e3b55780SDimitry Andric   // For now, we will only accept a forked pointer with two possible SCEVs
1051e3b55780SDimitry Andric   // that are either SCEVAddRecExprs or loop invariant.
1052e3b55780SDimitry Andric   if (Scevs.size() == 2 &&
1053e3b55780SDimitry Andric       (isa<SCEVAddRecExpr>(get<0>(Scevs[0])) ||
1054e3b55780SDimitry Andric        SE->isLoopInvariant(get<0>(Scevs[0]), L)) &&
1055e3b55780SDimitry Andric       (isa<SCEVAddRecExpr>(get<0>(Scevs[1])) ||
1056e3b55780SDimitry Andric        SE->isLoopInvariant(get<0>(Scevs[1]), L))) {
1057e3b55780SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Found forked pointer: " << *Ptr << "\n");
1058e3b55780SDimitry Andric     LLVM_DEBUG(dbgs() << "\t(1) " << *get<0>(Scevs[0]) << "\n");
1059e3b55780SDimitry Andric     LLVM_DEBUG(dbgs() << "\t(2) " << *get<0>(Scevs[1]) << "\n");
10604b4fe385SDimitry Andric     return Scevs;
1061e3b55780SDimitry Andric   }
10624b4fe385SDimitry Andric 
1063e3b55780SDimitry Andric   return {{replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr), false}};
10644b4fe385SDimitry Andric }
10654b4fe385SDimitry Andric 
createCheckForAccess(RuntimePointerChecking & RtCheck,MemAccessInfo Access,Type * AccessTy,const DenseMap<Value *,const SCEV * > & StridesMap,DenseMap<Value *,unsigned> & DepSetId,Loop * TheLoop,unsigned & RunningDepId,unsigned ASId,bool ShouldCheckWrap,bool Assume)1066044eb2f6SDimitry Andric bool AccessAnalysis::createCheckForAccess(RuntimePointerChecking &RtCheck,
1067145449b1SDimitry Andric                                           MemAccessInfo Access, Type *AccessTy,
10687fa27ce4SDimitry Andric                                           const DenseMap<Value *, const SCEV *> &StridesMap,
1069044eb2f6SDimitry Andric                                           DenseMap<Value *, unsigned> &DepSetId,
1070044eb2f6SDimitry Andric                                           Loop *TheLoop, unsigned &RunningDepId,
1071044eb2f6SDimitry Andric                                           unsigned ASId, bool ShouldCheckWrap,
1072044eb2f6SDimitry Andric                                           bool Assume) {
1073044eb2f6SDimitry Andric   Value *Ptr = Access.getPointer();
1074044eb2f6SDimitry Andric 
1075e3b55780SDimitry Andric   SmallVector<PointerIntPair<const SCEV *, 1, bool>> TranslatedPtrs =
10764b4fe385SDimitry Andric       findForkedPointer(PSE, StridesMap, Ptr, TheLoop);
1077145449b1SDimitry Andric 
1078145449b1SDimitry Andric   for (auto &P : TranslatedPtrs) {
1079e3b55780SDimitry Andric     const SCEV *PtrExpr = get<0>(P);
1080145449b1SDimitry Andric     if (!hasComputableBounds(PSE, Ptr, PtrExpr, TheLoop, Assume))
1081044eb2f6SDimitry Andric       return false;
1082044eb2f6SDimitry Andric 
1083044eb2f6SDimitry Andric     // When we run after a failing dependency check we have to make sure
1084044eb2f6SDimitry Andric     // we don't have wrapping pointers.
1085145449b1SDimitry Andric     if (ShouldCheckWrap) {
1086145449b1SDimitry Andric       // Skip wrap checking when translating pointers.
1087145449b1SDimitry Andric       if (TranslatedPtrs.size() > 1)
1088145449b1SDimitry Andric         return false;
1089145449b1SDimitry Andric 
1090145449b1SDimitry Andric       if (!isNoWrap(PSE, StridesMap, Ptr, AccessTy, TheLoop)) {
1091044eb2f6SDimitry Andric         auto *Expr = PSE.getSCEV(Ptr);
1092044eb2f6SDimitry Andric         if (!Assume || !isa<SCEVAddRecExpr>(Expr))
1093044eb2f6SDimitry Andric           return false;
1094044eb2f6SDimitry Andric         PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
1095044eb2f6SDimitry Andric       }
1096145449b1SDimitry Andric     }
1097145449b1SDimitry Andric     // If there's only one option for Ptr, look it up after bounds and wrap
1098145449b1SDimitry Andric     // checking, because assumptions might have been added to PSE.
1099145449b1SDimitry Andric     if (TranslatedPtrs.size() == 1)
1100e3b55780SDimitry Andric       TranslatedPtrs[0] = {replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr),
1101e3b55780SDimitry Andric                            false};
1102145449b1SDimitry Andric   }
1103145449b1SDimitry Andric 
1104e3b55780SDimitry Andric   for (auto [PtrExpr, NeedsFreeze] : TranslatedPtrs) {
1105044eb2f6SDimitry Andric     // The id of the dependence set.
1106044eb2f6SDimitry Andric     unsigned DepId;
1107044eb2f6SDimitry Andric 
1108044eb2f6SDimitry Andric     if (isDependencyCheckNeeded()) {
1109044eb2f6SDimitry Andric       Value *Leader = DepCands.getLeaderValue(Access).getPointer();
1110044eb2f6SDimitry Andric       unsigned &LeaderId = DepSetId[Leader];
1111044eb2f6SDimitry Andric       if (!LeaderId)
1112044eb2f6SDimitry Andric         LeaderId = RunningDepId++;
1113044eb2f6SDimitry Andric       DepId = LeaderId;
1114044eb2f6SDimitry Andric     } else
1115044eb2f6SDimitry Andric       // Each access has its own dependence set.
1116044eb2f6SDimitry Andric       DepId = RunningDepId++;
1117044eb2f6SDimitry Andric 
1118044eb2f6SDimitry Andric     bool IsWrite = Access.getInt();
1119145449b1SDimitry Andric     RtCheck.insert(TheLoop, Ptr, PtrExpr, AccessTy, IsWrite, DepId, ASId, PSE,
1120e3b55780SDimitry Andric                    NeedsFreeze);
1121eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
1122145449b1SDimitry Andric   }
1123044eb2f6SDimitry Andric 
1124044eb2f6SDimitry Andric   return true;
112501095a5dSDimitry Andric }
112601095a5dSDimitry Andric 
canCheckPtrAtRT(RuntimePointerChecking & RtCheck,ScalarEvolution * SE,Loop * TheLoop,const DenseMap<Value *,const SCEV * > & StridesMap,Value * & UncomputablePtr,bool ShouldCheckWrap)1127ee8648bdSDimitry Andric bool AccessAnalysis::canCheckPtrAtRT(RuntimePointerChecking &RtCheck,
1128ee8648bdSDimitry Andric                                      ScalarEvolution *SE, Loop *TheLoop,
11297fa27ce4SDimitry Andric                                      const DenseMap<Value *, const SCEV *> &StridesMap,
1130145449b1SDimitry Andric                                      Value *&UncomputablePtr, bool ShouldCheckWrap) {
11315a5ac124SDimitry Andric   // Find pointers with computable bounds. We are going to use this information
11325a5ac124SDimitry Andric   // to place a runtime bound check.
11335a5ac124SDimitry Andric   bool CanDoRT = true;
11345a5ac124SDimitry Andric 
1135cfca06d7SDimitry Andric   bool MayNeedRTCheck = false;
1136ee8648bdSDimitry Andric   if (!IsRTCheckAnalysisNeeded) return true;
113785d8b2bbSDimitry Andric 
11385a5ac124SDimitry Andric   bool IsDepCheckNeeded = isDependencyCheckNeeded();
11395a5ac124SDimitry Andric 
11405a5ac124SDimitry Andric   // We assign a consecutive id to access from different alias sets.
11415a5ac124SDimitry Andric   // Accesses between different groups doesn't need to be checked.
1142cfca06d7SDimitry Andric   unsigned ASId = 0;
11435a5ac124SDimitry Andric   for (auto &AS : AST) {
1144ee8648bdSDimitry Andric     int NumReadPtrChecks = 0;
1145ee8648bdSDimitry Andric     int NumWritePtrChecks = 0;
1146044eb2f6SDimitry Andric     bool CanDoAliasSetRT = true;
1147cfca06d7SDimitry Andric     ++ASId;
11484df029ccSDimitry Andric     auto ASPointers = AS.getPointers();
1149ee8648bdSDimitry Andric 
11505a5ac124SDimitry Andric     // We assign consecutive id to access from different dependence sets.
11515a5ac124SDimitry Andric     // Accesses within the same set don't need a runtime check.
11525a5ac124SDimitry Andric     unsigned RunningDepId = 1;
11535a5ac124SDimitry Andric     DenseMap<Value *, unsigned> DepSetId;
11545a5ac124SDimitry Andric 
11554b4fe385SDimitry Andric     SmallVector<std::pair<MemAccessInfo, Type *>, 4> Retries;
1156044eb2f6SDimitry Andric 
1157b60736ecSDimitry Andric     // First, count how many write and read accesses are in the alias set. Also
1158b60736ecSDimitry Andric     // collect MemAccessInfos for later.
1159b60736ecSDimitry Andric     SmallVector<MemAccessInfo, 4> AccessInfos;
1160ac9a064cSDimitry Andric     for (const Value *ConstPtr : ASPointers) {
1161ac9a064cSDimitry Andric       Value *Ptr = const_cast<Value *>(ConstPtr);
11625a5ac124SDimitry Andric       bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
1163ee8648bdSDimitry Andric       if (IsWrite)
1164ee8648bdSDimitry Andric         ++NumWritePtrChecks;
1165ee8648bdSDimitry Andric       else
1166ee8648bdSDimitry Andric         ++NumReadPtrChecks;
1167b60736ecSDimitry Andric       AccessInfos.emplace_back(Ptr, IsWrite);
11685a5ac124SDimitry Andric     }
11695a5ac124SDimitry Andric 
1170b60736ecSDimitry Andric     // We do not need runtime checks for this alias set, if there are no writes
1171b60736ecSDimitry Andric     // or a single write and no reads.
1172b60736ecSDimitry Andric     if (NumWritePtrChecks == 0 ||
1173b60736ecSDimitry Andric         (NumWritePtrChecks == 1 && NumReadPtrChecks == 0)) {
11744df029ccSDimitry Andric       assert((ASPointers.size() <= 1 ||
11754df029ccSDimitry Andric               all_of(ASPointers,
11764df029ccSDimitry Andric                      [this](const Value *Ptr) {
11774df029ccSDimitry Andric                        MemAccessInfo AccessWrite(const_cast<Value *>(Ptr),
11784df029ccSDimitry Andric                                                  true);
1179b60736ecSDimitry Andric                        return DepCands.findValue(AccessWrite) == DepCands.end();
1180cfca06d7SDimitry Andric                      })) &&
1181cfca06d7SDimitry Andric              "Can only skip updating CanDoRT below, if all entries in AS "
1182cfca06d7SDimitry Andric              "are reads or there is at most 1 entry");
1183cfca06d7SDimitry Andric       continue;
1184cfca06d7SDimitry Andric     }
1185b60736ecSDimitry Andric 
1186b60736ecSDimitry Andric     for (auto &Access : AccessInfos) {
11874b4fe385SDimitry Andric       for (const auto &AccessTy : Accesses[Access]) {
1188145449b1SDimitry Andric         if (!createCheckForAccess(RtCheck, Access, AccessTy, StridesMap,
1189145449b1SDimitry Andric                                   DepSetId, TheLoop, RunningDepId, ASId,
1190145449b1SDimitry Andric                                   ShouldCheckWrap, false)) {
1191b60736ecSDimitry Andric           LLVM_DEBUG(dbgs() << "LAA: Can't find bounds for ptr:"
1192b60736ecSDimitry Andric                             << *Access.getPointer() << '\n');
11934b4fe385SDimitry Andric           Retries.push_back({Access, AccessTy});
1194b60736ecSDimitry Andric           CanDoAliasSetRT = false;
1195cfca06d7SDimitry Andric         }
1196b60736ecSDimitry Andric       }
1197145449b1SDimitry Andric     }
1198b60736ecSDimitry Andric 
1199b60736ecSDimitry Andric     // Note that this function computes CanDoRT and MayNeedRTCheck
1200b60736ecSDimitry Andric     // independently. For example CanDoRT=false, MayNeedRTCheck=false means that
1201b60736ecSDimitry Andric     // we have a pointer for which we couldn't find the bounds but we don't
1202b60736ecSDimitry Andric     // actually need to emit any checks so it does not matter.
1203b60736ecSDimitry Andric     //
1204b60736ecSDimitry Andric     // We need runtime checks for this alias set, if there are at least 2
1205b60736ecSDimitry Andric     // dependence sets (in which case RunningDepId > 2) or if we need to re-try
1206b60736ecSDimitry Andric     // any bound checks (because in that case the number of dependence sets is
1207b60736ecSDimitry Andric     // incomplete).
1208b60736ecSDimitry Andric     bool NeedsAliasSetRTCheck = RunningDepId > 2 || !Retries.empty();
1209ee8648bdSDimitry Andric 
1210044eb2f6SDimitry Andric     // We need to perform run-time alias checks, but some pointers had bounds
1211044eb2f6SDimitry Andric     // that couldn't be checked.
1212044eb2f6SDimitry Andric     if (NeedsAliasSetRTCheck && !CanDoAliasSetRT) {
1213044eb2f6SDimitry Andric       // Reset the CanDoSetRt flag and retry all accesses that have failed.
1214044eb2f6SDimitry Andric       // We know that we need these checks, so we can now be more aggressive
1215044eb2f6SDimitry Andric       // and add further checks if required (overflow checks).
1216044eb2f6SDimitry Andric       CanDoAliasSetRT = true;
1217ac9a064cSDimitry Andric       for (const auto &[Access, AccessTy] : Retries) {
1218145449b1SDimitry Andric         if (!createCheckForAccess(RtCheck, Access, AccessTy, StridesMap,
1219145449b1SDimitry Andric                                   DepSetId, TheLoop, RunningDepId, ASId,
1220044eb2f6SDimitry Andric                                   ShouldCheckWrap, /*Assume=*/true)) {
1221044eb2f6SDimitry Andric           CanDoAliasSetRT = false;
1222145449b1SDimitry Andric           UncomputablePtr = Access.getPointer();
1223044eb2f6SDimitry Andric           break;
1224044eb2f6SDimitry Andric         }
1225044eb2f6SDimitry Andric       }
1226145449b1SDimitry Andric     }
1227044eb2f6SDimitry Andric 
1228044eb2f6SDimitry Andric     CanDoRT &= CanDoAliasSetRT;
1229cfca06d7SDimitry Andric     MayNeedRTCheck |= NeedsAliasSetRTCheck;
12305a5ac124SDimitry Andric     ++ASId;
12315a5ac124SDimitry Andric   }
12325a5ac124SDimitry Andric 
12335a5ac124SDimitry Andric   // If the pointers that we would use for the bounds comparison have different
12345a5ac124SDimitry Andric   // address spaces, assume the values aren't directly comparable, so we can't
12355a5ac124SDimitry Andric   // use them for the runtime check. We also have to assume they could
12365a5ac124SDimitry Andric   // overlap. In the future there should be metadata for whether address spaces
12375a5ac124SDimitry Andric   // are disjoint.
12385a5ac124SDimitry Andric   unsigned NumPointers = RtCheck.Pointers.size();
12395a5ac124SDimitry Andric   for (unsigned i = 0; i < NumPointers; ++i) {
12405a5ac124SDimitry Andric     for (unsigned j = i + 1; j < NumPointers; ++j) {
12415a5ac124SDimitry Andric       // Only need to check pointers between two different dependency sets.
1242ee8648bdSDimitry Andric       if (RtCheck.Pointers[i].DependencySetId ==
1243ee8648bdSDimitry Andric           RtCheck.Pointers[j].DependencySetId)
12445a5ac124SDimitry Andric        continue;
12455a5ac124SDimitry Andric       // Only need to check pointers in the same alias set.
1246ee8648bdSDimitry Andric       if (RtCheck.Pointers[i].AliasSetId != RtCheck.Pointers[j].AliasSetId)
12475a5ac124SDimitry Andric         continue;
12485a5ac124SDimitry Andric 
1249ee8648bdSDimitry Andric       Value *PtrI = RtCheck.Pointers[i].PointerValue;
1250ee8648bdSDimitry Andric       Value *PtrJ = RtCheck.Pointers[j].PointerValue;
12515a5ac124SDimitry Andric 
12525a5ac124SDimitry Andric       unsigned ASi = PtrI->getType()->getPointerAddressSpace();
12535a5ac124SDimitry Andric       unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
12545a5ac124SDimitry Andric       if (ASi != ASj) {
1255eb11fae6SDimitry Andric         LLVM_DEBUG(
1256eb11fae6SDimitry Andric             dbgs() << "LAA: Runtime check would require comparison between"
12575a5ac124SDimitry Andric                       " different address spaces\n");
12585a5ac124SDimitry Andric         return false;
12595a5ac124SDimitry Andric       }
12605a5ac124SDimitry Andric     }
12615a5ac124SDimitry Andric   }
12625a5ac124SDimitry Andric 
1263cfca06d7SDimitry Andric   if (MayNeedRTCheck && CanDoRT)
1264dd58ef01SDimitry Andric     RtCheck.generateChecks(DepCands, IsDepCheckNeeded);
1265ee8648bdSDimitry Andric 
1266eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: We need to do " << RtCheck.getNumberOfChecks()
1267ee8648bdSDimitry Andric                     << " pointer comparisons.\n");
1268ee8648bdSDimitry Andric 
1269cfca06d7SDimitry Andric   // If we can do run-time checks, but there are no checks, no runtime checks
1270cfca06d7SDimitry Andric   // are needed. This can happen when all pointers point to the same underlying
1271cfca06d7SDimitry Andric   // object for example.
1272cfca06d7SDimitry Andric   RtCheck.Need = CanDoRT ? RtCheck.getNumberOfChecks() != 0 : MayNeedRTCheck;
1273ee8648bdSDimitry Andric 
1274cfca06d7SDimitry Andric   bool CanDoRTIfNeeded = !RtCheck.Need || CanDoRT;
1275ee8648bdSDimitry Andric   if (!CanDoRTIfNeeded)
1276ee8648bdSDimitry Andric     RtCheck.reset();
1277ee8648bdSDimitry Andric   return CanDoRTIfNeeded;
12785a5ac124SDimitry Andric }
12795a5ac124SDimitry Andric 
processMemAccesses()12805a5ac124SDimitry Andric void AccessAnalysis::processMemAccesses() {
12815a5ac124SDimitry Andric   // We process the set twice: first we process read-write pointers, last we
12825a5ac124SDimitry Andric   // process read-only pointers. This allows us to skip dependence tests for
12835a5ac124SDimitry Andric   // read-only pointers.
12845a5ac124SDimitry Andric 
1285eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
1286eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << "  AST: "; AST.dump());
1287eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA:   Accesses(" << Accesses.size() << "):\n");
1288eb11fae6SDimitry Andric   LLVM_DEBUG({
1289ac9a064cSDimitry Andric     for (const auto &[A, _] : Accesses)
1290ac9a064cSDimitry Andric       dbgs() << "\t" << *A.getPointer() << " ("
1291ac9a064cSDimitry Andric              << (A.getInt() ? "write"
1292ac9a064cSDimitry Andric                             : (ReadOnlyPtr.count(A.getPointer()) ? "read-only"
1293145449b1SDimitry Andric                                                                  : "read"))
1294145449b1SDimitry Andric              << ")\n";
12955a5ac124SDimitry Andric   });
12965a5ac124SDimitry Andric 
12975a5ac124SDimitry Andric   // The AliasSetTracker has nicely partitioned our pointers by metadata
12985a5ac124SDimitry Andric   // compatibility and potential for underlying-object overlap. As a result, we
12995a5ac124SDimitry Andric   // only need to check for potential pointer dependencies within each alias
13005a5ac124SDimitry Andric   // set.
1301b60736ecSDimitry Andric   for (const auto &AS : AST) {
13025a5ac124SDimitry Andric     // Note that both the alias-set tracker and the alias sets themselves used
13034df029ccSDimitry Andric     // ordered collections internally and so the iteration order here is
13044df029ccSDimitry Andric     // deterministic.
13054df029ccSDimitry Andric     auto ASPointers = AS.getPointers();
13065a5ac124SDimitry Andric 
13075a5ac124SDimitry Andric     bool SetHasWrite = false;
13085a5ac124SDimitry Andric 
13095a5ac124SDimitry Andric     // Map of pointers to last access encountered.
1310e6d15924SDimitry Andric     typedef DenseMap<const Value*, MemAccessInfo> UnderlyingObjToAccessMap;
13115a5ac124SDimitry Andric     UnderlyingObjToAccessMap ObjToLastAccess;
13125a5ac124SDimitry Andric 
13135a5ac124SDimitry Andric     // Set of access to check after all writes have been processed.
1314145449b1SDimitry Andric     PtrAccessMap DeferredAccesses;
13155a5ac124SDimitry Andric 
13165a5ac124SDimitry Andric     // Iterate over each alias set twice, once to process read/write pointers,
13175a5ac124SDimitry Andric     // and then to process read-only pointers.
13185a5ac124SDimitry Andric     for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
13195a5ac124SDimitry Andric       bool UseDeferred = SetIteration > 0;
1320145449b1SDimitry Andric       PtrAccessMap &S = UseDeferred ? DeferredAccesses : Accesses;
13215a5ac124SDimitry Andric 
1322ac9a064cSDimitry Andric       for (const Value *ConstPtr : ASPointers) {
1323ac9a064cSDimitry Andric         Value *Ptr = const_cast<Value *>(ConstPtr);
13245a5ac124SDimitry Andric 
13255a5ac124SDimitry Andric         // For a single memory access in AliasSetTracker, Accesses may contain
13265a5ac124SDimitry Andric         // both read and write, and they both need to be handled for CheckDeps.
1327ac9a064cSDimitry Andric         for (const auto &[AC, _] : S) {
1328ac9a064cSDimitry Andric           if (AC.getPointer() != Ptr)
13295a5ac124SDimitry Andric             continue;
13305a5ac124SDimitry Andric 
1331ac9a064cSDimitry Andric           bool IsWrite = AC.getInt();
13325a5ac124SDimitry Andric 
13335a5ac124SDimitry Andric           // If we're using the deferred access set, then it contains only
13345a5ac124SDimitry Andric           // reads.
13355a5ac124SDimitry Andric           bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
13365a5ac124SDimitry Andric           if (UseDeferred && !IsReadOnlyPtr)
13375a5ac124SDimitry Andric             continue;
13385a5ac124SDimitry Andric           // Otherwise, the pointer must be in the PtrAccessSet, either as a
13395a5ac124SDimitry Andric           // read or a write.
13405a5ac124SDimitry Andric           assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
13415a5ac124SDimitry Andric                   S.count(MemAccessInfo(Ptr, false))) &&
13425a5ac124SDimitry Andric                  "Alias-set pointer not in the access set?");
13435a5ac124SDimitry Andric 
13445a5ac124SDimitry Andric           MemAccessInfo Access(Ptr, IsWrite);
13455a5ac124SDimitry Andric           DepCands.insert(Access);
13465a5ac124SDimitry Andric 
13475a5ac124SDimitry Andric           // Memorize read-only pointers for later processing and skip them in
13485a5ac124SDimitry Andric           // the first round (they need to be checked after we have seen all
13495a5ac124SDimitry Andric           // write pointers). Note: we also mark pointer that are not
13505a5ac124SDimitry Andric           // consecutive as "read-only" pointers (so that we check
13515a5ac124SDimitry Andric           // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
13525a5ac124SDimitry Andric           if (!UseDeferred && IsReadOnlyPtr) {
1353145449b1SDimitry Andric             // We only use the pointer keys, the types vector values don't
1354145449b1SDimitry Andric             // matter.
1355145449b1SDimitry Andric             DeferredAccesses.insert({Access, {}});
13565a5ac124SDimitry Andric             continue;
13575a5ac124SDimitry Andric           }
13585a5ac124SDimitry Andric 
13595a5ac124SDimitry Andric           // If this is a write - check other reads and writes for conflicts. If
13605a5ac124SDimitry Andric           // this is a read only check other writes for conflicts (but only if
13615a5ac124SDimitry Andric           // there is no other write to the ptr - this is an optimization to
13625a5ac124SDimitry Andric           // catch "a[i] = a[i] + " without having to do a dependence check).
13635a5ac124SDimitry Andric           if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
136471d5a254SDimitry Andric             CheckDeps.push_back(Access);
1365ee8648bdSDimitry Andric             IsRTCheckAnalysisNeeded = true;
13665a5ac124SDimitry Andric           }
13675a5ac124SDimitry Andric 
13685a5ac124SDimitry Andric           if (IsWrite)
13695a5ac124SDimitry Andric             SetHasWrite = true;
13705a5ac124SDimitry Andric 
13715a5ac124SDimitry Andric           // Create sets of pointers connected by a shared alias set and
13725a5ac124SDimitry Andric           // underlying object.
1373e6d15924SDimitry Andric           typedef SmallVector<const Value *, 16> ValueVector;
13745a5ac124SDimitry Andric           ValueVector TempObjects;
13755a5ac124SDimitry Andric 
1376b1c73532SDimitry Andric           UnderlyingObjects[Ptr] = {};
1377b1c73532SDimitry Andric           SmallVector<const Value *, 16> &UOs = UnderlyingObjects[Ptr];
1378b1c73532SDimitry Andric           ::getUnderlyingObjects(Ptr, UOs, LI);
1379eb11fae6SDimitry Andric           LLVM_DEBUG(dbgs()
1380eb11fae6SDimitry Andric                      << "Underlying objects for pointer " << *Ptr << "\n");
1381b1c73532SDimitry Andric           for (const Value *UnderlyingObj : UOs) {
1382dd58ef01SDimitry Andric             // nullptr never alias, don't join sets for pointer that have "null"
1383dd58ef01SDimitry Andric             // in their UnderlyingObjects list.
1384eb11fae6SDimitry Andric             if (isa<ConstantPointerNull>(UnderlyingObj) &&
1385eb11fae6SDimitry Andric                 !NullPointerIsDefined(
1386eb11fae6SDimitry Andric                     TheLoop->getHeader()->getParent(),
1387eb11fae6SDimitry Andric                     UnderlyingObj->getType()->getPointerAddressSpace()))
1388dd58ef01SDimitry Andric               continue;
1389dd58ef01SDimitry Andric 
13905a5ac124SDimitry Andric             UnderlyingObjToAccessMap::iterator Prev =
13915a5ac124SDimitry Andric                 ObjToLastAccess.find(UnderlyingObj);
13925a5ac124SDimitry Andric             if (Prev != ObjToLastAccess.end())
13935a5ac124SDimitry Andric               DepCands.unionSets(Access, Prev->second);
13945a5ac124SDimitry Andric 
13955a5ac124SDimitry Andric             ObjToLastAccess[UnderlyingObj] = Access;
1396eb11fae6SDimitry Andric             LLVM_DEBUG(dbgs() << "  " << *UnderlyingObj << "\n");
13975a5ac124SDimitry Andric           }
13985a5ac124SDimitry Andric         }
13995a5ac124SDimitry Andric       }
14005a5ac124SDimitry Andric     }
14015a5ac124SDimitry Andric   }
14025a5ac124SDimitry Andric }
14035a5ac124SDimitry Andric 
1404eb11fae6SDimitry Andric /// Return true if an AddRec pointer \p Ptr is unsigned non-wrapping,
14051a82d4c0SDimitry Andric /// i.e. monotonically increasing/decreasing.
isNoWrapAddRec(Value * Ptr,const SCEVAddRecExpr * AR,PredicatedScalarEvolution & PSE,const Loop * L)14061a82d4c0SDimitry Andric static bool isNoWrapAddRec(Value *Ptr, const SCEVAddRecExpr *AR,
140701095a5dSDimitry Andric                            PredicatedScalarEvolution &PSE, const Loop *L) {
14087fa27ce4SDimitry Andric 
14091a82d4c0SDimitry Andric   // FIXME: This should probably only return true for NUW.
14101a82d4c0SDimitry Andric   if (AR->getNoWrapFlags(SCEV::NoWrapMask))
14111a82d4c0SDimitry Andric     return true;
14121a82d4c0SDimitry Andric 
14137fa27ce4SDimitry Andric   if (PSE.hasNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW))
14147fa27ce4SDimitry Andric     return true;
14157fa27ce4SDimitry Andric 
14161a82d4c0SDimitry Andric   // Scalar evolution does not propagate the non-wrapping flags to values that
14171a82d4c0SDimitry Andric   // are derived from a non-wrapping induction variable because non-wrapping
14181a82d4c0SDimitry Andric   // could be flow-sensitive.
14191a82d4c0SDimitry Andric   //
14201a82d4c0SDimitry Andric   // Look through the potentially overflowing instruction to try to prove
14211a82d4c0SDimitry Andric   // non-wrapping for the *specific* value of Ptr.
14221a82d4c0SDimitry Andric 
14231a82d4c0SDimitry Andric   // The arithmetic implied by an inbounds GEP can't overflow.
14241a82d4c0SDimitry Andric   auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
14251a82d4c0SDimitry Andric   if (!GEP || !GEP->isInBounds())
14261a82d4c0SDimitry Andric     return false;
14271a82d4c0SDimitry Andric 
14281a82d4c0SDimitry Andric   // Make sure there is only one non-const index and analyze that.
14291a82d4c0SDimitry Andric   Value *NonConstIndex = nullptr;
1430b60736ecSDimitry Andric   for (Value *Index : GEP->indices())
143101095a5dSDimitry Andric     if (!isa<ConstantInt>(Index)) {
14321a82d4c0SDimitry Andric       if (NonConstIndex)
14331a82d4c0SDimitry Andric         return false;
143401095a5dSDimitry Andric       NonConstIndex = Index;
14351a82d4c0SDimitry Andric     }
14361a82d4c0SDimitry Andric   if (!NonConstIndex)
14371a82d4c0SDimitry Andric     // The recurrence is on the pointer, ignore for now.
14381a82d4c0SDimitry Andric     return false;
14391a82d4c0SDimitry Andric 
14401a82d4c0SDimitry Andric   // The index in GEP is signed.  It is non-wrapping if it's derived from a NSW
14411a82d4c0SDimitry Andric   // AddRec using a NSW operation.
14421a82d4c0SDimitry Andric   if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(NonConstIndex))
14431a82d4c0SDimitry Andric     if (OBO->hasNoSignedWrap() &&
14441a82d4c0SDimitry Andric         // Assume constant for other the operand so that the AddRec can be
14451a82d4c0SDimitry Andric         // easily found.
14461a82d4c0SDimitry Andric         isa<ConstantInt>(OBO->getOperand(1))) {
144701095a5dSDimitry Andric       auto *OpScev = PSE.getSCEV(OBO->getOperand(0));
14481a82d4c0SDimitry Andric 
14491a82d4c0SDimitry Andric       if (auto *OpAR = dyn_cast<SCEVAddRecExpr>(OpScev))
14501a82d4c0SDimitry Andric         return OpAR->getLoop() == L && OpAR->getNoWrapFlags(SCEV::FlagNSW);
14511a82d4c0SDimitry Andric     }
14521a82d4c0SDimitry Andric 
14531a82d4c0SDimitry Andric   return false;
14541a82d4c0SDimitry Andric }
14551a82d4c0SDimitry Andric 
1456eb11fae6SDimitry Andric /// Check whether the access through \p Ptr has a constant stride.
1457adf62863SDimitry Andric std::optional<int64_t>
getPtrStride(PredicatedScalarEvolution & PSE,Type * AccessTy,Value * Ptr,const Loop * Lp,const DenseMap<Value *,const SCEV * > & StridesMap,bool Assume,bool ShouldCheckWrap)1458adf62863SDimitry Andric llvm::getPtrStride(PredicatedScalarEvolution &PSE, Type *AccessTy, Value *Ptr,
1459e3b55780SDimitry Andric                    const Loop *Lp,
14607fa27ce4SDimitry Andric                    const DenseMap<Value *, const SCEV *> &StridesMap,
1461e3b55780SDimitry Andric                    bool Assume, bool ShouldCheckWrap) {
1462adf62863SDimitry Andric   const SCEV *PtrScev = replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr);
1463adf62863SDimitry Andric   if (PSE.getSE()->isLoopInvariant(PtrScev, Lp))
1464adf62863SDimitry Andric     return {0};
1465adf62863SDimitry Andric 
1466dd58ef01SDimitry Andric   Type *Ty = Ptr->getType();
14675a5ac124SDimitry Andric   assert(Ty->isPointerTy() && "Unexpected non-ptr");
1468f65dcba8SDimitry Andric   if (isa<ScalableVectorType>(AccessTy)) {
1469f65dcba8SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Bad stride - Scalable object: " << *AccessTy
1470f65dcba8SDimitry Andric                       << "\n");
1471e3b55780SDimitry Andric     return std::nullopt;
14725a5ac124SDimitry Andric   }
14735a5ac124SDimitry Andric 
14745a5ac124SDimitry Andric   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
147501095a5dSDimitry Andric   if (Assume && !AR)
147601095a5dSDimitry Andric     AR = PSE.getAsAddRec(Ptr);
147701095a5dSDimitry Andric 
14785a5ac124SDimitry Andric   if (!AR) {
1479eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer " << *Ptr
148001095a5dSDimitry Andric                       << " SCEV: " << *PtrScev << "\n");
1481e3b55780SDimitry Andric     return std::nullopt;
14825a5ac124SDimitry Andric   }
14835a5ac124SDimitry Andric 
1484e6d15924SDimitry Andric   // The access function must stride over the innermost loop.
14855a5ac124SDimitry Andric   if (Lp != AR->getLoop()) {
1486eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop "
1487eb11fae6SDimitry Andric                       << *Ptr << " SCEV: " << *AR << "\n");
1488e3b55780SDimitry Andric     return std::nullopt;
14895a5ac124SDimitry Andric   }
14905a5ac124SDimitry Andric 
14915a5ac124SDimitry Andric   // Check the step is constant.
1492dd58ef01SDimitry Andric   const SCEV *Step = AR->getStepRecurrence(*PSE.getSE());
14935a5ac124SDimitry Andric 
1494ee8648bdSDimitry Andric   // Calculate the pointer stride and check if it is constant.
14955a5ac124SDimitry Andric   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
14965a5ac124SDimitry Andric   if (!C) {
1497eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr
1498eb11fae6SDimitry Andric                       << " SCEV: " << *AR << "\n");
1499e3b55780SDimitry Andric     return std::nullopt;
15005a5ac124SDimitry Andric   }
15015a5ac124SDimitry Andric 
1502ac9a064cSDimitry Andric   auto &DL = Lp->getHeader()->getDataLayout();
1503f65dcba8SDimitry Andric   TypeSize AllocSize = DL.getTypeAllocSize(AccessTy);
1504e3b55780SDimitry Andric   int64_t Size = AllocSize.getFixedValue();
1505dd58ef01SDimitry Andric   const APInt &APStepVal = C->getAPInt();
15065a5ac124SDimitry Andric 
15075a5ac124SDimitry Andric   // Huge step value - give up.
15085a5ac124SDimitry Andric   if (APStepVal.getBitWidth() > 64)
1509e3b55780SDimitry Andric     return std::nullopt;
15105a5ac124SDimitry Andric 
15115a5ac124SDimitry Andric   int64_t StepVal = APStepVal.getSExtValue();
15125a5ac124SDimitry Andric 
15135a5ac124SDimitry Andric   // Strided access.
15145a5ac124SDimitry Andric   int64_t Stride = StepVal / Size;
15155a5ac124SDimitry Andric   int64_t Rem = StepVal % Size;
15165a5ac124SDimitry Andric   if (Rem)
1517e3b55780SDimitry Andric     return std::nullopt;
15185a5ac124SDimitry Andric 
15197fa27ce4SDimitry Andric   if (!ShouldCheckWrap)
15207fa27ce4SDimitry Andric     return Stride;
15217fa27ce4SDimitry Andric 
15227fa27ce4SDimitry Andric   // The address calculation must not wrap. Otherwise, a dependence could be
15237fa27ce4SDimitry Andric   // inverted.
15247fa27ce4SDimitry Andric   if (isNoWrapAddRec(Ptr, AR, PSE, Lp))
15257fa27ce4SDimitry Andric     return Stride;
15267fa27ce4SDimitry Andric 
15277fa27ce4SDimitry Andric   // An inbounds getelementptr that is a AddRec with a unit stride
15287fa27ce4SDimitry Andric   // cannot wrap per definition.  If it did, the result would be poison
15297fa27ce4SDimitry Andric   // and any memory access dependent on it would be immediate UB
15307fa27ce4SDimitry Andric   // when executed.
15317fa27ce4SDimitry Andric   if (auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
15327fa27ce4SDimitry Andric       GEP && GEP->isInBounds() && (Stride == 1 || Stride == -1))
15337fa27ce4SDimitry Andric     return Stride;
15347fa27ce4SDimitry Andric 
15357fa27ce4SDimitry Andric   // If the null pointer is undefined, then a access sequence which would
15367fa27ce4SDimitry Andric   // otherwise access it can be assumed not to unsigned wrap.  Note that this
15377fa27ce4SDimitry Andric   // assumes the object in memory is aligned to the natural alignment.
15387fa27ce4SDimitry Andric   unsigned AddrSpace = Ty->getPointerAddressSpace();
15397fa27ce4SDimitry Andric   if (!NullPointerIsDefined(Lp->getHeader()->getParent(), AddrSpace) &&
15407fa27ce4SDimitry Andric       (Stride == 1 || Stride == -1))
15417fa27ce4SDimitry Andric     return Stride;
15427fa27ce4SDimitry Andric 
154301095a5dSDimitry Andric   if (Assume) {
15447fa27ce4SDimitry Andric     PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
15457fa27ce4SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Pointer may wrap:\n"
154601095a5dSDimitry Andric                       << "LAA:   Pointer: " << *Ptr << "\n"
154701095a5dSDimitry Andric                       << "LAA:   SCEV: " << *AR << "\n"
154801095a5dSDimitry Andric                       << "LAA:   Added an overflow assumption\n");
15495a5ac124SDimitry Andric     return Stride;
15505a5ac124SDimitry Andric   }
15517fa27ce4SDimitry Andric   LLVM_DEBUG(
15527fa27ce4SDimitry Andric       dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
15537fa27ce4SDimitry Andric              << *Ptr << " SCEV: " << *AR << "\n");
15547fa27ce4SDimitry Andric   return std::nullopt;
15557fa27ce4SDimitry Andric }
15565a5ac124SDimitry Andric 
getPointersDiff(Type * ElemTyA,Value * PtrA,Type * ElemTyB,Value * PtrB,const DataLayout & DL,ScalarEvolution & SE,bool StrictCheck,bool CheckType)1557e3b55780SDimitry Andric std::optional<int> llvm::getPointersDiff(Type *ElemTyA, Value *PtrA,
1558e3b55780SDimitry Andric                                          Type *ElemTyB, Value *PtrB,
1559e3b55780SDimitry Andric                                          const DataLayout &DL,
1560344a3780SDimitry Andric                                          ScalarEvolution &SE, bool StrictCheck,
1561344a3780SDimitry Andric                                          bool CheckType) {
1562344a3780SDimitry Andric   assert(PtrA && PtrB && "Expected non-nullptr pointers.");
1563344a3780SDimitry Andric 
1564344a3780SDimitry Andric   // Make sure that A and B are different pointers.
1565344a3780SDimitry Andric   if (PtrA == PtrB)
1566344a3780SDimitry Andric     return 0;
1567344a3780SDimitry Andric 
1568344a3780SDimitry Andric   // Make sure that the element types are the same if required.
1569344a3780SDimitry Andric   if (CheckType && ElemTyA != ElemTyB)
1570e3b55780SDimitry Andric     return std::nullopt;
1571344a3780SDimitry Andric 
1572344a3780SDimitry Andric   unsigned ASA = PtrA->getType()->getPointerAddressSpace();
1573344a3780SDimitry Andric   unsigned ASB = PtrB->getType()->getPointerAddressSpace();
1574344a3780SDimitry Andric 
1575344a3780SDimitry Andric   // Check that the address spaces match.
1576344a3780SDimitry Andric   if (ASA != ASB)
1577e3b55780SDimitry Andric     return std::nullopt;
1578344a3780SDimitry Andric   unsigned IdxWidth = DL.getIndexSizeInBits(ASA);
1579344a3780SDimitry Andric 
1580344a3780SDimitry Andric   APInt OffsetA(IdxWidth, 0), OffsetB(IdxWidth, 0);
1581344a3780SDimitry Andric   Value *PtrA1 = PtrA->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetA);
1582344a3780SDimitry Andric   Value *PtrB1 = PtrB->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetB);
1583344a3780SDimitry Andric 
1584344a3780SDimitry Andric   int Val;
1585344a3780SDimitry Andric   if (PtrA1 == PtrB1) {
1586344a3780SDimitry Andric     // Retrieve the address space again as pointer stripping now tracks through
1587344a3780SDimitry Andric     // `addrspacecast`.
1588344a3780SDimitry Andric     ASA = cast<PointerType>(PtrA1->getType())->getAddressSpace();
1589344a3780SDimitry Andric     ASB = cast<PointerType>(PtrB1->getType())->getAddressSpace();
1590344a3780SDimitry Andric     // Check that the address spaces match and that the pointers are valid.
1591344a3780SDimitry Andric     if (ASA != ASB)
1592e3b55780SDimitry Andric       return std::nullopt;
1593344a3780SDimitry Andric 
1594344a3780SDimitry Andric     IdxWidth = DL.getIndexSizeInBits(ASA);
1595344a3780SDimitry Andric     OffsetA = OffsetA.sextOrTrunc(IdxWidth);
1596344a3780SDimitry Andric     OffsetB = OffsetB.sextOrTrunc(IdxWidth);
1597344a3780SDimitry Andric 
1598344a3780SDimitry Andric     OffsetB -= OffsetA;
1599344a3780SDimitry Andric     Val = OffsetB.getSExtValue();
1600344a3780SDimitry Andric   } else {
1601344a3780SDimitry Andric     // Otherwise compute the distance with SCEV between the base pointers.
1602344a3780SDimitry Andric     const SCEV *PtrSCEVA = SE.getSCEV(PtrA);
1603344a3780SDimitry Andric     const SCEV *PtrSCEVB = SE.getSCEV(PtrB);
1604344a3780SDimitry Andric     const auto *Diff =
1605344a3780SDimitry Andric         dyn_cast<SCEVConstant>(SE.getMinusSCEV(PtrSCEVB, PtrSCEVA));
1606344a3780SDimitry Andric     if (!Diff)
1607e3b55780SDimitry Andric       return std::nullopt;
1608344a3780SDimitry Andric     Val = Diff->getAPInt().getSExtValue();
1609344a3780SDimitry Andric   }
1610344a3780SDimitry Andric   int Size = DL.getTypeStoreSize(ElemTyA);
1611344a3780SDimitry Andric   int Dist = Val / Size;
1612344a3780SDimitry Andric 
1613344a3780SDimitry Andric   // Ensure that the calculated distance matches the type-based one after all
1614344a3780SDimitry Andric   // the bitcasts removal in the provided pointers.
1615344a3780SDimitry Andric   if (!StrictCheck || Dist * Size == Val)
1616344a3780SDimitry Andric     return Dist;
1617e3b55780SDimitry Andric   return std::nullopt;
1618344a3780SDimitry Andric }
1619344a3780SDimitry Andric 
sortPtrAccesses(ArrayRef<Value * > VL,Type * ElemTy,const DataLayout & DL,ScalarEvolution & SE,SmallVectorImpl<unsigned> & SortedIndices)1620344a3780SDimitry Andric bool llvm::sortPtrAccesses(ArrayRef<Value *> VL, Type *ElemTy,
1621344a3780SDimitry Andric                            const DataLayout &DL, ScalarEvolution &SE,
1622eb11fae6SDimitry Andric                            SmallVectorImpl<unsigned> &SortedIndices) {
1623eb11fae6SDimitry Andric   assert(llvm::all_of(
1624eb11fae6SDimitry Andric              VL, [](const Value *V) { return V->getType()->isPointerTy(); }) &&
1625eb11fae6SDimitry Andric          "Expected list of pointer operands.");
1626eb11fae6SDimitry Andric   // Walk over the pointers, and map each of them to an offset relative to
1627eb11fae6SDimitry Andric   // first pointer in the array.
1628eb11fae6SDimitry Andric   Value *Ptr0 = VL[0];
1629eb11fae6SDimitry Andric 
1630344a3780SDimitry Andric   using DistOrdPair = std::pair<int64_t, int>;
163108e8dd7bSDimitry Andric   auto Compare = llvm::less_first();
1632344a3780SDimitry Andric   std::set<DistOrdPair, decltype(Compare)> Offsets(Compare);
1633344a3780SDimitry Andric   Offsets.emplace(0, 0);
1634344a3780SDimitry Andric   bool IsConsecutive = true;
1635ac9a064cSDimitry Andric   for (auto [Idx, Ptr] : drop_begin(enumerate(VL))) {
1636e3b55780SDimitry Andric     std::optional<int> Diff = getPointersDiff(ElemTy, Ptr0, ElemTy, Ptr, DL, SE,
1637344a3780SDimitry Andric                                               /*StrictCheck=*/true);
1638eb11fae6SDimitry Andric     if (!Diff)
1639eb11fae6SDimitry Andric       return false;
1640eb11fae6SDimitry Andric 
1641eb11fae6SDimitry Andric     // Check if the pointer with the same offset is found.
1642344a3780SDimitry Andric     int64_t Offset = *Diff;
1643ac9a064cSDimitry Andric     auto [It, IsInserted] = Offsets.emplace(Offset, Idx);
1644ac9a064cSDimitry Andric     if (!IsInserted)
1645eb11fae6SDimitry Andric       return false;
1646344a3780SDimitry Andric     // Consecutive order if the inserted element is the last one.
1647ac9a064cSDimitry Andric     IsConsecutive &= std::next(It) == Offsets.end();
1648eb11fae6SDimitry Andric   }
1649eb11fae6SDimitry Andric   SortedIndices.clear();
1650344a3780SDimitry Andric   if (!IsConsecutive) {
1651344a3780SDimitry Andric     // Fill SortedIndices array only if it is non-consecutive.
1652eb11fae6SDimitry Andric     SortedIndices.resize(VL.size());
1653ac9a064cSDimitry Andric     for (auto [Idx, Off] : enumerate(Offsets))
1654ac9a064cSDimitry Andric       SortedIndices[Idx] = Off.second;
1655344a3780SDimitry Andric   }
1656344a3780SDimitry Andric   return true;
165701095a5dSDimitry Andric }
165801095a5dSDimitry Andric 
165901095a5dSDimitry Andric /// Returns true if the memory operations \p A and \p B are consecutive.
isConsecutiveAccess(Value * A,Value * B,const DataLayout & DL,ScalarEvolution & SE,bool CheckType)166001095a5dSDimitry Andric bool llvm::isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL,
166101095a5dSDimitry Andric                                ScalarEvolution &SE, bool CheckType) {
1662eb11fae6SDimitry Andric   Value *PtrA = getLoadStorePointerOperand(A);
1663eb11fae6SDimitry Andric   Value *PtrB = getLoadStorePointerOperand(B);
1664344a3780SDimitry Andric   if (!PtrA || !PtrB)
166501095a5dSDimitry Andric     return false;
1666344a3780SDimitry Andric   Type *ElemTyA = getLoadStoreType(A);
1667344a3780SDimitry Andric   Type *ElemTyB = getLoadStoreType(B);
1668e3b55780SDimitry Andric   std::optional<int> Diff =
1669e3b55780SDimitry Andric       getPointersDiff(ElemTyA, PtrA, ElemTyB, PtrB, DL, SE,
1670344a3780SDimitry Andric                       /*StrictCheck=*/true, CheckType);
1671344a3780SDimitry Andric   return Diff && *Diff == 1;
167201095a5dSDimitry Andric }
167301095a5dSDimitry Andric 
addAccess(StoreInst * SI)1674c0981da4SDimitry Andric void MemoryDepChecker::addAccess(StoreInst *SI) {
1675c0981da4SDimitry Andric   visitPointers(SI->getPointerOperand(), *InnermostLoop,
1676c0981da4SDimitry Andric                 [this, SI](Value *Ptr) {
1677c0981da4SDimitry Andric                   Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
1678c0981da4SDimitry Andric                   InstMap.push_back(SI);
1679c0981da4SDimitry Andric                   ++AccessIdx;
1680c0981da4SDimitry Andric                 });
1681c0981da4SDimitry Andric }
1682c0981da4SDimitry Andric 
addAccess(LoadInst * LI)1683c0981da4SDimitry Andric void MemoryDepChecker::addAccess(LoadInst *LI) {
1684c0981da4SDimitry Andric   visitPointers(LI->getPointerOperand(), *InnermostLoop,
1685c0981da4SDimitry Andric                 [this, LI](Value *Ptr) {
1686c0981da4SDimitry Andric                   Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
1687c0981da4SDimitry Andric                   InstMap.push_back(LI);
1688c0981da4SDimitry Andric                   ++AccessIdx;
1689c0981da4SDimitry Andric                 });
1690c0981da4SDimitry Andric }
1691c0981da4SDimitry Andric 
1692d8e91e46SDimitry Andric MemoryDepChecker::VectorizationSafetyStatus
isSafeForVectorization(DepType Type)1693d8e91e46SDimitry Andric MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
16945a5ac124SDimitry Andric   switch (Type) {
16955a5ac124SDimitry Andric   case NoDep:
16965a5ac124SDimitry Andric   case Forward:
16975a5ac124SDimitry Andric   case BackwardVectorizable:
1698d8e91e46SDimitry Andric     return VectorizationSafetyStatus::Safe;
16995a5ac124SDimitry Andric 
17005a5ac124SDimitry Andric   case Unknown:
1701d8e91e46SDimitry Andric     return VectorizationSafetyStatus::PossiblySafeWithRtChecks;
17025a5ac124SDimitry Andric   case ForwardButPreventsForwarding:
17035a5ac124SDimitry Andric   case Backward:
17045a5ac124SDimitry Andric   case BackwardVectorizableButPreventsForwarding:
1705b1c73532SDimitry Andric   case IndirectUnsafe:
1706d8e91e46SDimitry Andric     return VectorizationSafetyStatus::Unsafe;
17075a5ac124SDimitry Andric   }
17085a5ac124SDimitry Andric   llvm_unreachable("unexpected DepType!");
17095a5ac124SDimitry Andric }
17105a5ac124SDimitry Andric 
isBackward() const1711dd58ef01SDimitry Andric bool MemoryDepChecker::Dependence::isBackward() const {
17125a5ac124SDimitry Andric   switch (Type) {
17135a5ac124SDimitry Andric   case NoDep:
17145a5ac124SDimitry Andric   case Forward:
1715dd58ef01SDimitry Andric   case ForwardButPreventsForwarding:
1716dd58ef01SDimitry Andric   case Unknown:
1717b1c73532SDimitry Andric   case IndirectUnsafe:
17185a5ac124SDimitry Andric     return false;
17195a5ac124SDimitry Andric 
17205a5ac124SDimitry Andric   case BackwardVectorizable:
17215a5ac124SDimitry Andric   case Backward:
17225a5ac124SDimitry Andric   case BackwardVectorizableButPreventsForwarding:
17235a5ac124SDimitry Andric     return true;
17245a5ac124SDimitry Andric   }
17255a5ac124SDimitry Andric   llvm_unreachable("unexpected DepType!");
17265a5ac124SDimitry Andric }
17275a5ac124SDimitry Andric 
isPossiblyBackward() const17285a5ac124SDimitry Andric bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
1729ac9a064cSDimitry Andric   return isBackward() || Type == Unknown || Type == IndirectUnsafe;
1730dd58ef01SDimitry Andric }
1731dd58ef01SDimitry Andric 
isForward() const1732dd58ef01SDimitry Andric bool MemoryDepChecker::Dependence::isForward() const {
17335a5ac124SDimitry Andric   switch (Type) {
17345a5ac124SDimitry Andric   case Forward:
17355a5ac124SDimitry Andric   case ForwardButPreventsForwarding:
1736dd58ef01SDimitry Andric     return true;
17375a5ac124SDimitry Andric 
1738dd58ef01SDimitry Andric   case NoDep:
17395a5ac124SDimitry Andric   case Unknown:
17405a5ac124SDimitry Andric   case BackwardVectorizable:
17415a5ac124SDimitry Andric   case Backward:
17425a5ac124SDimitry Andric   case BackwardVectorizableButPreventsForwarding:
1743b1c73532SDimitry Andric   case IndirectUnsafe:
1744dd58ef01SDimitry Andric     return false;
17455a5ac124SDimitry Andric   }
17465a5ac124SDimitry Andric   llvm_unreachable("unexpected DepType!");
17475a5ac124SDimitry Andric }
17485a5ac124SDimitry Andric 
couldPreventStoreLoadForward(uint64_t Distance,uint64_t TypeByteSize)174901095a5dSDimitry Andric bool MemoryDepChecker::couldPreventStoreLoadForward(uint64_t Distance,
175001095a5dSDimitry Andric                                                     uint64_t TypeByteSize) {
17515a5ac124SDimitry Andric   // If loads occur at a distance that is not a multiple of a feasible vector
17525a5ac124SDimitry Andric   // factor store-load forwarding does not take place.
17535a5ac124SDimitry Andric   // Positive dependences might cause troubles because vectorizing them might
17545a5ac124SDimitry Andric   // prevent store-load forwarding making vectorized code run a lot slower.
17555a5ac124SDimitry Andric   //   a[i] = a[i-3] ^ a[i-8];
17565a5ac124SDimitry Andric   //   The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
17575a5ac124SDimitry Andric   //   hence on your typical architecture store-load forwarding does not take
17585a5ac124SDimitry Andric   //   place. Vectorizing in such cases does not make sense.
17595a5ac124SDimitry Andric   // Store-load forwarding distance.
17605a5ac124SDimitry Andric 
176101095a5dSDimitry Andric   // After this many iterations store-to-load forwarding conflicts should not
176201095a5dSDimitry Andric   // cause any slowdowns.
176301095a5dSDimitry Andric   const uint64_t NumItersForStoreLoadThroughMemory = 8 * TypeByteSize;
176401095a5dSDimitry Andric   // Maximum vector factor.
176501095a5dSDimitry Andric   uint64_t MaxVFWithoutSLForwardIssues = std::min(
1766b1c73532SDimitry Andric       VectorizerParams::MaxVectorWidth * TypeByteSize, MinDepDistBytes);
176701095a5dSDimitry Andric 
176801095a5dSDimitry Andric   // Compute the smallest VF at which the store and load would be misaligned.
176901095a5dSDimitry Andric   for (uint64_t VF = 2 * TypeByteSize; VF <= MaxVFWithoutSLForwardIssues;
177001095a5dSDimitry Andric        VF *= 2) {
177101095a5dSDimitry Andric     // If the number of vector iteration between the store and the load are
177201095a5dSDimitry Andric     // small we could incur conflicts.
177301095a5dSDimitry Andric     if (Distance % VF && Distance / VF < NumItersForStoreLoadThroughMemory) {
1774b60736ecSDimitry Andric       MaxVFWithoutSLForwardIssues = (VF >> 1);
17755a5ac124SDimitry Andric       break;
17765a5ac124SDimitry Andric     }
17775a5ac124SDimitry Andric   }
17785a5ac124SDimitry Andric 
17795a5ac124SDimitry Andric   if (MaxVFWithoutSLForwardIssues < 2 * TypeByteSize) {
1780eb11fae6SDimitry Andric     LLVM_DEBUG(
1781eb11fae6SDimitry Andric         dbgs() << "LAA: Distance " << Distance
178201095a5dSDimitry Andric                << " that could cause a store-load forwarding conflict\n");
17835a5ac124SDimitry Andric     return true;
17845a5ac124SDimitry Andric   }
17855a5ac124SDimitry Andric 
1786b1c73532SDimitry Andric   if (MaxVFWithoutSLForwardIssues < MinDepDistBytes &&
17875a5ac124SDimitry Andric       MaxVFWithoutSLForwardIssues !=
17885a5ac124SDimitry Andric           VectorizerParams::MaxVectorWidth * TypeByteSize)
1789b1c73532SDimitry Andric     MinDepDistBytes = MaxVFWithoutSLForwardIssues;
17905a5ac124SDimitry Andric   return false;
17915a5ac124SDimitry Andric }
17925a5ac124SDimitry Andric 
mergeInStatus(VectorizationSafetyStatus S)1793d8e91e46SDimitry Andric void MemoryDepChecker::mergeInStatus(VectorizationSafetyStatus S) {
1794d8e91e46SDimitry Andric   if (Status < S)
1795d8e91e46SDimitry Andric     Status = S;
1796d8e91e46SDimitry Andric }
1797d8e91e46SDimitry Andric 
1798e3b55780SDimitry Andric /// Given a dependence-distance \p Dist between two
1799ac9a064cSDimitry Andric /// memory accesses, that have strides in the same direction whose absolute
1800ac9a064cSDimitry Andric /// value of the maximum stride is given in \p MaxStride, and that have the same
1801ac9a064cSDimitry Andric /// type size \p TypeByteSize, in a loop whose maximum backedge taken count is
1802ac9a064cSDimitry Andric /// \p MaxBTC, check if it is possible to prove statically that the dependence
1803ac9a064cSDimitry Andric /// distance is larger than the range that the accesses will travel through the
1804ac9a064cSDimitry Andric /// execution of the loop. If so, return true; false otherwise. This is useful
1805ac9a064cSDimitry Andric /// for example in loops such as the following (PR31098):
180671d5a254SDimitry Andric ///     for (i = 0; i < D; ++i) {
180771d5a254SDimitry Andric ///                = out[i];
180871d5a254SDimitry Andric ///       out[i+D] =
180971d5a254SDimitry Andric ///     }
isSafeDependenceDistance(const DataLayout & DL,ScalarEvolution & SE,const SCEV & MaxBTC,const SCEV & Dist,uint64_t MaxStride,uint64_t TypeByteSize)181071d5a254SDimitry Andric static bool isSafeDependenceDistance(const DataLayout &DL, ScalarEvolution &SE,
1811ac9a064cSDimitry Andric                                      const SCEV &MaxBTC, const SCEV &Dist,
1812ac9a064cSDimitry Andric                                      uint64_t MaxStride,
181371d5a254SDimitry Andric                                      uint64_t TypeByteSize) {
181471d5a254SDimitry Andric 
181571d5a254SDimitry Andric   // If we can prove that
1816ac9a064cSDimitry Andric   //      (**) |Dist| > MaxBTC * Step
181771d5a254SDimitry Andric   // where Step is the absolute stride of the memory accesses in bytes,
181871d5a254SDimitry Andric   // then there is no dependence.
181971d5a254SDimitry Andric   //
1820e6d15924SDimitry Andric   // Rationale:
182171d5a254SDimitry Andric   // We basically want to check if the absolute distance (|Dist/Step|)
1822ac9a064cSDimitry Andric   // is >= the loop iteration count (or > MaxBTC).
182371d5a254SDimitry Andric   // This is equivalent to the Strong SIV Test (Practical Dependence Testing,
182471d5a254SDimitry Andric   // Section 4.2.1); Note, that for vectorization it is sufficient to prove
182571d5a254SDimitry Andric   // that the dependence distance is >= VF; This is checked elsewhere.
1826e3b55780SDimitry Andric   // But in some cases we can prune dependence distances early, and
182771d5a254SDimitry Andric   // even before selecting the VF, and without a runtime test, by comparing
182871d5a254SDimitry Andric   // the distance against the loop iteration count. Since the vectorized code
182971d5a254SDimitry Andric   // will be executed only if LoopCount >= VF, proving distance >= LoopCount
183071d5a254SDimitry Andric   // also guarantees that distance >= VF.
183171d5a254SDimitry Andric   //
1832ac9a064cSDimitry Andric   const uint64_t ByteStride = MaxStride * TypeByteSize;
1833ac9a064cSDimitry Andric   const SCEV *Step = SE.getConstant(MaxBTC.getType(), ByteStride);
1834ac9a064cSDimitry Andric   const SCEV *Product = SE.getMulExpr(&MaxBTC, Step);
183571d5a254SDimitry Andric 
183671d5a254SDimitry Andric   const SCEV *CastedDist = &Dist;
183771d5a254SDimitry Andric   const SCEV *CastedProduct = Product;
1838145449b1SDimitry Andric   uint64_t DistTypeSizeBits = DL.getTypeSizeInBits(Dist.getType());
1839145449b1SDimitry Andric   uint64_t ProductTypeSizeBits = DL.getTypeSizeInBits(Product->getType());
184071d5a254SDimitry Andric 
184171d5a254SDimitry Andric   // The dependence distance can be positive/negative, so we sign extend Dist;
184271d5a254SDimitry Andric   // The multiplication of the absolute stride in bytes and the
1843e6d15924SDimitry Andric   // backedgeTakenCount is non-negative, so we zero extend Product.
1844145449b1SDimitry Andric   if (DistTypeSizeBits > ProductTypeSizeBits)
184571d5a254SDimitry Andric     CastedProduct = SE.getZeroExtendExpr(Product, Dist.getType());
184671d5a254SDimitry Andric   else
184771d5a254SDimitry Andric     CastedDist = SE.getNoopOrSignExtend(&Dist, Product->getType());
184871d5a254SDimitry Andric 
1849ac9a064cSDimitry Andric   // Is  Dist - (MaxBTC * Step) > 0 ?
185071d5a254SDimitry Andric   // (If so, then we have proven (**) because |Dist| >= Dist)
185171d5a254SDimitry Andric   const SCEV *Minus = SE.getMinusSCEV(CastedDist, CastedProduct);
185271d5a254SDimitry Andric   if (SE.isKnownPositive(Minus))
185371d5a254SDimitry Andric     return true;
185471d5a254SDimitry Andric 
1855ac9a064cSDimitry Andric   // Second try: Is  -Dist - (MaxBTC * Step) > 0 ?
185671d5a254SDimitry Andric   // (If so, then we have proven (**) because |Dist| >= -1*Dist)
185771d5a254SDimitry Andric   const SCEV *NegDist = SE.getNegativeSCEV(CastedDist);
185871d5a254SDimitry Andric   Minus = SE.getMinusSCEV(NegDist, CastedProduct);
1859ac9a064cSDimitry Andric   return SE.isKnownPositive(Minus);
186071d5a254SDimitry Andric }
186171d5a254SDimitry Andric 
1862eb11fae6SDimitry Andric /// Check the dependence for two accesses with the same stride \p Stride.
186385d8b2bbSDimitry Andric /// \p Distance is the positive distance and \p TypeByteSize is type size in
186485d8b2bbSDimitry Andric /// bytes.
186585d8b2bbSDimitry Andric ///
186685d8b2bbSDimitry Andric /// \returns true if they are independent.
areStridedAccessesIndependent(uint64_t Distance,uint64_t Stride,uint64_t TypeByteSize)186701095a5dSDimitry Andric static bool areStridedAccessesIndependent(uint64_t Distance, uint64_t Stride,
186801095a5dSDimitry Andric                                           uint64_t TypeByteSize) {
186985d8b2bbSDimitry Andric   assert(Stride > 1 && "The stride must be greater than 1");
187085d8b2bbSDimitry Andric   assert(TypeByteSize > 0 && "The type size in byte must be non-zero");
187185d8b2bbSDimitry Andric   assert(Distance > 0 && "The distance must be non-zero");
187285d8b2bbSDimitry Andric 
187385d8b2bbSDimitry Andric   // Skip if the distance is not multiple of type byte size.
187485d8b2bbSDimitry Andric   if (Distance % TypeByteSize)
187585d8b2bbSDimitry Andric     return false;
187685d8b2bbSDimitry Andric 
187701095a5dSDimitry Andric   uint64_t ScaledDist = Distance / TypeByteSize;
187885d8b2bbSDimitry Andric 
187985d8b2bbSDimitry Andric   // No dependence if the scaled distance is not multiple of the stride.
188085d8b2bbSDimitry Andric   // E.g.
188185d8b2bbSDimitry Andric   //      for (i = 0; i < 1024 ; i += 4)
188285d8b2bbSDimitry Andric   //        A[i+2] = A[i] + 1;
188385d8b2bbSDimitry Andric   //
188485d8b2bbSDimitry Andric   // Two accesses in memory (scaled distance is 2, stride is 4):
188585d8b2bbSDimitry Andric   //     | A[0] |      |      |      | A[4] |      |      |      |
188685d8b2bbSDimitry Andric   //     |      |      | A[2] |      |      |      | A[6] |      |
188785d8b2bbSDimitry Andric   //
188885d8b2bbSDimitry Andric   // E.g.
188985d8b2bbSDimitry Andric   //      for (i = 0; i < 1024 ; i += 3)
189085d8b2bbSDimitry Andric   //        A[i+4] = A[i] + 1;
189185d8b2bbSDimitry Andric   //
189285d8b2bbSDimitry Andric   // Two accesses in memory (scaled distance is 4, stride is 3):
189385d8b2bbSDimitry Andric   //     | A[0] |      |      | A[3] |      |      | A[6] |      |      |
189485d8b2bbSDimitry Andric   //     |      |      |      |      | A[4] |      |      | A[7] |      |
189585d8b2bbSDimitry Andric   return ScaledDist % Stride;
189685d8b2bbSDimitry Andric }
189785d8b2bbSDimitry Andric 
1898ac9a064cSDimitry Andric std::variant<MemoryDepChecker::Dependence::DepType,
1899ac9a064cSDimitry Andric              MemoryDepChecker::DepDistanceStrideAndSizeInfo>
getDependenceDistanceStrideAndSize(const AccessAnalysis::MemAccessInfo & A,Instruction * AInst,const AccessAnalysis::MemAccessInfo & B,Instruction * BInst)1900ac9a064cSDimitry Andric MemoryDepChecker::getDependenceDistanceStrideAndSize(
1901b1c73532SDimitry Andric     const AccessAnalysis::MemAccessInfo &A, Instruction *AInst,
1902adf62863SDimitry Andric     const AccessAnalysis::MemAccessInfo &B, Instruction *BInst) {
1903adf62863SDimitry Andric   const auto &DL = InnermostLoop->getHeader()->getDataLayout();
1904b1c73532SDimitry Andric   auto &SE = *PSE.getSE();
1905e3b55780SDimitry Andric   auto [APtr, AIsWrite] = A;
1906e3b55780SDimitry Andric   auto [BPtr, BIsWrite] = B;
19075a5ac124SDimitry Andric 
19085a5ac124SDimitry Andric   // Two reads are independent.
19095a5ac124SDimitry Andric   if (!AIsWrite && !BIsWrite)
1910b1c73532SDimitry Andric     return MemoryDepChecker::Dependence::NoDep;
1911b1c73532SDimitry Andric 
1912b1c73532SDimitry Andric   Type *ATy = getLoadStoreType(AInst);
1913b1c73532SDimitry Andric   Type *BTy = getLoadStoreType(BInst);
19145a5ac124SDimitry Andric 
19155a5ac124SDimitry Andric   // We cannot check pointers in different address spaces.
19165a5ac124SDimitry Andric   if (APtr->getType()->getPointerAddressSpace() !=
19175a5ac124SDimitry Andric       BPtr->getType()->getPointerAddressSpace())
1918b1c73532SDimitry Andric     return MemoryDepChecker::Dependence::Unknown;
19195a5ac124SDimitry Andric 
1920adf62863SDimitry Andric   std::optional<int64_t> StrideAPtr =
1921adf62863SDimitry Andric       getPtrStride(PSE, ATy, APtr, InnermostLoop, SymbolicStrides, true, true);
1922adf62863SDimitry Andric   std::optional<int64_t> StrideBPtr =
1923adf62863SDimitry Andric       getPtrStride(PSE, BTy, BPtr, InnermostLoop, SymbolicStrides, true, true);
19245a5ac124SDimitry Andric 
192501095a5dSDimitry Andric   const SCEV *Src = PSE.getSCEV(APtr);
192601095a5dSDimitry Andric   const SCEV *Sink = PSE.getSCEV(BPtr);
19275a5ac124SDimitry Andric 
19285a5ac124SDimitry Andric   // If the induction step is negative we have to invert source and sink of the
1929b1c73532SDimitry Andric   // dependence when measuring the distance between them. We should not swap
1930b1c73532SDimitry Andric   // AIsWrite with BIsWrite, as their uses expect them in program order.
1931adf62863SDimitry Andric   if (StrideAPtr && *StrideAPtr < 0) {
19325a5ac124SDimitry Andric     std::swap(Src, Sink);
1933b1c73532SDimitry Andric     std::swap(AInst, BInst);
1934adf62863SDimitry Andric     std::swap(StrideAPtr, StrideBPtr);
19355a5ac124SDimitry Andric   }
19365a5ac124SDimitry Andric 
1937e3b55780SDimitry Andric   const SCEV *Dist = SE.getMinusSCEV(Sink, Src);
19385a5ac124SDimitry Andric 
1939eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
1940adf62863SDimitry Andric                     << "\n");
1941b1c73532SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: Distance for " << *AInst << " to " << *BInst
1942b1c73532SDimitry Andric                     << ": " << *Dist << "\n");
1943b1c73532SDimitry Andric 
1944ac9a064cSDimitry Andric   // Check if we can prove that Sink only accesses memory after Src's end or
1945ac9a064cSDimitry Andric   // vice versa. At the moment this is limited to cases where either source or
1946ac9a064cSDimitry Andric   // sink are loop invariant to avoid compile-time increases. This is not
1947ac9a064cSDimitry Andric   // required for correctness.
1948ac9a064cSDimitry Andric   if (SE.isLoopInvariant(Src, InnermostLoop) ||
1949ac9a064cSDimitry Andric       SE.isLoopInvariant(Sink, InnermostLoop)) {
1950ac9a064cSDimitry Andric     const auto &[SrcStart, SrcEnd] =
1951ac9a064cSDimitry Andric         getStartAndEndForAccess(InnermostLoop, Src, ATy, PSE, PointerBounds);
1952ac9a064cSDimitry Andric     const auto &[SinkStart, SinkEnd] =
1953ac9a064cSDimitry Andric         getStartAndEndForAccess(InnermostLoop, Sink, BTy, PSE, PointerBounds);
1954ac9a064cSDimitry Andric     if (!isa<SCEVCouldNotCompute>(SrcStart) &&
1955ac9a064cSDimitry Andric         !isa<SCEVCouldNotCompute>(SrcEnd) &&
1956ac9a064cSDimitry Andric         !isa<SCEVCouldNotCompute>(SinkStart) &&
1957ac9a064cSDimitry Andric         !isa<SCEVCouldNotCompute>(SinkEnd)) {
1958ac9a064cSDimitry Andric       if (SE.isKnownPredicate(CmpInst::ICMP_ULE, SrcEnd, SinkStart))
1959ac9a064cSDimitry Andric         return MemoryDepChecker::Dependence::NoDep;
1960ac9a064cSDimitry Andric       if (SE.isKnownPredicate(CmpInst::ICMP_ULE, SinkEnd, SrcStart))
1961ac9a064cSDimitry Andric         return MemoryDepChecker::Dependence::NoDep;
1962ac9a064cSDimitry Andric     }
1963ac9a064cSDimitry Andric   }
1964ac9a064cSDimitry Andric 
1965adf62863SDimitry Andric   // Need accesses with constant strides and the same direction for further
1966adf62863SDimitry Andric   // dependence analysis. We don't want to vectorize "A[B[i]] += ..." and
1967adf62863SDimitry Andric   // similar code or pointer arithmetic that could wrap in the address space.
1968adf62863SDimitry Andric 
1969adf62863SDimitry Andric   // If either Src or Sink are not strided (i.e. not a non-wrapping AddRec) and
1970adf62863SDimitry Andric   // not loop-invariant (stride will be 0 in that case), we cannot analyze the
1971adf62863SDimitry Andric   // dependence further and also cannot generate runtime checks.
1972adf62863SDimitry Andric   if (!StrideAPtr || !StrideBPtr) {
1973eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "Pointer access with non-constant stride\n");
1974adf62863SDimitry Andric     return MemoryDepChecker::Dependence::IndirectUnsafe;
1975adf62863SDimitry Andric   }
1976adf62863SDimitry Andric 
1977adf62863SDimitry Andric   int64_t StrideAPtrInt = *StrideAPtr;
1978adf62863SDimitry Andric   int64_t StrideBPtrInt = *StrideBPtr;
1979adf62863SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA:  Src induction step: " << StrideAPtrInt
1980adf62863SDimitry Andric                     << " Sink induction step: " << StrideBPtrInt << "\n");
1981adf62863SDimitry Andric   // At least Src or Sink are loop invariant and the other is strided or
1982adf62863SDimitry Andric   // invariant. We can generate a runtime check to disambiguate the accesses.
1983adf62863SDimitry Andric   if (StrideAPtrInt == 0 || StrideBPtrInt == 0)
1984adf62863SDimitry Andric     return MemoryDepChecker::Dependence::Unknown;
1985adf62863SDimitry Andric 
1986adf62863SDimitry Andric   // Both Src and Sink have a constant stride, check if they are in the same
1987adf62863SDimitry Andric   // direction.
1988adf62863SDimitry Andric   if ((StrideAPtrInt > 0 && StrideBPtrInt < 0) ||
1989adf62863SDimitry Andric       (StrideAPtrInt < 0 && StrideBPtrInt > 0)) {
1990adf62863SDimitry Andric     LLVM_DEBUG(
1991adf62863SDimitry Andric         dbgs() << "Pointer access with strides in different directions\n");
1992b1c73532SDimitry Andric     return MemoryDepChecker::Dependence::Unknown;
19935a5ac124SDimitry Andric   }
19945a5ac124SDimitry Andric 
199571d5a254SDimitry Andric   uint64_t TypeByteSize = DL.getTypeAllocSize(ATy);
199677fc4c14SDimitry Andric   bool HasSameSize =
199777fc4c14SDimitry Andric       DL.getTypeStoreSizeInBits(ATy) == DL.getTypeStoreSizeInBits(BTy);
1998b1c73532SDimitry Andric   if (!HasSameSize)
1999b1c73532SDimitry Andric     TypeByteSize = 0;
2000adf62863SDimitry Andric   return DepDistanceStrideAndSizeInfo(Dist, std::abs(StrideAPtrInt),
2001adf62863SDimitry Andric                                       std::abs(StrideBPtrInt), TypeByteSize,
2002ac9a064cSDimitry Andric                                       AIsWrite, BIsWrite);
2003b1c73532SDimitry Andric }
2004e3b55780SDimitry Andric 
2005adf62863SDimitry Andric MemoryDepChecker::Dependence::DepType
isDependent(const MemAccessInfo & A,unsigned AIdx,const MemAccessInfo & B,unsigned BIdx)2006adf62863SDimitry Andric MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
2007adf62863SDimitry Andric                               const MemAccessInfo &B, unsigned BIdx) {
2008b1c73532SDimitry Andric   assert(AIdx < BIdx && "Must pass arguments in program order");
2009b1c73532SDimitry Andric 
2010b1c73532SDimitry Andric   // Get the dependence distance, stride, type size and what access writes for
2011b1c73532SDimitry Andric   // the dependence between A and B.
2012adf62863SDimitry Andric   auto Res =
2013adf62863SDimitry Andric       getDependenceDistanceStrideAndSize(A, InstMap[AIdx], B, InstMap[BIdx]);
2014b1c73532SDimitry Andric   if (std::holds_alternative<Dependence::DepType>(Res))
2015b1c73532SDimitry Andric     return std::get<Dependence::DepType>(Res);
2016b1c73532SDimitry Andric 
2017ac9a064cSDimitry Andric   auto &[Dist, StrideA, StrideB, TypeByteSize, AIsWrite, BIsWrite] =
2018ac9a064cSDimitry Andric       std::get<DepDistanceStrideAndSizeInfo>(Res);
2019b1c73532SDimitry Andric   bool HasSameSize = TypeByteSize > 0;
2020b1c73532SDimitry Andric 
2021ac9a064cSDimitry Andric   std::optional<uint64_t> CommonStride =
2022ac9a064cSDimitry Andric       StrideA == StrideB ? std::make_optional(StrideA) : std::nullopt;
2023ac9a064cSDimitry Andric   if (isa<SCEVCouldNotCompute>(Dist)) {
2024ac9a064cSDimitry Andric     // TODO: Relax requirement that there is a common stride to retry with
2025ac9a064cSDimitry Andric     // non-constant distance dependencies.
2026ac9a064cSDimitry Andric     FoundNonConstantDistanceDependence |= CommonStride.has_value();
2027ac9a064cSDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Dependence because of uncomputable distance.\n");
20285a5ac124SDimitry Andric     return Dependence::Unknown;
20295a5ac124SDimitry Andric   }
20305a5ac124SDimitry Andric 
2031ac9a064cSDimitry Andric   ScalarEvolution &SE = *PSE.getSE();
2032ac9a064cSDimitry Andric   auto &DL = InnermostLoop->getHeader()->getDataLayout();
2033ac9a064cSDimitry Andric   uint64_t MaxStride = std::max(StrideA, StrideB);
2034ac9a064cSDimitry Andric 
2035ac9a064cSDimitry Andric   // If the distance between the acecsses is larger than their maximum absolute
2036ac9a064cSDimitry Andric   // stride multiplied by the symbolic maximum backedge taken count (which is an
2037ac9a064cSDimitry Andric   // upper bound of the number of iterations), the accesses are independet, i.e.
2038ac9a064cSDimitry Andric   // they are far enough appart that accesses won't access the same location
2039ac9a064cSDimitry Andric   // across all loop ierations.
2040ac9a064cSDimitry Andric   if (HasSameSize && isSafeDependenceDistance(
2041ac9a064cSDimitry Andric                          DL, SE, *(PSE.getSymbolicMaxBackedgeTakenCount()),
2042ac9a064cSDimitry Andric                          *Dist, MaxStride, TypeByteSize))
2043ac9a064cSDimitry Andric     return Dependence::NoDep;
2044ac9a064cSDimitry Andric 
2045ac9a064cSDimitry Andric   const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
2046ac9a064cSDimitry Andric 
2047ac9a064cSDimitry Andric   // Attempt to prove strided accesses independent.
2048ac9a064cSDimitry Andric   if (C) {
204901095a5dSDimitry Andric     const APInt &Val = C->getAPInt();
205001095a5dSDimitry Andric     int64_t Distance = Val.getSExtValue();
205101095a5dSDimitry Andric 
2052ac9a064cSDimitry Andric     // If the distance between accesses and their strides are known constants,
2053ac9a064cSDimitry Andric     // check whether the accesses interlace each other.
2054ac9a064cSDimitry Andric     if (std::abs(Distance) > 0 && CommonStride && *CommonStride > 1 &&
2055ac9a064cSDimitry Andric         HasSameSize &&
2056ac9a064cSDimitry Andric         areStridedAccessesIndependent(std::abs(Distance), *CommonStride,
2057ac9a064cSDimitry Andric                                       TypeByteSize)) {
2058eb11fae6SDimitry Andric       LLVM_DEBUG(dbgs() << "LAA: Strided accesses are independent\n");
205901095a5dSDimitry Andric       return Dependence::NoDep;
206001095a5dSDimitry Andric     }
2061ac9a064cSDimitry Andric   } else
2062ac9a064cSDimitry Andric     Dist = SE.applyLoopGuards(Dist, InnermostLoop);
20635a5ac124SDimitry Andric 
20645a5ac124SDimitry Andric   // Negative distances are not plausible dependencies.
2065ac9a064cSDimitry Andric   if (SE.isKnownNonPositive(Dist)) {
2066ac9a064cSDimitry Andric     if (SE.isKnownNonNegative(Dist)) {
2067ac9a064cSDimitry Andric       if (HasSameSize) {
2068ac9a064cSDimitry Andric         // Write to the same location with the same size.
2069ac9a064cSDimitry Andric         return Dependence::Forward;
2070ac9a064cSDimitry Andric       }
2071ac9a064cSDimitry Andric       LLVM_DEBUG(dbgs() << "LAA: possibly zero dependence difference but "
2072ac9a064cSDimitry Andric                            "different type sizes\n");
2073ac9a064cSDimitry Andric       return Dependence::Unknown;
2074ac9a064cSDimitry Andric     }
2075ac9a064cSDimitry Andric 
20765a5ac124SDimitry Andric     bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
2077ac9a064cSDimitry Andric     // Check if the first access writes to a location that is read in a later
2078ac9a064cSDimitry Andric     // iteration, where the distance between them is not a multiple of a vector
2079ac9a064cSDimitry Andric     // factor and relatively small.
2080ac9a064cSDimitry Andric     //
2081ac9a064cSDimitry Andric     // NOTE: There is no need to update MaxSafeVectorWidthInBits after call to
2082ac9a064cSDimitry Andric     // couldPreventStoreLoadForward, even if it changed MinDepDistBytes, since a
2083ac9a064cSDimitry Andric     // forward dependency will allow vectorization using any width.
2084ac9a064cSDimitry Andric 
2085ac9a064cSDimitry Andric     if (IsTrueDataDependence && EnableForwardingConflictDetection) {
2086ac9a064cSDimitry Andric       if (!C) {
2087ac9a064cSDimitry Andric         // TODO: FoundNonConstantDistanceDependence is used as a necessary
2088ac9a064cSDimitry Andric         // condition to consider retrying with runtime checks. Historically, we
2089ac9a064cSDimitry Andric         // did not set it when strides were different but there is no inherent
2090ac9a064cSDimitry Andric         // reason to.
2091ac9a064cSDimitry Andric         FoundNonConstantDistanceDependence |= CommonStride.has_value();
2092ac9a064cSDimitry Andric         return Dependence::Unknown;
2093ac9a064cSDimitry Andric       }
2094ac9a064cSDimitry Andric       if (!HasSameSize ||
2095ac9a064cSDimitry Andric           couldPreventStoreLoadForward(C->getAPInt().abs().getZExtValue(),
2096ac9a064cSDimitry Andric                                        TypeByteSize)) {
2097ac9a064cSDimitry Andric         LLVM_DEBUG(
2098ac9a064cSDimitry Andric             dbgs() << "LAA: Forward but may prevent st->ld forwarding\n");
20995a5ac124SDimitry Andric         return Dependence::ForwardButPreventsForwarding;
210001095a5dSDimitry Andric       }
2101ac9a064cSDimitry Andric     }
21025a5ac124SDimitry Andric 
2103eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Dependence is negative\n");
21045a5ac124SDimitry Andric     return Dependence::Forward;
21055a5ac124SDimitry Andric   }
21065a5ac124SDimitry Andric 
2107ac9a064cSDimitry Andric   int64_t MinDistance = SE.getSignedRangeMin(Dist).getSExtValue();
2108ac9a064cSDimitry Andric   // Below we only handle strictly positive distances.
2109ac9a064cSDimitry Andric   if (MinDistance <= 0) {
2110ac9a064cSDimitry Andric     FoundNonConstantDistanceDependence |= CommonStride.has_value();
21115a5ac124SDimitry Andric     return Dependence::Unknown;
21125a5ac124SDimitry Andric   }
21135a5ac124SDimitry Andric 
2114ac9a064cSDimitry Andric   if (!isa<SCEVConstant>(Dist)) {
2115ac9a064cSDimitry Andric     // Previously this case would be treated as Unknown, possibly setting
2116ac9a064cSDimitry Andric     // FoundNonConstantDistanceDependence to force re-trying with runtime
2117ac9a064cSDimitry Andric     // checks. Until the TODO below is addressed, set it here to preserve
2118ac9a064cSDimitry Andric     // original behavior w.r.t. re-trying with runtime checks.
2119ac9a064cSDimitry Andric     // TODO: FoundNonConstantDistanceDependence is used as a necessary
2120ac9a064cSDimitry Andric     // condition to consider retrying with runtime checks. Historically, we
2121ac9a064cSDimitry Andric     // did not set it when strides were different but there is no inherent
2122ac9a064cSDimitry Andric     // reason to.
2123ac9a064cSDimitry Andric     FoundNonConstantDistanceDependence |= CommonStride.has_value();
2124ac9a064cSDimitry Andric   }
21255a5ac124SDimitry Andric 
212677fc4c14SDimitry Andric   if (!HasSameSize) {
212777fc4c14SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: ReadWrite-Write positive dependency with "
212877fc4c14SDimitry Andric                          "different type sizes\n");
21295a5ac124SDimitry Andric     return Dependence::Unknown;
21305a5ac124SDimitry Andric   }
21315a5ac124SDimitry Andric 
2132ac9a064cSDimitry Andric   if (!CommonStride)
2133ac9a064cSDimitry Andric     return Dependence::Unknown;
2134ac9a064cSDimitry Andric 
21355a5ac124SDimitry Andric   // Bail out early if passed-in parameters make vectorization not feasible.
21365a5ac124SDimitry Andric   unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
21375a5ac124SDimitry Andric                            VectorizerParams::VectorizationFactor : 1);
21385a5ac124SDimitry Andric   unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
21395a5ac124SDimitry Andric                            VectorizerParams::VectorizationInterleave : 1);
214085d8b2bbSDimitry Andric   // The minimum number of iterations for a vectorized/unrolled version.
214185d8b2bbSDimitry Andric   unsigned MinNumIter = std::max(ForcedFactor * ForcedUnroll, 2U);
21425a5ac124SDimitry Andric 
214385d8b2bbSDimitry Andric   // It's not vectorizable if the distance is smaller than the minimum distance
214485d8b2bbSDimitry Andric   // needed for a vectroized/unrolled version. Vectorizing one iteration in
214585d8b2bbSDimitry Andric   // front needs TypeByteSize * Stride. Vectorizing the last iteration needs
214685d8b2bbSDimitry Andric   // TypeByteSize (No need to plus the last gap distance).
214785d8b2bbSDimitry Andric   //
214885d8b2bbSDimitry Andric   // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
214985d8b2bbSDimitry Andric   //      foo(int *A) {
215085d8b2bbSDimitry Andric   //        int *B = (int *)((char *)A + 14);
215185d8b2bbSDimitry Andric   //        for (i = 0 ; i < 1024 ; i += 2)
215285d8b2bbSDimitry Andric   //          B[i] = A[i] + 1;
215385d8b2bbSDimitry Andric   //      }
215485d8b2bbSDimitry Andric   //
215585d8b2bbSDimitry Andric   // Two accesses in memory (stride is 2):
215685d8b2bbSDimitry Andric   //     | A[0] |      | A[2] |      | A[4] |      | A[6] |      |
215785d8b2bbSDimitry Andric   //                              | B[0] |      | B[2] |      | B[4] |
215885d8b2bbSDimitry Andric   //
2159ac9a064cSDimitry Andric   // MinDistance needs for vectorizing iterations except the last iteration:
2160ac9a064cSDimitry Andric   // 4 * 2 * (MinNumIter - 1). MinDistance needs for the last iteration: 4.
216185d8b2bbSDimitry Andric   // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4.
216285d8b2bbSDimitry Andric   //
216385d8b2bbSDimitry Andric   // If MinNumIter is 2, it is vectorizable as the minimum distance needed is
216485d8b2bbSDimitry Andric   // 12, which is less than distance.
216585d8b2bbSDimitry Andric   //
216685d8b2bbSDimitry Andric   // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4),
216785d8b2bbSDimitry Andric   // the minimum distance needed is 28, which is greater than distance. It is
216885d8b2bbSDimitry Andric   // not safe to do vectorization.
2169ac9a064cSDimitry Andric 
2170ac9a064cSDimitry Andric   // We know that Dist is positive, but it may not be constant. Use the signed
2171ac9a064cSDimitry Andric   // minimum for computations below, as this ensures we compute the closest
2172ac9a064cSDimitry Andric   // possible dependence distance.
217301095a5dSDimitry Andric   uint64_t MinDistanceNeeded =
2174ac9a064cSDimitry Andric       TypeByteSize * *CommonStride * (MinNumIter - 1) + TypeByteSize;
2175ac9a064cSDimitry Andric   if (MinDistanceNeeded > static_cast<uint64_t>(MinDistance)) {
2176ac9a064cSDimitry Andric     if (!isa<SCEVConstant>(Dist)) {
2177ac9a064cSDimitry Andric       // For non-constant distances, we checked the lower bound of the
2178ac9a064cSDimitry Andric       // dependence distance and the distance may be larger at runtime (and safe
2179ac9a064cSDimitry Andric       // for vectorization). Classify it as Unknown, so we re-try with runtime
2180ac9a064cSDimitry Andric       // checks.
2181ac9a064cSDimitry Andric       return Dependence::Unknown;
2182ac9a064cSDimitry Andric     }
2183ac9a064cSDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Failure because of positive minimum distance "
2184ac9a064cSDimitry Andric                       << MinDistance << '\n');
218585d8b2bbSDimitry Andric     return Dependence::Backward;
218685d8b2bbSDimitry Andric   }
218785d8b2bbSDimitry Andric 
2188b1c73532SDimitry Andric   // Unsafe if the minimum distance needed is greater than smallest dependence
2189b1c73532SDimitry Andric   // distance distance.
2190b1c73532SDimitry Andric   if (MinDistanceNeeded > MinDepDistBytes) {
2191eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Failure because it needs at least "
2192e3b55780SDimitry Andric                       << MinDistanceNeeded << " size in bytes\n");
21935a5ac124SDimitry Andric     return Dependence::Backward;
21945a5ac124SDimitry Andric   }
21955a5ac124SDimitry Andric 
21965a5ac124SDimitry Andric   // Positive distance bigger than max vectorization factor.
219785d8b2bbSDimitry Andric   // FIXME: Should use max factor instead of max distance in bytes, which could
219885d8b2bbSDimitry Andric   // not handle different types.
219985d8b2bbSDimitry Andric   // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
220085d8b2bbSDimitry Andric   //      void foo (int *A, char *B) {
220185d8b2bbSDimitry Andric   //        for (unsigned i = 0; i < 1024; i++) {
220285d8b2bbSDimitry Andric   //          A[i+2] = A[i] + 1;
220385d8b2bbSDimitry Andric   //          B[i+2] = B[i] + 1;
220485d8b2bbSDimitry Andric   //        }
220585d8b2bbSDimitry Andric   //      }
220685d8b2bbSDimitry Andric   //
220785d8b2bbSDimitry Andric   // This case is currently unsafe according to the max safe distance. If we
220885d8b2bbSDimitry Andric   // analyze the two accesses on array B, the max safe dependence distance
220985d8b2bbSDimitry Andric   // is 2. Then we analyze the accesses on array A, the minimum distance needed
221085d8b2bbSDimitry Andric   // is 8, which is less than 2 and forbidden vectorization, But actually
221185d8b2bbSDimitry Andric   // both A and B could be vectorized by 2 iterations.
2212b1c73532SDimitry Andric   MinDepDistBytes =
2213ac9a064cSDimitry Andric       std::min(static_cast<uint64_t>(MinDistance), MinDepDistBytes);
22145a5ac124SDimitry Andric 
22155a5ac124SDimitry Andric   bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
2216b1c73532SDimitry Andric   uint64_t MinDepDistBytesOld = MinDepDistBytes;
221701095a5dSDimitry Andric   if (IsTrueDataDependence && EnableForwardingConflictDetection &&
2218ac9a064cSDimitry Andric       isa<SCEVConstant>(Dist) &&
2219ac9a064cSDimitry Andric       couldPreventStoreLoadForward(MinDistance, TypeByteSize)) {
2220b1c73532SDimitry Andric     // Sanity check that we didn't update MinDepDistBytes when calling
2221b1c73532SDimitry Andric     // couldPreventStoreLoadForward
2222b1c73532SDimitry Andric     assert(MinDepDistBytes == MinDepDistBytesOld &&
2223b1c73532SDimitry Andric            "An update to MinDepDistBytes requires an update to "
2224b1c73532SDimitry Andric            "MaxSafeVectorWidthInBits");
2225b1c73532SDimitry Andric     (void)MinDepDistBytesOld;
22265a5ac124SDimitry Andric     return Dependence::BackwardVectorizableButPreventsForwarding;
2227b1c73532SDimitry Andric   }
22285a5ac124SDimitry Andric 
2229b1c73532SDimitry Andric   // An update to MinDepDistBytes requires an update to MaxSafeVectorWidthInBits
2230b1c73532SDimitry Andric   // since there is a backwards dependency.
2231ac9a064cSDimitry Andric   uint64_t MaxVF = MinDepDistBytes / (TypeByteSize * *CommonStride);
2232ac9a064cSDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: Positive min distance " << MinDistance
2233044eb2f6SDimitry Andric                     << " with max VF = " << MaxVF << '\n');
2234ac9a064cSDimitry Andric 
2235044eb2f6SDimitry Andric   uint64_t MaxVFInBits = MaxVF * TypeByteSize * 8;
2236ac9a064cSDimitry Andric   if (!isa<SCEVConstant>(Dist) && MaxVFInBits < MaxTargetVectorWidthInBits) {
2237ac9a064cSDimitry Andric     // For non-constant distances, we checked the lower bound of the dependence
2238ac9a064cSDimitry Andric     // distance and the distance may be larger at runtime (and safe for
2239ac9a064cSDimitry Andric     // vectorization). Classify it as Unknown, so we re-try with runtime checks.
2240ac9a064cSDimitry Andric     return Dependence::Unknown;
2241ac9a064cSDimitry Andric   }
2242ac9a064cSDimitry Andric 
2243b60736ecSDimitry Andric   MaxSafeVectorWidthInBits = std::min(MaxSafeVectorWidthInBits, MaxVFInBits);
22445a5ac124SDimitry Andric   return Dependence::BackwardVectorizable;
22455a5ac124SDimitry Andric }
22465a5ac124SDimitry Andric 
areDepsSafe(const DepCandidates & AccessSets,const MemAccessInfoList & CheckDeps)2247adf62863SDimitry Andric bool MemoryDepChecker::areDepsSafe(const DepCandidates &AccessSets,
2248adf62863SDimitry Andric                                    const MemAccessInfoList &CheckDeps) {
22495a5ac124SDimitry Andric 
2250b1c73532SDimitry Andric   MinDepDistBytes = -1;
225171d5a254SDimitry Andric   SmallPtrSet<MemAccessInfo, 8> Visited;
225271d5a254SDimitry Andric   for (MemAccessInfo CurAccess : CheckDeps) {
225371d5a254SDimitry Andric     if (Visited.count(CurAccess))
225471d5a254SDimitry Andric       continue;
22555a5ac124SDimitry Andric 
22565a5ac124SDimitry Andric     // Get the relevant memory access set.
22575a5ac124SDimitry Andric     EquivalenceClasses<MemAccessInfo>::iterator I =
22585a5ac124SDimitry Andric       AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
22595a5ac124SDimitry Andric 
22605a5ac124SDimitry Andric     // Check accesses within this set.
226101095a5dSDimitry Andric     EquivalenceClasses<MemAccessInfo>::member_iterator AI =
226201095a5dSDimitry Andric         AccessSets.member_begin(I);
226301095a5dSDimitry Andric     EquivalenceClasses<MemAccessInfo>::member_iterator AE =
226401095a5dSDimitry Andric         AccessSets.member_end();
22655a5ac124SDimitry Andric 
22665a5ac124SDimitry Andric     // Check every access pair.
22675a5ac124SDimitry Andric     while (AI != AE) {
226871d5a254SDimitry Andric       Visited.insert(*AI);
22691d5ae102SDimitry Andric       bool AIIsWrite = AI->getInt();
22701d5ae102SDimitry Andric       // Check loads only against next equivalent class, but stores also against
22711d5ae102SDimitry Andric       // other stores in the same equivalence class - to the same address.
22721d5ae102SDimitry Andric       EquivalenceClasses<MemAccessInfo>::member_iterator OI =
22731d5ae102SDimitry Andric           (AIIsWrite ? AI : std::next(AI));
22745a5ac124SDimitry Andric       while (OI != AE) {
22755a5ac124SDimitry Andric         // Check every accessing instruction pair in program order.
22765a5ac124SDimitry Andric         for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
22775a5ac124SDimitry Andric              I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
22781d5ae102SDimitry Andric           // Scan all accesses of another equivalence class, but only the next
22791d5ae102SDimitry Andric           // accesses of the same equivalent class.
22801d5ae102SDimitry Andric           for (std::vector<unsigned>::iterator
22811d5ae102SDimitry Andric                    I2 = (OI == AI ? std::next(I1) : Accesses[*OI].begin()),
22821d5ae102SDimitry Andric                    I2E = (OI == AI ? I1E : Accesses[*OI].end());
22831d5ae102SDimitry Andric                I2 != I2E; ++I2) {
22845a5ac124SDimitry Andric             auto A = std::make_pair(&*AI, *I1);
22855a5ac124SDimitry Andric             auto B = std::make_pair(&*OI, *I2);
22865a5ac124SDimitry Andric 
22875a5ac124SDimitry Andric             assert(*I1 != *I2);
22885a5ac124SDimitry Andric             if (*I1 > *I2)
22895a5ac124SDimitry Andric               std::swap(A, B);
22905a5ac124SDimitry Andric 
2291adf62863SDimitry Andric             Dependence::DepType Type =
2292adf62863SDimitry Andric                 isDependent(*A.first, A.second, *B.first, B.second);
2293d8e91e46SDimitry Andric             mergeInStatus(Dependence::isSafeForVectorization(Type));
22945a5ac124SDimitry Andric 
2295dd58ef01SDimitry Andric             // Gather dependences unless we accumulated MaxDependences
22965a5ac124SDimitry Andric             // dependences.  In that case return as soon as we find the first
22975a5ac124SDimitry Andric             // unsafe dependence.  This puts a limit on this quadratic
22985a5ac124SDimitry Andric             // algorithm.
2299dd58ef01SDimitry Andric             if (RecordDependences) {
2300dd58ef01SDimitry Andric               if (Type != Dependence::NoDep)
2301dd58ef01SDimitry Andric                 Dependences.push_back(Dependence(A.second, B.second, Type));
23025a5ac124SDimitry Andric 
2303dd58ef01SDimitry Andric               if (Dependences.size() >= MaxDependences) {
2304dd58ef01SDimitry Andric                 RecordDependences = false;
2305dd58ef01SDimitry Andric                 Dependences.clear();
2306eb11fae6SDimitry Andric                 LLVM_DEBUG(dbgs()
2307eb11fae6SDimitry Andric                            << "Too many dependences, stopped recording\n");
23085a5ac124SDimitry Andric               }
23095a5ac124SDimitry Andric             }
2310d8e91e46SDimitry Andric             if (!RecordDependences && !isSafeForVectorization())
23115a5ac124SDimitry Andric               return false;
23125a5ac124SDimitry Andric           }
23135a5ac124SDimitry Andric         ++OI;
23145a5ac124SDimitry Andric       }
2315ac9a064cSDimitry Andric       ++AI;
23165a5ac124SDimitry Andric     }
23175a5ac124SDimitry Andric   }
23185a5ac124SDimitry Andric 
2319eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << "Total Dependences: " << Dependences.size() << "\n");
2320d8e91e46SDimitry Andric   return isSafeForVectorization();
23215a5ac124SDimitry Andric }
23225a5ac124SDimitry Andric 
23235a5ac124SDimitry Andric SmallVector<Instruction *, 4>
getInstructionsForAccess(Value * Ptr,bool IsWrite) const2324ac9a064cSDimitry Andric MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool IsWrite) const {
2325ac9a064cSDimitry Andric   MemAccessInfo Access(Ptr, IsWrite);
23265a5ac124SDimitry Andric   auto &IndexVector = Accesses.find(Access)->second;
23275a5ac124SDimitry Andric 
23285a5ac124SDimitry Andric   SmallVector<Instruction *, 4> Insts;
2329b915e9e0SDimitry Andric   transform(IndexVector,
23305a5ac124SDimitry Andric                  std::back_inserter(Insts),
23315a5ac124SDimitry Andric                  [&](unsigned Idx) { return this->InstMap[Idx]; });
23325a5ac124SDimitry Andric   return Insts;
23335a5ac124SDimitry Andric }
23345a5ac124SDimitry Andric 
23355a5ac124SDimitry Andric const char *MemoryDepChecker::Dependence::DepName[] = {
2336b1c73532SDimitry Andric     "NoDep",
2337b1c73532SDimitry Andric     "Unknown",
2338ac9a064cSDimitry Andric     "IndirectUnsafe",
2339b1c73532SDimitry Andric     "Forward",
2340b1c73532SDimitry Andric     "ForwardButPreventsForwarding",
2341b1c73532SDimitry Andric     "Backward",
2342b1c73532SDimitry Andric     "BackwardVectorizable",
2343b1c73532SDimitry Andric     "BackwardVectorizableButPreventsForwarding"};
23445a5ac124SDimitry Andric 
print(raw_ostream & OS,unsigned Depth,const SmallVectorImpl<Instruction * > & Instrs) const23455a5ac124SDimitry Andric void MemoryDepChecker::Dependence::print(
23465a5ac124SDimitry Andric     raw_ostream &OS, unsigned Depth,
23475a5ac124SDimitry Andric     const SmallVectorImpl<Instruction *> &Instrs) const {
23485a5ac124SDimitry Andric   OS.indent(Depth) << DepName[Type] << ":\n";
23495a5ac124SDimitry Andric   OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
23505a5ac124SDimitry Andric   OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
23515a5ac124SDimitry Andric }
23525a5ac124SDimitry Andric 
canAnalyzeLoop()23535a5ac124SDimitry Andric bool LoopAccessInfo::canAnalyzeLoop() {
23545a5ac124SDimitry Andric   // We need to have a loop header.
2355ac9a064cSDimitry Andric   LLVM_DEBUG(dbgs() << "\nLAA: Checking a loop in '"
2356ac9a064cSDimitry Andric                     << TheLoop->getHeader()->getParent()->getName() << "' from "
2357ac9a064cSDimitry Andric                     << TheLoop->getLocStr() << "\n");
23585a5ac124SDimitry Andric 
23595a5ac124SDimitry Andric   // We can only analyze innermost loops.
2360b60736ecSDimitry Andric   if (!TheLoop->isInnermost()) {
2361eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
2362b915e9e0SDimitry Andric     recordAnalysis("NotInnerMostLoop") << "loop is not the innermost loop";
23635a5ac124SDimitry Andric     return false;
23645a5ac124SDimitry Andric   }
23655a5ac124SDimitry Andric 
23665a5ac124SDimitry Andric   // We must have a single backedge.
23675a5ac124SDimitry Andric   if (TheLoop->getNumBackEdges() != 1) {
2368eb11fae6SDimitry Andric     LLVM_DEBUG(
2369eb11fae6SDimitry Andric         dbgs() << "LAA: loop control flow is not understood by analyzer\n");
2370b915e9e0SDimitry Andric     recordAnalysis("CFGNotUnderstood")
2371b915e9e0SDimitry Andric         << "loop control flow is not understood by analyzer";
23725a5ac124SDimitry Andric     return false;
23735a5ac124SDimitry Andric   }
23745a5ac124SDimitry Andric 
2375ac9a064cSDimitry Andric   // ScalarEvolution needs to be able to find the symbolic max backedge taken
2376ac9a064cSDimitry Andric   // count, which is an upper bound on the number of loop iterations. The loop
2377ac9a064cSDimitry Andric   // may execute fewer iterations, if it exits via an uncountable exit.
2378ac9a064cSDimitry Andric   const SCEV *ExitCount = PSE->getSymbolicMaxBackedgeTakenCount();
2379b60736ecSDimitry Andric   if (isa<SCEVCouldNotCompute>(ExitCount)) {
2380b915e9e0SDimitry Andric     recordAnalysis("CantComputeNumberOfIterations")
2381b915e9e0SDimitry Andric         << "could not determine number of loop iterations";
2382eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
23835a5ac124SDimitry Andric     return false;
23845a5ac124SDimitry Andric   }
23855a5ac124SDimitry Andric 
2386ac9a064cSDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: Found an analyzable loop: "
2387ac9a064cSDimitry Andric                     << TheLoop->getHeader()->getName() << "\n");
23885a5ac124SDimitry Andric   return true;
23895a5ac124SDimitry Andric }
23905a5ac124SDimitry Andric 
analyzeLoop(AAResults * AA,LoopInfo * LI,const TargetLibraryInfo * TLI,DominatorTree * DT)2391ac9a064cSDimitry Andric bool LoopAccessInfo::analyzeLoop(AAResults *AA, LoopInfo *LI,
239201095a5dSDimitry Andric                                  const TargetLibraryInfo *TLI,
239301095a5dSDimitry Andric                                  DominatorTree *DT) {
239401095a5dSDimitry Andric   // Holds the Load and Store instructions.
239501095a5dSDimitry Andric   SmallVector<LoadInst *, 16> Loads;
239601095a5dSDimitry Andric   SmallVector<StoreInst *, 16> Stores;
2397ac9a064cSDimitry Andric   SmallPtrSet<MDNode *, 8> LoopAliasScopes;
23985a5ac124SDimitry Andric 
23995a5ac124SDimitry Andric   // Holds all the different accesses in the loop.
24005a5ac124SDimitry Andric   unsigned NumReads = 0;
24015a5ac124SDimitry Andric   unsigned NumReadWrites = 0;
24025a5ac124SDimitry Andric 
2403e6d15924SDimitry Andric   bool HasComplexMemInst = false;
2404e6d15924SDimitry Andric 
2405e6d15924SDimitry Andric   // A runtime check is only legal to insert if there are no convergent calls.
2406e6d15924SDimitry Andric   HasConvergentOp = false;
2407e6d15924SDimitry Andric 
240801095a5dSDimitry Andric   PtrRtChecking->Pointers.clear();
240901095a5dSDimitry Andric   PtrRtChecking->Need = false;
24105a5ac124SDimitry Andric 
24115a5ac124SDimitry Andric   const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
24125a5ac124SDimitry Andric 
2413cfca06d7SDimitry Andric   const bool EnableMemAccessVersioningOfLoop =
2414cfca06d7SDimitry Andric       EnableMemAccessVersioning &&
2415cfca06d7SDimitry Andric       !TheLoop->getHeader()->getParent()->hasOptSize();
2416cfca06d7SDimitry Andric 
2417e3b55780SDimitry Andric   // Traverse blocks in fixed RPOT order, regardless of their storage in the
2418e3b55780SDimitry Andric   // loop info, as it may be arbitrary.
2419e3b55780SDimitry Andric   LoopBlocksRPO RPOT(TheLoop);
2420e3b55780SDimitry Andric   RPOT.perform(LI);
2421e3b55780SDimitry Andric   for (BasicBlock *BB : RPOT) {
2422e6d15924SDimitry Andric     // Scan the BB and collect legal loads and stores. Also detect any
2423e6d15924SDimitry Andric     // convergent instructions.
242401095a5dSDimitry Andric     for (Instruction &I : *BB) {
2425e6d15924SDimitry Andric       if (auto *Call = dyn_cast<CallBase>(&I)) {
2426e6d15924SDimitry Andric         if (Call->isConvergent())
2427e6d15924SDimitry Andric           HasConvergentOp = true;
2428e6d15924SDimitry Andric       }
2429e6d15924SDimitry Andric 
2430e6d15924SDimitry Andric       // With both a non-vectorizable memory instruction and a convergent
2431e6d15924SDimitry Andric       // operation, found in this loop, no reason to continue the search.
2432ac9a064cSDimitry Andric       if (HasComplexMemInst && HasConvergentOp)
2433ac9a064cSDimitry Andric         return false;
2434e6d15924SDimitry Andric 
2435e6d15924SDimitry Andric       // Avoid hitting recordAnalysis multiple times.
2436e6d15924SDimitry Andric       if (HasComplexMemInst)
2437e6d15924SDimitry Andric         continue;
2438e6d15924SDimitry Andric 
2439ac9a064cSDimitry Andric       // Record alias scopes defined inside the loop.
2440ac9a064cSDimitry Andric       if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
2441ac9a064cSDimitry Andric         for (Metadata *Op : Decl->getScopeList()->operands())
2442ac9a064cSDimitry Andric           LoopAliasScopes.insert(cast<MDNode>(Op));
2443ac9a064cSDimitry Andric 
24445a5ac124SDimitry Andric       // Many math library functions read the rounding mode. We will only
24455a5ac124SDimitry Andric       // vectorize a loop if it contains known function calls that don't set
24465a5ac124SDimitry Andric       // the flag. Therefore, it is safe to ignore this read from memory.
244701095a5dSDimitry Andric       auto *Call = dyn_cast<CallInst>(&I);
244801095a5dSDimitry Andric       if (Call && getVectorIntrinsicIDForCall(Call, TLI))
24495a5ac124SDimitry Andric         continue;
24505a5ac124SDimitry Andric 
2451b1c73532SDimitry Andric       // If this is a load, save it. If this instruction can read from memory
2452b1c73532SDimitry Andric       // but is not a load, then we quit. Notice that we don't handle function
2453b1c73532SDimitry Andric       // calls that read or write.
2454b1c73532SDimitry Andric       if (I.mayReadFromMemory()) {
24555a5ac124SDimitry Andric         // If the function has an explicit vectorized counterpart, we can safely
24565a5ac124SDimitry Andric         // assume that it can be vectorized.
24575a5ac124SDimitry Andric         if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
2458cfca06d7SDimitry Andric             !VFDatabase::getMappings(*Call).empty())
24595a5ac124SDimitry Andric           continue;
24605a5ac124SDimitry Andric 
246101095a5dSDimitry Andric         auto *Ld = dyn_cast<LoadInst>(&I);
2462e6d15924SDimitry Andric         if (!Ld) {
2463e6d15924SDimitry Andric           recordAnalysis("CantVectorizeInstruction", Ld)
2464e6d15924SDimitry Andric             << "instruction cannot be vectorized";
2465e6d15924SDimitry Andric           HasComplexMemInst = true;
2466e6d15924SDimitry Andric           continue;
2467e6d15924SDimitry Andric         }
2468e6d15924SDimitry Andric         if (!Ld->isSimple() && !IsAnnotatedParallel) {
2469b915e9e0SDimitry Andric           recordAnalysis("NonSimpleLoad", Ld)
2470b915e9e0SDimitry Andric               << "read with atomic ordering or volatile read";
2471eb11fae6SDimitry Andric           LLVM_DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
2472e6d15924SDimitry Andric           HasComplexMemInst = true;
2473e6d15924SDimitry Andric           continue;
24745a5ac124SDimitry Andric         }
24755a5ac124SDimitry Andric         NumLoads++;
24765a5ac124SDimitry Andric         Loads.push_back(Ld);
247701095a5dSDimitry Andric         DepChecker->addAccess(Ld);
2478cfca06d7SDimitry Andric         if (EnableMemAccessVersioningOfLoop)
247901095a5dSDimitry Andric           collectStridedAccess(Ld);
24805a5ac124SDimitry Andric         continue;
24815a5ac124SDimitry Andric       }
24825a5ac124SDimitry Andric 
24835a5ac124SDimitry Andric       // Save 'store' instructions. Abort if other instructions write to memory.
248401095a5dSDimitry Andric       if (I.mayWriteToMemory()) {
248501095a5dSDimitry Andric         auto *St = dyn_cast<StoreInst>(&I);
24865a5ac124SDimitry Andric         if (!St) {
2487b915e9e0SDimitry Andric           recordAnalysis("CantVectorizeInstruction", St)
2488b915e9e0SDimitry Andric               << "instruction cannot be vectorized";
2489e6d15924SDimitry Andric           HasComplexMemInst = true;
2490e6d15924SDimitry Andric           continue;
24915a5ac124SDimitry Andric         }
24925a5ac124SDimitry Andric         if (!St->isSimple() && !IsAnnotatedParallel) {
2493b915e9e0SDimitry Andric           recordAnalysis("NonSimpleStore", St)
2494b915e9e0SDimitry Andric               << "write with atomic ordering or volatile write";
2495eb11fae6SDimitry Andric           LLVM_DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
2496e6d15924SDimitry Andric           HasComplexMemInst = true;
2497e6d15924SDimitry Andric           continue;
24985a5ac124SDimitry Andric         }
24995a5ac124SDimitry Andric         NumStores++;
25005a5ac124SDimitry Andric         Stores.push_back(St);
250101095a5dSDimitry Andric         DepChecker->addAccess(St);
2502cfca06d7SDimitry Andric         if (EnableMemAccessVersioningOfLoop)
250301095a5dSDimitry Andric           collectStridedAccess(St);
25045a5ac124SDimitry Andric       }
25055a5ac124SDimitry Andric     } // Next instr.
25065a5ac124SDimitry Andric   } // Next block.
25075a5ac124SDimitry Andric 
2508ac9a064cSDimitry Andric   if (HasComplexMemInst)
2509ac9a064cSDimitry Andric     return false;
2510e6d15924SDimitry Andric 
25115a5ac124SDimitry Andric   // Now we have two lists that hold the loads and the stores.
25125a5ac124SDimitry Andric   // Next, we find the pointers that they use.
25135a5ac124SDimitry Andric 
25145a5ac124SDimitry Andric   // Check if we see any stores. If there are no stores, then we don't
25155a5ac124SDimitry Andric   // care if the pointers are *restrict*.
25165a5ac124SDimitry Andric   if (!Stores.size()) {
2517eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
2518ac9a064cSDimitry Andric     return true;
25195a5ac124SDimitry Andric   }
25205a5ac124SDimitry Andric 
25215a5ac124SDimitry Andric   MemoryDepChecker::DepCandidates DependentAccesses;
2522ac9a064cSDimitry Andric   AccessAnalysis Accesses(TheLoop, AA, LI, DependentAccesses, *PSE,
2523ac9a064cSDimitry Andric                           LoopAliasScopes);
25245a5ac124SDimitry Andric 
2525b60736ecSDimitry Andric   // Holds the analyzed pointers. We don't want to call getUnderlyingObjects
25265a5ac124SDimitry Andric   // multiple times on the same object. If the ptr is accessed twice, once
25275a5ac124SDimitry Andric   // for read and once for write, it will only appear once (on the write
25285a5ac124SDimitry Andric   // list). This is okay, since we are going to check for conflicts between
25295a5ac124SDimitry Andric   // writes and between reads and writes, but not between reads and reads.
2530145449b1SDimitry Andric   SmallSet<std::pair<Value *, Type *>, 16> Seen;
25315a5ac124SDimitry Andric 
2532d8e91e46SDimitry Andric   // Record uniform store addresses to identify if we have multiple stores
2533d8e91e46SDimitry Andric   // to the same address.
2534145449b1SDimitry Andric   SmallPtrSet<Value *, 16> UniformStores;
2535d8e91e46SDimitry Andric 
253601095a5dSDimitry Andric   for (StoreInst *ST : Stores) {
25375a5ac124SDimitry Andric     Value *Ptr = ST->getPointerOperand();
2538d8e91e46SDimitry Andric 
25397fa27ce4SDimitry Andric     if (isInvariant(Ptr)) {
2540145449b1SDimitry Andric       // Record store instructions to loop invariant addresses
2541145449b1SDimitry Andric       StoresToInvariantAddresses.push_back(ST);
2542ac9a064cSDimitry Andric       HasStoreStoreDependenceInvolvingLoopInvariantAddress |=
2543d8e91e46SDimitry Andric           !UniformStores.insert(Ptr).second;
2544145449b1SDimitry Andric     }
2545d8e91e46SDimitry Andric 
25465a5ac124SDimitry Andric     // If we did *not* see this pointer before, insert it to  the read-write
25475a5ac124SDimitry Andric     // list. At this phase it is only a 'write' list.
2548145449b1SDimitry Andric     Type *AccessTy = getLoadStoreType(ST);
2549145449b1SDimitry Andric     if (Seen.insert({Ptr, AccessTy}).second) {
25505a5ac124SDimitry Andric       ++NumReadWrites;
25515a5ac124SDimitry Andric 
25523a0822f0SDimitry Andric       MemoryLocation Loc = MemoryLocation::get(ST);
25535a5ac124SDimitry Andric       // The TBAA metadata could have a control dependency on the predication
25545a5ac124SDimitry Andric       // condition, so we cannot rely on it when determining whether or not we
25555a5ac124SDimitry Andric       // need runtime pointer checks.
25565a5ac124SDimitry Andric       if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
25575a5ac124SDimitry Andric         Loc.AATags.TBAA = nullptr;
25585a5ac124SDimitry Andric 
2559c0981da4SDimitry Andric       visitPointers(const_cast<Value *>(Loc.Ptr), *TheLoop,
2560145449b1SDimitry Andric                     [&Accesses, AccessTy, Loc](Value *Ptr) {
2561c0981da4SDimitry Andric                       MemoryLocation NewLoc = Loc.getWithNewPtr(Ptr);
2562145449b1SDimitry Andric                       Accesses.addStore(NewLoc, AccessTy);
2563c0981da4SDimitry Andric                     });
25645a5ac124SDimitry Andric     }
25655a5ac124SDimitry Andric   }
25665a5ac124SDimitry Andric 
25675a5ac124SDimitry Andric   if (IsAnnotatedParallel) {
2568eb11fae6SDimitry Andric     LLVM_DEBUG(
2569eb11fae6SDimitry Andric         dbgs() << "LAA: A loop annotated parallel, ignore memory dependency "
25705a5ac124SDimitry Andric                << "checks.\n");
2571ac9a064cSDimitry Andric     return true;
25725a5ac124SDimitry Andric   }
25735a5ac124SDimitry Andric 
257401095a5dSDimitry Andric   for (LoadInst *LD : Loads) {
25755a5ac124SDimitry Andric     Value *Ptr = LD->getPointerOperand();
25765a5ac124SDimitry Andric     // If we did *not* see this pointer before, insert it to the
25775a5ac124SDimitry Andric     // read list. If we *did* see it before, then it is already in
25785a5ac124SDimitry Andric     // the read-write list. This allows us to vectorize expressions
25795a5ac124SDimitry Andric     // such as A[i] += x;  Because the address of A[i] is a read-write
25805a5ac124SDimitry Andric     // pointer. This only works if the index of A[i] is consecutive.
25815a5ac124SDimitry Andric     // If the address of i is unknown (for example A[B[i]]) then we may
25825a5ac124SDimitry Andric     // read a few words, modify, and write a few words, and some of the
25835a5ac124SDimitry Andric     // words may be written to the same address.
25845a5ac124SDimitry Andric     bool IsReadOnlyPtr = false;
2585145449b1SDimitry Andric     Type *AccessTy = getLoadStoreType(LD);
2586145449b1SDimitry Andric     if (Seen.insert({Ptr, AccessTy}).second ||
2587e3b55780SDimitry Andric         !getPtrStride(*PSE, LD->getType(), Ptr, TheLoop, SymbolicStrides).value_or(0)) {
25885a5ac124SDimitry Andric       ++NumReads;
25895a5ac124SDimitry Andric       IsReadOnlyPtr = true;
25905a5ac124SDimitry Andric     }
25915a5ac124SDimitry Andric 
2592d8e91e46SDimitry Andric     // See if there is an unsafe dependency between a load to a uniform address and
2593d8e91e46SDimitry Andric     // store to the same uniform address.
2594d8e91e46SDimitry Andric     if (UniformStores.count(Ptr)) {
2595d8e91e46SDimitry Andric       LLVM_DEBUG(dbgs() << "LAA: Found an unsafe dependency between a uniform "
2596d8e91e46SDimitry Andric                            "load and uniform store to the same address!\n");
2597ac9a064cSDimitry Andric       HasLoadStoreDependenceInvolvingLoopInvariantAddress = true;
2598d8e91e46SDimitry Andric     }
2599d8e91e46SDimitry Andric 
26003a0822f0SDimitry Andric     MemoryLocation Loc = MemoryLocation::get(LD);
26015a5ac124SDimitry Andric     // The TBAA metadata could have a control dependency on the predication
26025a5ac124SDimitry Andric     // condition, so we cannot rely on it when determining whether or not we
26035a5ac124SDimitry Andric     // need runtime pointer checks.
26045a5ac124SDimitry Andric     if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
26055a5ac124SDimitry Andric       Loc.AATags.TBAA = nullptr;
26065a5ac124SDimitry Andric 
2607c0981da4SDimitry Andric     visitPointers(const_cast<Value *>(Loc.Ptr), *TheLoop,
2608145449b1SDimitry Andric                   [&Accesses, AccessTy, Loc, IsReadOnlyPtr](Value *Ptr) {
2609c0981da4SDimitry Andric                     MemoryLocation NewLoc = Loc.getWithNewPtr(Ptr);
2610145449b1SDimitry Andric                     Accesses.addLoad(NewLoc, AccessTy, IsReadOnlyPtr);
2611c0981da4SDimitry Andric                   });
26125a5ac124SDimitry Andric   }
26135a5ac124SDimitry Andric 
26145a5ac124SDimitry Andric   // If we write (or read-write) to a single destination and there are no
26155a5ac124SDimitry Andric   // other reads in this loop then is it safe to vectorize.
26165a5ac124SDimitry Andric   if (NumReadWrites == 1 && NumReads == 0) {
2617eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
2618ac9a064cSDimitry Andric     return true;
26195a5ac124SDimitry Andric   }
26205a5ac124SDimitry Andric 
26215a5ac124SDimitry Andric   // Build dependence sets and check whether we need a runtime pointer bounds
26225a5ac124SDimitry Andric   // check.
26235a5ac124SDimitry Andric   Accesses.buildDependenceSets();
26245a5ac124SDimitry Andric 
26255a5ac124SDimitry Andric   // Find pointers with computable bounds. We are going to use this information
26265a5ac124SDimitry Andric   // to place a runtime bound check.
2627145449b1SDimitry Andric   Value *UncomputablePtr = nullptr;
2628145449b1SDimitry Andric   bool CanDoRTIfNeeded =
2629145449b1SDimitry Andric       Accesses.canCheckPtrAtRT(*PtrRtChecking, PSE->getSE(), TheLoop,
2630145449b1SDimitry Andric                                SymbolicStrides, UncomputablePtr, false);
2631ee8648bdSDimitry Andric   if (!CanDoRTIfNeeded) {
2632145449b1SDimitry Andric     auto *I = dyn_cast_or_null<Instruction>(UncomputablePtr);
2633145449b1SDimitry Andric     recordAnalysis("CantIdentifyArrayBounds", I)
2634145449b1SDimitry Andric         << "cannot identify array bounds";
2635eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: We can't vectorize because we can't find "
2636ee8648bdSDimitry Andric                       << "the array bounds.\n");
2637ac9a064cSDimitry Andric     return false;
26385a5ac124SDimitry Andric   }
26395a5ac124SDimitry Andric 
2640eb11fae6SDimitry Andric   LLVM_DEBUG(
2641e6d15924SDimitry Andric     dbgs() << "LAA: May be able to perform a memory runtime check if needed.\n");
26425a5ac124SDimitry Andric 
2643ac9a064cSDimitry Andric   bool DepsAreSafe = true;
26445a5ac124SDimitry Andric   if (Accesses.isDependencyCheckNeeded()) {
2645eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
2646ac9a064cSDimitry Andric     DepsAreSafe = DepChecker->areDepsSafe(DependentAccesses,
2647adf62863SDimitry Andric                                           Accesses.getDependenciesToCheck());
26485a5ac124SDimitry Andric 
2649ac9a064cSDimitry Andric     if (!DepsAreSafe && DepChecker->shouldRetryWithRuntimeCheck()) {
2650eb11fae6SDimitry Andric       LLVM_DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
26515a5ac124SDimitry Andric 
26525a5ac124SDimitry Andric       // Clear the dependency checks. We assume they are not needed.
265301095a5dSDimitry Andric       Accesses.resetDepChecks(*DepChecker);
26545a5ac124SDimitry Andric 
265501095a5dSDimitry Andric       PtrRtChecking->reset();
265601095a5dSDimitry Andric       PtrRtChecking->Need = true;
26575a5ac124SDimitry Andric 
265801095a5dSDimitry Andric       auto *SE = PSE->getSE();
2659145449b1SDimitry Andric       UncomputablePtr = nullptr;
2660145449b1SDimitry Andric       CanDoRTIfNeeded = Accesses.canCheckPtrAtRT(
2661145449b1SDimitry Andric           *PtrRtChecking, SE, TheLoop, SymbolicStrides, UncomputablePtr, true);
266285d8b2bbSDimitry Andric 
26635a5ac124SDimitry Andric       // Check that we found the bounds for the pointer.
2664ee8648bdSDimitry Andric       if (!CanDoRTIfNeeded) {
2665145449b1SDimitry Andric         auto *I = dyn_cast_or_null<Instruction>(UncomputablePtr);
2666145449b1SDimitry Andric         recordAnalysis("CantCheckMemDepsAtRunTime", I)
2667b915e9e0SDimitry Andric             << "cannot check memory dependencies at runtime";
2668eb11fae6SDimitry Andric         LLVM_DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
2669ac9a064cSDimitry Andric         return false;
26705a5ac124SDimitry Andric       }
2671ac9a064cSDimitry Andric       DepsAreSafe = true;
26725a5ac124SDimitry Andric     }
26735a5ac124SDimitry Andric   }
26745a5ac124SDimitry Andric 
2675e6d15924SDimitry Andric   if (HasConvergentOp) {
2676e6d15924SDimitry Andric     recordAnalysis("CantInsertRuntimeCheckWithConvergent")
2677e6d15924SDimitry Andric         << "cannot add control dependency to convergent operation";
2678e6d15924SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: We can't vectorize because a runtime check "
2679e6d15924SDimitry Andric                          "would be needed with a convergent operation\n");
2680ac9a064cSDimitry Andric     return false;
2681e6d15924SDimitry Andric   }
2682e6d15924SDimitry Andric 
2683ac9a064cSDimitry Andric   if (DepsAreSafe) {
2684eb11fae6SDimitry Andric     LLVM_DEBUG(
2685eb11fae6SDimitry Andric         dbgs() << "LAA: No unsafe dependent memory operations in loop.  We"
268601095a5dSDimitry Andric                << (PtrRtChecking->Need ? "" : " don't")
2687ee8648bdSDimitry Andric                << " need runtime memory checks.\n");
2688ac9a064cSDimitry Andric     return true;
2689ac9a064cSDimitry Andric   }
2690ac9a064cSDimitry Andric 
2691145449b1SDimitry Andric   emitUnsafeDependenceRemark();
2692ac9a064cSDimitry Andric   return false;
2693145449b1SDimitry Andric }
2694145449b1SDimitry Andric 
emitUnsafeDependenceRemark()2695145449b1SDimitry Andric void LoopAccessInfo::emitUnsafeDependenceRemark() {
2696ac9a064cSDimitry Andric   const auto *Deps = getDepChecker().getDependences();
2697145449b1SDimitry Andric   if (!Deps)
2698145449b1SDimitry Andric     return;
2699ac9a064cSDimitry Andric   const auto *Found =
2700ac9a064cSDimitry Andric       llvm::find_if(*Deps, [](const MemoryDepChecker::Dependence &D) {
2701145449b1SDimitry Andric         return MemoryDepChecker::Dependence::isSafeForVectorization(D.Type) !=
2702145449b1SDimitry Andric                MemoryDepChecker::VectorizationSafetyStatus::Safe;
2703145449b1SDimitry Andric       });
2704145449b1SDimitry Andric   if (Found == Deps->end())
2705145449b1SDimitry Andric     return;
2706145449b1SDimitry Andric   MemoryDepChecker::Dependence Dep = *Found;
2707145449b1SDimitry Andric 
2708145449b1SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
2709145449b1SDimitry Andric 
2710145449b1SDimitry Andric   // Emit remark for first unsafe dependence
2711b1c73532SDimitry Andric   bool HasForcedDistribution = false;
2712b1c73532SDimitry Andric   std::optional<const MDOperand *> Value =
2713b1c73532SDimitry Andric       findStringMetadataForLoop(TheLoop, "llvm.loop.distribute.enable");
2714b1c73532SDimitry Andric   if (Value) {
2715b1c73532SDimitry Andric     const MDOperand *Op = *Value;
2716b1c73532SDimitry Andric     assert(Op && mdconst::hasa<ConstantInt>(*Op) && "invalid metadata");
2717b1c73532SDimitry Andric     HasForcedDistribution = mdconst::extract<ConstantInt>(*Op)->getZExtValue();
2718b1c73532SDimitry Andric   }
2719b1c73532SDimitry Andric 
2720b1c73532SDimitry Andric   const std::string Info =
2721b1c73532SDimitry Andric       HasForcedDistribution
2722b1c73532SDimitry Andric           ? "unsafe dependent memory operations in loop."
2723b1c73532SDimitry Andric           : "unsafe dependent memory operations in loop. Use "
2724b1c73532SDimitry Andric             "#pragma clang loop distribute(enable) to allow loop distribution "
272501095a5dSDimitry Andric             "to attempt to isolate the offending operations into a separate "
2726b915e9e0SDimitry Andric             "loop";
2727b1c73532SDimitry Andric   OptimizationRemarkAnalysis &R =
2728ac9a064cSDimitry Andric       recordAnalysis("UnsafeDep", Dep.getDestination(getDepChecker())) << Info;
2729145449b1SDimitry Andric 
2730145449b1SDimitry Andric   switch (Dep.Type) {
2731145449b1SDimitry Andric   case MemoryDepChecker::Dependence::NoDep:
2732145449b1SDimitry Andric   case MemoryDepChecker::Dependence::Forward:
2733145449b1SDimitry Andric   case MemoryDepChecker::Dependence::BackwardVectorizable:
2734145449b1SDimitry Andric     llvm_unreachable("Unexpected dependence");
2735145449b1SDimitry Andric   case MemoryDepChecker::Dependence::Backward:
2736145449b1SDimitry Andric     R << "\nBackward loop carried data dependence.";
2737145449b1SDimitry Andric     break;
2738145449b1SDimitry Andric   case MemoryDepChecker::Dependence::ForwardButPreventsForwarding:
2739145449b1SDimitry Andric     R << "\nForward loop carried data dependence that prevents "
2740145449b1SDimitry Andric          "store-to-load forwarding.";
2741145449b1SDimitry Andric     break;
2742145449b1SDimitry Andric   case MemoryDepChecker::Dependence::BackwardVectorizableButPreventsForwarding:
2743145449b1SDimitry Andric     R << "\nBackward loop carried data dependence that prevents "
2744145449b1SDimitry Andric          "store-to-load forwarding.";
2745145449b1SDimitry Andric     break;
2746b1c73532SDimitry Andric   case MemoryDepChecker::Dependence::IndirectUnsafe:
2747b1c73532SDimitry Andric     R << "\nUnsafe indirect dependence.";
2748b1c73532SDimitry Andric     break;
2749145449b1SDimitry Andric   case MemoryDepChecker::Dependence::Unknown:
2750145449b1SDimitry Andric     R << "\nUnknown data dependence.";
2751145449b1SDimitry Andric     break;
2752145449b1SDimitry Andric   }
2753145449b1SDimitry Andric 
2754ac9a064cSDimitry Andric   if (Instruction *I = Dep.getSource(getDepChecker())) {
2755145449b1SDimitry Andric     DebugLoc SourceLoc = I->getDebugLoc();
2756145449b1SDimitry Andric     if (auto *DD = dyn_cast_or_null<Instruction>(getPointerOperand(I)))
2757145449b1SDimitry Andric       SourceLoc = DD->getDebugLoc();
2758145449b1SDimitry Andric     if (SourceLoc)
2759145449b1SDimitry Andric       R << " Memory location is the same as accessed at "
2760145449b1SDimitry Andric         << ore::NV("Location", SourceLoc);
27615a5ac124SDimitry Andric   }
27625a5ac124SDimitry Andric }
27635a5ac124SDimitry Andric 
blockNeedsPredication(BasicBlock * BB,Loop * TheLoop,DominatorTree * DT)27645a5ac124SDimitry Andric bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
27655a5ac124SDimitry Andric                                            DominatorTree *DT)  {
27665a5ac124SDimitry Andric   assert(TheLoop->contains(BB) && "Unknown block used");
27675a5ac124SDimitry Andric 
27685a5ac124SDimitry Andric   // Blocks that do not dominate the latch need predication.
27695a5ac124SDimitry Andric   BasicBlock* Latch = TheLoop->getLoopLatch();
27705a5ac124SDimitry Andric   return !DT->dominates(BB, Latch);
27715a5ac124SDimitry Andric }
27725a5ac124SDimitry Andric 
recordAnalysis(StringRef RemarkName,Instruction * I)2773b915e9e0SDimitry Andric OptimizationRemarkAnalysis &LoopAccessInfo::recordAnalysis(StringRef RemarkName,
2774b915e9e0SDimitry Andric                                                            Instruction *I) {
27755a5ac124SDimitry Andric   assert(!Report && "Multiple reports generated");
2776b915e9e0SDimitry Andric 
2777b915e9e0SDimitry Andric   Value *CodeRegion = TheLoop->getHeader();
2778b915e9e0SDimitry Andric   DebugLoc DL = TheLoop->getStartLoc();
2779b915e9e0SDimitry Andric 
2780b915e9e0SDimitry Andric   if (I) {
2781b915e9e0SDimitry Andric     CodeRegion = I->getParent();
2782b915e9e0SDimitry Andric     // If there is no debug location attached to the instruction, revert back to
2783b915e9e0SDimitry Andric     // using the loop's.
2784b915e9e0SDimitry Andric     if (I->getDebugLoc())
2785b915e9e0SDimitry Andric       DL = I->getDebugLoc();
2786b915e9e0SDimitry Andric   }
2787b915e9e0SDimitry Andric 
27881d5ae102SDimitry Andric   Report = std::make_unique<OptimizationRemarkAnalysis>(DEBUG_TYPE, RemarkName, DL,
2789b915e9e0SDimitry Andric                                                    CodeRegion);
2790b915e9e0SDimitry Andric   return *Report;
27915a5ac124SDimitry Andric }
27925a5ac124SDimitry Andric 
isInvariant(Value * V) const27937fa27ce4SDimitry Andric bool LoopAccessInfo::isInvariant(Value *V) const {
2794b915e9e0SDimitry Andric   auto *SE = PSE->getSE();
2795b915e9e0SDimitry Andric   // TODO: Is this really what we want? Even without FP SCEV, we may want some
27967fa27ce4SDimitry Andric   // trivially loop-invariant FP values to be considered invariant.
2797b915e9e0SDimitry Andric   if (!SE->isSCEVable(V->getType()))
2798b915e9e0SDimitry Andric     return false;
27997fa27ce4SDimitry Andric   const SCEV *S = SE->getSCEV(V);
28007fa27ce4SDimitry Andric   return SE->isLoopInvariant(S, TheLoop);
28017fa27ce4SDimitry Andric }
28027fa27ce4SDimitry Andric 
28037fa27ce4SDimitry Andric /// Find the operand of the GEP that should be checked for consecutive
28047fa27ce4SDimitry Andric /// stores. This ignores trailing indices that have no effect on the final
28057fa27ce4SDimitry Andric /// pointer.
getGEPInductionOperand(const GetElementPtrInst * Gep)28067fa27ce4SDimitry Andric static unsigned getGEPInductionOperand(const GetElementPtrInst *Gep) {
2807ac9a064cSDimitry Andric   const DataLayout &DL = Gep->getDataLayout();
28087fa27ce4SDimitry Andric   unsigned LastOperand = Gep->getNumOperands() - 1;
28097fa27ce4SDimitry Andric   TypeSize GEPAllocSize = DL.getTypeAllocSize(Gep->getResultElementType());
28107fa27ce4SDimitry Andric 
28117fa27ce4SDimitry Andric   // Walk backwards and try to peel off zeros.
28127fa27ce4SDimitry Andric   while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
28137fa27ce4SDimitry Andric     // Find the type we're currently indexing into.
28147fa27ce4SDimitry Andric     gep_type_iterator GEPTI = gep_type_begin(Gep);
28157fa27ce4SDimitry Andric     std::advance(GEPTI, LastOperand - 2);
28167fa27ce4SDimitry Andric 
28177fa27ce4SDimitry Andric     // If it's a type with the same allocation size as the result of the GEP we
28187fa27ce4SDimitry Andric     // can peel off the zero index.
2819aca2e42cSDimitry Andric     TypeSize ElemSize = GEPTI.isStruct()
2820aca2e42cSDimitry Andric                             ? DL.getTypeAllocSize(GEPTI.getIndexedType())
2821aca2e42cSDimitry Andric                             : GEPTI.getSequentialElementStride(DL);
2822aca2e42cSDimitry Andric     if (ElemSize != GEPAllocSize)
28237fa27ce4SDimitry Andric       break;
28247fa27ce4SDimitry Andric     --LastOperand;
28257fa27ce4SDimitry Andric   }
28267fa27ce4SDimitry Andric 
28277fa27ce4SDimitry Andric   return LastOperand;
28287fa27ce4SDimitry Andric }
28297fa27ce4SDimitry Andric 
28307fa27ce4SDimitry Andric /// If the argument is a GEP, then returns the operand identified by
28317fa27ce4SDimitry Andric /// getGEPInductionOperand. However, if there is some other non-loop-invariant
28327fa27ce4SDimitry Andric /// operand, it returns that instead.
stripGetElementPtr(Value * Ptr,ScalarEvolution * SE,Loop * Lp)28337fa27ce4SDimitry Andric static Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
28347fa27ce4SDimitry Andric   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
28357fa27ce4SDimitry Andric   if (!GEP)
28367fa27ce4SDimitry Andric     return Ptr;
28377fa27ce4SDimitry Andric 
28387fa27ce4SDimitry Andric   unsigned InductionOperand = getGEPInductionOperand(GEP);
28397fa27ce4SDimitry Andric 
28407fa27ce4SDimitry Andric   // Check that all of the gep indices are uniform except for our induction
28417fa27ce4SDimitry Andric   // operand.
2842ac9a064cSDimitry Andric   for (unsigned I = 0, E = GEP->getNumOperands(); I != E; ++I)
2843ac9a064cSDimitry Andric     if (I != InductionOperand &&
2844ac9a064cSDimitry Andric         !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(I)), Lp))
28457fa27ce4SDimitry Andric       return Ptr;
28467fa27ce4SDimitry Andric   return GEP->getOperand(InductionOperand);
28477fa27ce4SDimitry Andric }
28487fa27ce4SDimitry Andric 
28497fa27ce4SDimitry Andric /// Get the stride of a pointer access in a loop. Looks for symbolic
28507fa27ce4SDimitry Andric /// strides "a[i*stride]". Returns the symbolic stride, or null otherwise.
getStrideFromPointer(Value * Ptr,ScalarEvolution * SE,Loop * Lp)28517fa27ce4SDimitry Andric static const SCEV *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
28527fa27ce4SDimitry Andric   auto *PtrTy = dyn_cast<PointerType>(Ptr->getType());
28537fa27ce4SDimitry Andric   if (!PtrTy || PtrTy->isAggregateType())
28547fa27ce4SDimitry Andric     return nullptr;
28557fa27ce4SDimitry Andric 
28567fa27ce4SDimitry Andric   // Try to remove a gep instruction to make the pointer (actually index at this
28577fa27ce4SDimitry Andric   // point) easier analyzable. If OrigPtr is equal to Ptr we are analyzing the
28587fa27ce4SDimitry Andric   // pointer, otherwise, we are analyzing the index.
28597fa27ce4SDimitry Andric   Value *OrigPtr = Ptr;
28607fa27ce4SDimitry Andric 
28617fa27ce4SDimitry Andric   // The size of the pointer access.
28627fa27ce4SDimitry Andric   int64_t PtrAccessSize = 1;
28637fa27ce4SDimitry Andric 
28647fa27ce4SDimitry Andric   Ptr = stripGetElementPtr(Ptr, SE, Lp);
28657fa27ce4SDimitry Andric   const SCEV *V = SE->getSCEV(Ptr);
28667fa27ce4SDimitry Andric 
28677fa27ce4SDimitry Andric   if (Ptr != OrigPtr)
28687fa27ce4SDimitry Andric     // Strip off casts.
28697fa27ce4SDimitry Andric     while (const SCEVIntegralCastExpr *C = dyn_cast<SCEVIntegralCastExpr>(V))
28707fa27ce4SDimitry Andric       V = C->getOperand();
28717fa27ce4SDimitry Andric 
28727fa27ce4SDimitry Andric   const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
28737fa27ce4SDimitry Andric   if (!S)
28747fa27ce4SDimitry Andric     return nullptr;
28757fa27ce4SDimitry Andric 
28767fa27ce4SDimitry Andric   // If the pointer is invariant then there is no stride and it makes no
28777fa27ce4SDimitry Andric   // sense to add it here.
28787fa27ce4SDimitry Andric   if (Lp != S->getLoop())
28797fa27ce4SDimitry Andric     return nullptr;
28807fa27ce4SDimitry Andric 
28817fa27ce4SDimitry Andric   V = S->getStepRecurrence(*SE);
28827fa27ce4SDimitry Andric   if (!V)
28837fa27ce4SDimitry Andric     return nullptr;
28847fa27ce4SDimitry Andric 
28857fa27ce4SDimitry Andric   // Strip off the size of access multiplication if we are still analyzing the
28867fa27ce4SDimitry Andric   // pointer.
28877fa27ce4SDimitry Andric   if (OrigPtr == Ptr) {
28887fa27ce4SDimitry Andric     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
28897fa27ce4SDimitry Andric       if (M->getOperand(0)->getSCEVType() != scConstant)
28907fa27ce4SDimitry Andric         return nullptr;
28917fa27ce4SDimitry Andric 
28927fa27ce4SDimitry Andric       const APInt &APStepVal = cast<SCEVConstant>(M->getOperand(0))->getAPInt();
28937fa27ce4SDimitry Andric 
28947fa27ce4SDimitry Andric       // Huge step value - give up.
28957fa27ce4SDimitry Andric       if (APStepVal.getBitWidth() > 64)
28967fa27ce4SDimitry Andric         return nullptr;
28977fa27ce4SDimitry Andric 
28987fa27ce4SDimitry Andric       int64_t StepVal = APStepVal.getSExtValue();
28997fa27ce4SDimitry Andric       if (PtrAccessSize != StepVal)
29007fa27ce4SDimitry Andric         return nullptr;
29017fa27ce4SDimitry Andric       V = M->getOperand(1);
29027fa27ce4SDimitry Andric     }
29037fa27ce4SDimitry Andric   }
29047fa27ce4SDimitry Andric 
29057fa27ce4SDimitry Andric   // Note that the restriction after this loop invariant check are only
29067fa27ce4SDimitry Andric   // profitability restrictions.
29077fa27ce4SDimitry Andric   if (!SE->isLoopInvariant(V, Lp))
29087fa27ce4SDimitry Andric     return nullptr;
29097fa27ce4SDimitry Andric 
29107fa27ce4SDimitry Andric   // Look for the loop invariant symbolic value.
2911ac9a064cSDimitry Andric   if (isa<SCEVUnknown>(V))
29127fa27ce4SDimitry Andric     return V;
2913ac9a064cSDimitry Andric 
2914ac9a064cSDimitry Andric   if (const auto *C = dyn_cast<SCEVIntegralCastExpr>(V))
2915ac9a064cSDimitry Andric     if (isa<SCEVUnknown>(C->getOperand()))
2916ac9a064cSDimitry Andric       return V;
2917ac9a064cSDimitry Andric 
2918ac9a064cSDimitry Andric   return nullptr;
29195a5ac124SDimitry Andric }
29205a5ac124SDimitry Andric 
collectStridedAccess(Value * MemAccess)292101095a5dSDimitry Andric void LoopAccessInfo::collectStridedAccess(Value *MemAccess) {
2922b60736ecSDimitry Andric   Value *Ptr = getLoadStorePointerOperand(MemAccess);
2923b60736ecSDimitry Andric   if (!Ptr)
292401095a5dSDimitry Andric     return;
292501095a5dSDimitry Andric 
29267fa27ce4SDimitry Andric   // Note: getStrideFromPointer is a *profitability* heuristic.  We
29277fa27ce4SDimitry Andric   // could broaden the scope of values returned here - to anything
29287fa27ce4SDimitry Andric   // which happens to be loop invariant and contributes to the
29297fa27ce4SDimitry Andric   // computation of an interesting IV - but we chose not to as we
29307fa27ce4SDimitry Andric   // don't have a cost model here, and broadening the scope exposes
29317fa27ce4SDimitry Andric   // far too many unprofitable cases.
29327fa27ce4SDimitry Andric   const SCEV *StrideExpr = getStrideFromPointer(Ptr, PSE->getSE(), TheLoop);
29337fa27ce4SDimitry Andric   if (!StrideExpr)
293401095a5dSDimitry Andric     return;
293501095a5dSDimitry Andric 
2936eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: Found a strided access that is a candidate for "
2937044eb2f6SDimitry Andric                        "versioning:");
29387fa27ce4SDimitry Andric   LLVM_DEBUG(dbgs() << "  Ptr: " << *Ptr << " Stride: " << *StrideExpr << "\n");
29397fa27ce4SDimitry Andric 
29407fa27ce4SDimitry Andric   if (!SpeculateUnitStride) {
29417fa27ce4SDimitry Andric     LLVM_DEBUG(dbgs() << "  Chose not to due to -laa-speculate-unit-stride\n");
29427fa27ce4SDimitry Andric     return;
29437fa27ce4SDimitry Andric   }
2944044eb2f6SDimitry Andric 
2945044eb2f6SDimitry Andric   // Avoid adding the "Stride == 1" predicate when we know that
2946044eb2f6SDimitry Andric   // Stride >= Trip-Count. Such a predicate will effectively optimize a single
2947044eb2f6SDimitry Andric   // or zero iteration loop, as Trip-Count <= Stride == 1.
2948044eb2f6SDimitry Andric   //
2949044eb2f6SDimitry Andric   // TODO: We are currently not making a very informed decision on when it is
2950044eb2f6SDimitry Andric   // beneficial to apply stride versioning. It might make more sense that the
2951044eb2f6SDimitry Andric   // users of this analysis (such as the vectorizer) will trigger it, based on
2952044eb2f6SDimitry Andric   // their specific cost considerations; For example, in cases where stride
2953044eb2f6SDimitry Andric   // versioning does  not help resolving memory accesses/dependences, the
2954044eb2f6SDimitry Andric   // vectorizer should evaluate the cost of the runtime test, and the benefit
2955044eb2f6SDimitry Andric   // of various possible stride specializations, considering the alternatives
2956044eb2f6SDimitry Andric   // of using gather/scatters (if available).
2957044eb2f6SDimitry Andric 
2958ac9a064cSDimitry Andric   const SCEV *MaxBTC = PSE->getSymbolicMaxBackedgeTakenCount();
2959044eb2f6SDimitry Andric 
2960ac9a064cSDimitry Andric   // Match the types so we can compare the stride and the MaxBTC.
2961044eb2f6SDimitry Andric   // The Stride can be positive/negative, so we sign extend Stride;
2962ac9a064cSDimitry Andric   // The backedgeTakenCount is non-negative, so we zero extend MaxBTC.
2963ac9a064cSDimitry Andric   const DataLayout &DL = TheLoop->getHeader()->getDataLayout();
2964145449b1SDimitry Andric   uint64_t StrideTypeSizeBits = DL.getTypeSizeInBits(StrideExpr->getType());
2965ac9a064cSDimitry Andric   uint64_t BETypeSizeBits = DL.getTypeSizeInBits(MaxBTC->getType());
2966044eb2f6SDimitry Andric   const SCEV *CastedStride = StrideExpr;
2967ac9a064cSDimitry Andric   const SCEV *CastedBECount = MaxBTC;
2968044eb2f6SDimitry Andric   ScalarEvolution *SE = PSE->getSE();
2969145449b1SDimitry Andric   if (BETypeSizeBits >= StrideTypeSizeBits)
2970ac9a064cSDimitry Andric     CastedStride = SE->getNoopOrSignExtend(StrideExpr, MaxBTC->getType());
2971044eb2f6SDimitry Andric   else
2972ac9a064cSDimitry Andric     CastedBECount = SE->getZeroExtendExpr(MaxBTC, StrideExpr->getType());
2973044eb2f6SDimitry Andric   const SCEV *StrideMinusBETaken = SE->getMinusSCEV(CastedStride, CastedBECount);
2974044eb2f6SDimitry Andric   // Since TripCount == BackEdgeTakenCount + 1, checking:
2975044eb2f6SDimitry Andric   // "Stride >= TripCount" is equivalent to checking:
2976ac9a064cSDimitry Andric   // Stride - MaxBTC> 0
2977044eb2f6SDimitry Andric   if (SE->isKnownPositive(StrideMinusBETaken)) {
2978eb11fae6SDimitry Andric     LLVM_DEBUG(
2979eb11fae6SDimitry Andric         dbgs() << "LAA: Stride>=TripCount; No point in versioning as the "
2980044eb2f6SDimitry Andric                   "Stride==1 predicate will imply that the loop executes "
2981044eb2f6SDimitry Andric                   "at most once.\n");
2982044eb2f6SDimitry Andric     return;
2983044eb2f6SDimitry Andric   }
2984145449b1SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: Found a strided access that we can version.\n");
2985044eb2f6SDimitry Andric 
29867fa27ce4SDimitry Andric   // Strip back off the integer cast, and check that our result is a
29877fa27ce4SDimitry Andric   // SCEVUnknown as we expect.
29887fa27ce4SDimitry Andric   const SCEV *StrideBase = StrideExpr;
29897fa27ce4SDimitry Andric   if (const auto *C = dyn_cast<SCEVIntegralCastExpr>(StrideBase))
29907fa27ce4SDimitry Andric     StrideBase = C->getOperand();
29917fa27ce4SDimitry Andric   SymbolicStrides[Ptr] = cast<SCEVUnknown>(StrideBase);
2992dd58ef01SDimitry Andric }
2993dd58ef01SDimitry Andric 
LoopAccessInfo(Loop * L,ScalarEvolution * SE,const TargetTransformInfo * TTI,const TargetLibraryInfo * TLI,AAResults * AA,DominatorTree * DT,LoopInfo * LI)29945a5ac124SDimitry Andric LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
2995ac9a064cSDimitry Andric                                const TargetTransformInfo *TTI,
2996cfca06d7SDimitry Andric                                const TargetLibraryInfo *TLI, AAResults *AA,
299701095a5dSDimitry Andric                                DominatorTree *DT, LoopInfo *LI)
29981d5ae102SDimitry Andric     : PSE(std::make_unique<PredicatedScalarEvolution>(*SE, *L)),
2999ac9a064cSDimitry Andric       PtrRtChecking(nullptr), TheLoop(L) {
3000ac9a064cSDimitry Andric   unsigned MaxTargetVectorWidthInBits = std::numeric_limits<unsigned>::max();
3001ac9a064cSDimitry Andric   if (TTI) {
3002ac9a064cSDimitry Andric     TypeSize FixedWidth =
3003ac9a064cSDimitry Andric         TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector);
3004ac9a064cSDimitry Andric     if (FixedWidth.isNonZero()) {
3005ac9a064cSDimitry Andric       // Scale the vector width by 2 as rough estimate to also consider
3006ac9a064cSDimitry Andric       // interleaving.
3007ac9a064cSDimitry Andric       MaxTargetVectorWidthInBits = FixedWidth.getFixedValue() * 2;
30085a5ac124SDimitry Andric     }
3009ac9a064cSDimitry Andric 
3010ac9a064cSDimitry Andric     TypeSize ScalableWidth =
3011ac9a064cSDimitry Andric         TTI->getRegisterBitWidth(TargetTransformInfo::RGK_ScalableVector);
3012ac9a064cSDimitry Andric     if (ScalableWidth.isNonZero())
3013ac9a064cSDimitry Andric       MaxTargetVectorWidthInBits = std::numeric_limits<unsigned>::max();
3014ac9a064cSDimitry Andric   }
3015ac9a064cSDimitry Andric   DepChecker = std::make_unique<MemoryDepChecker>(*PSE, L, SymbolicStrides,
3016ac9a064cSDimitry Andric                                                   MaxTargetVectorWidthInBits);
3017ac9a064cSDimitry Andric   PtrRtChecking = std::make_unique<RuntimePointerChecking>(*DepChecker, SE);
3018ac9a064cSDimitry Andric   if (canAnalyzeLoop())
3019ac9a064cSDimitry Andric     CanVecMem = analyzeLoop(AA, LI, TLI, DT);
3020145449b1SDimitry Andric }
30215a5ac124SDimitry Andric 
print(raw_ostream & OS,unsigned Depth) const30225a5ac124SDimitry Andric void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
30235a5ac124SDimitry Andric   if (CanVecMem) {
302401095a5dSDimitry Andric     OS.indent(Depth) << "Memory dependences are safe";
3025b1c73532SDimitry Andric     const MemoryDepChecker &DC = getDepChecker();
3026b1c73532SDimitry Andric     if (!DC.isSafeForAnyVectorWidth())
3027b1c73532SDimitry Andric       OS << " with a maximum safe vector width of "
3028b1c73532SDimitry Andric          << DC.getMaxSafeVectorWidthInBits() << " bits";
302901095a5dSDimitry Andric     if (PtrRtChecking->Need)
303001095a5dSDimitry Andric       OS << " with run-time checks";
303101095a5dSDimitry Andric     OS << "\n";
30325a5ac124SDimitry Andric   }
30335a5ac124SDimitry Andric 
3034e6d15924SDimitry Andric   if (HasConvergentOp)
3035e6d15924SDimitry Andric     OS.indent(Depth) << "Has convergent operation in loop\n";
3036e6d15924SDimitry Andric 
30375a5ac124SDimitry Andric   if (Report)
3038b915e9e0SDimitry Andric     OS.indent(Depth) << "Report: " << Report->getMsg() << "\n";
30395a5ac124SDimitry Andric 
304001095a5dSDimitry Andric   if (auto *Dependences = DepChecker->getDependences()) {
3041dd58ef01SDimitry Andric     OS.indent(Depth) << "Dependences:\n";
30424b4fe385SDimitry Andric     for (const auto &Dep : *Dependences) {
304301095a5dSDimitry Andric       Dep.print(OS, Depth + 2, DepChecker->getMemoryInstructions());
30445a5ac124SDimitry Andric       OS << "\n";
30455a5ac124SDimitry Andric     }
30465a5ac124SDimitry Andric   } else
3047dd58ef01SDimitry Andric     OS.indent(Depth) << "Too many dependences, not recorded\n";
30485a5ac124SDimitry Andric 
30495a5ac124SDimitry Andric   // List the pair of accesses need run-time checks to prove independence.
305001095a5dSDimitry Andric   PtrRtChecking->print(OS, Depth);
30515a5ac124SDimitry Andric   OS << "\n";
30525a5ac124SDimitry Andric 
3053ac9a064cSDimitry Andric   OS.indent(Depth)
3054ac9a064cSDimitry Andric       << "Non vectorizable stores to invariant address were "
3055ac9a064cSDimitry Andric       << (HasStoreStoreDependenceInvolvingLoopInvariantAddress ||
3056ac9a064cSDimitry Andric                   HasLoadStoreDependenceInvolvingLoopInvariantAddress
3057ac9a064cSDimitry Andric               ? ""
3058ac9a064cSDimitry Andric               : "not ")
30595a5ac124SDimitry Andric       << "found in loop.\n";
3060dd58ef01SDimitry Andric 
3061dd58ef01SDimitry Andric   OS.indent(Depth) << "SCEV assumptions:\n";
3062145449b1SDimitry Andric   PSE->getPredicate().print(OS, Depth);
306301095a5dSDimitry Andric 
306401095a5dSDimitry Andric   OS << "\n";
306501095a5dSDimitry Andric 
306601095a5dSDimitry Andric   OS.indent(Depth) << "Expressions re-written:\n";
306701095a5dSDimitry Andric   PSE->print(OS, Depth);
30685a5ac124SDimitry Andric }
30695a5ac124SDimitry Andric 
getInfo(Loop & L)3070e3b55780SDimitry Andric const LoopAccessInfo &LoopAccessInfoManager::getInfo(Loop &L) {
3071ac9a064cSDimitry Andric   auto [It, Inserted] = LoopAccessInfoMap.insert({&L, nullptr});
3072e3b55780SDimitry Andric 
3073ac9a064cSDimitry Andric   if (Inserted)
3074ac9a064cSDimitry Andric     It->second =
3075ac9a064cSDimitry Andric         std::make_unique<LoopAccessInfo>(&L, &SE, TTI, TLI, &AA, &DT, &LI);
3076e3b55780SDimitry Andric 
3077ac9a064cSDimitry Andric   return *It->second;
3078ac9a064cSDimitry Andric }
clear()3079ac9a064cSDimitry Andric void LoopAccessInfoManager::clear() {
3080ac9a064cSDimitry Andric   SmallVector<Loop *> ToRemove;
3081ac9a064cSDimitry Andric   // Collect LoopAccessInfo entries that may keep references to IR outside the
3082ac9a064cSDimitry Andric   // analyzed loop or SCEVs that may have been modified or invalidated. At the
3083ac9a064cSDimitry Andric   // moment, that is loops requiring memory or SCEV runtime checks, as those cache
3084ac9a064cSDimitry Andric   // SCEVs, e.g. for pointer expressions.
3085ac9a064cSDimitry Andric   for (const auto &[L, LAI] : LoopAccessInfoMap) {
3086ac9a064cSDimitry Andric     if (LAI->getRuntimePointerChecking()->getChecks().empty() &&
3087ac9a064cSDimitry Andric         LAI->getPSE().getPredicate().isAlwaysTrue())
3088ac9a064cSDimitry Andric       continue;
3089ac9a064cSDimitry Andric     ToRemove.push_back(L);
3090ac9a064cSDimitry Andric   }
3091ac9a064cSDimitry Andric 
3092ac9a064cSDimitry Andric   for (Loop *L : ToRemove)
3093ac9a064cSDimitry Andric     LoopAccessInfoMap.erase(L);
3094e3b55780SDimitry Andric }
3095e3b55780SDimitry Andric 
invalidate(Function & F,const PreservedAnalyses & PA,FunctionAnalysisManager::Invalidator & Inv)30967fa27ce4SDimitry Andric bool LoopAccessInfoManager::invalidate(
30977fa27ce4SDimitry Andric     Function &F, const PreservedAnalyses &PA,
30987fa27ce4SDimitry Andric     FunctionAnalysisManager::Invalidator &Inv) {
30997fa27ce4SDimitry Andric   // Check whether our analysis is preserved.
31007fa27ce4SDimitry Andric   auto PAC = PA.getChecker<LoopAccessAnalysis>();
31017fa27ce4SDimitry Andric   if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<Function>>())
31027fa27ce4SDimitry Andric     // If not, give up now.
31037fa27ce4SDimitry Andric     return true;
3104706b4fc4SDimitry Andric 
31057fa27ce4SDimitry Andric   // Check whether the analyses we depend on became invalid for any reason.
31067fa27ce4SDimitry Andric   // Skip checking TargetLibraryAnalysis as it is immutable and can't become
31077fa27ce4SDimitry Andric   // invalid.
31087fa27ce4SDimitry Andric   return Inv.invalidate<AAManager>(F, PA) ||
31097fa27ce4SDimitry Andric          Inv.invalidate<ScalarEvolutionAnalysis>(F, PA) ||
31107fa27ce4SDimitry Andric          Inv.invalidate<LoopAnalysis>(F, PA) ||
31117fa27ce4SDimitry Andric          Inv.invalidate<DominatorTreeAnalysis>(F, PA);
31125a5ac124SDimitry Andric }
31135a5ac124SDimitry Andric 
run(Function & F,FunctionAnalysisManager & FAM)3114e3b55780SDimitry Andric LoopAccessInfoManager LoopAccessAnalysis::run(Function &F,
31157fa27ce4SDimitry Andric                                               FunctionAnalysisManager &FAM) {
31167fa27ce4SDimitry Andric   auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
31177fa27ce4SDimitry Andric   auto &AA = FAM.getResult<AAManager>(F);
31187fa27ce4SDimitry Andric   auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
31197fa27ce4SDimitry Andric   auto &LI = FAM.getResult<LoopAnalysis>(F);
3120ac9a064cSDimitry Andric   auto &TTI = FAM.getResult<TargetIRAnalysis>(F);
31217fa27ce4SDimitry Andric   auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
3122ac9a064cSDimitry Andric   return LoopAccessInfoManager(SE, AA, DT, LI, &TTI, &TLI);
3123e3b55780SDimitry Andric }
3124e3b55780SDimitry Andric 
3125b915e9e0SDimitry Andric AnalysisKey LoopAccessAnalysis::Key;
3126