xref: /freebsd-src/contrib/llvm-project/llvm/lib/Analysis/LoopAccessAnalysis.cpp (revision 7a6dacaca14b62ca4b74406814becb87a3fefac0)
1 //===- LoopAccessAnalysis.cpp - Loop Access Analysis Implementation --------==//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // The implementation for the loop memory dependence that was originally
10 // developed for the loop vectorizer.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Analysis/LoopAccessAnalysis.h"
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/EquivalenceClasses.h"
18 #include "llvm/ADT/PointerIntPair.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/Analysis/AliasSetTracker.h"
26 #include "llvm/Analysis/LoopAnalysisManager.h"
27 #include "llvm/Analysis/LoopInfo.h"
28 #include "llvm/Analysis/LoopIterator.h"
29 #include "llvm/Analysis/MemoryLocation.h"
30 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
31 #include "llvm/Analysis/ScalarEvolution.h"
32 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
33 #include "llvm/Analysis/TargetLibraryInfo.h"
34 #include "llvm/Analysis/ValueTracking.h"
35 #include "llvm/Analysis/VectorUtils.h"
36 #include "llvm/IR/BasicBlock.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/DataLayout.h"
39 #include "llvm/IR/DebugLoc.h"
40 #include "llvm/IR/DerivedTypes.h"
41 #include "llvm/IR/DiagnosticInfo.h"
42 #include "llvm/IR/Dominators.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/IR/GetElementPtrTypeIterator.h"
45 #include "llvm/IR/InstrTypes.h"
46 #include "llvm/IR/Instruction.h"
47 #include "llvm/IR/Instructions.h"
48 #include "llvm/IR/Operator.h"
49 #include "llvm/IR/PassManager.h"
50 #include "llvm/IR/PatternMatch.h"
51 #include "llvm/IR/Type.h"
52 #include "llvm/IR/Value.h"
53 #include "llvm/IR/ValueHandle.h"
54 #include "llvm/Support/Casting.h"
55 #include "llvm/Support/CommandLine.h"
56 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/ErrorHandling.h"
58 #include "llvm/Support/raw_ostream.h"
59 #include <algorithm>
60 #include <cassert>
61 #include <cstdint>
62 #include <iterator>
63 #include <utility>
64 #include <variant>
65 #include <vector>
66 
67 using namespace llvm;
68 using namespace llvm::PatternMatch;
69 
70 #define DEBUG_TYPE "loop-accesses"
71 
72 static cl::opt<unsigned, true>
73 VectorizationFactor("force-vector-width", cl::Hidden,
74                     cl::desc("Sets the SIMD width. Zero is autoselect."),
75                     cl::location(VectorizerParams::VectorizationFactor));
76 unsigned VectorizerParams::VectorizationFactor;
77 
78 static cl::opt<unsigned, true>
79 VectorizationInterleave("force-vector-interleave", cl::Hidden,
80                         cl::desc("Sets the vectorization interleave count. "
81                                  "Zero is autoselect."),
82                         cl::location(
83                             VectorizerParams::VectorizationInterleave));
84 unsigned VectorizerParams::VectorizationInterleave;
85 
86 static cl::opt<unsigned, true> RuntimeMemoryCheckThreshold(
87     "runtime-memory-check-threshold", cl::Hidden,
88     cl::desc("When performing memory disambiguation checks at runtime do not "
89              "generate more than this number of comparisons (default = 8)."),
90     cl::location(VectorizerParams::RuntimeMemoryCheckThreshold), cl::init(8));
91 unsigned VectorizerParams::RuntimeMemoryCheckThreshold;
92 
93 /// The maximum iterations used to merge memory checks
94 static cl::opt<unsigned> MemoryCheckMergeThreshold(
95     "memory-check-merge-threshold", cl::Hidden,
96     cl::desc("Maximum number of comparisons done when trying to merge "
97              "runtime memory checks. (default = 100)"),
98     cl::init(100));
99 
100 /// Maximum SIMD width.
101 const unsigned VectorizerParams::MaxVectorWidth = 64;
102 
103 /// We collect dependences up to this threshold.
104 static cl::opt<unsigned>
105     MaxDependences("max-dependences", cl::Hidden,
106                    cl::desc("Maximum number of dependences collected by "
107                             "loop-access analysis (default = 100)"),
108                    cl::init(100));
109 
110 /// This enables versioning on the strides of symbolically striding memory
111 /// accesses in code like the following.
112 ///   for (i = 0; i < N; ++i)
113 ///     A[i * Stride1] += B[i * Stride2] ...
114 ///
115 /// Will be roughly translated to
116 ///    if (Stride1 == 1 && Stride2 == 1) {
117 ///      for (i = 0; i < N; i+=4)
118 ///       A[i:i+3] += ...
119 ///    } else
120 ///      ...
121 static cl::opt<bool> EnableMemAccessVersioning(
122     "enable-mem-access-versioning", cl::init(true), cl::Hidden,
123     cl::desc("Enable symbolic stride memory access versioning"));
124 
125 /// Enable store-to-load forwarding conflict detection. This option can
126 /// be disabled for correctness testing.
127 static cl::opt<bool> EnableForwardingConflictDetection(
128     "store-to-load-forwarding-conflict-detection", cl::Hidden,
129     cl::desc("Enable conflict detection in loop-access analysis"),
130     cl::init(true));
131 
132 static cl::opt<unsigned> MaxForkedSCEVDepth(
133     "max-forked-scev-depth", cl::Hidden,
134     cl::desc("Maximum recursion depth when finding forked SCEVs (default = 5)"),
135     cl::init(5));
136 
137 static cl::opt<bool> SpeculateUnitStride(
138     "laa-speculate-unit-stride", cl::Hidden,
139     cl::desc("Speculate that non-constant strides are unit in LAA"),
140     cl::init(true));
141 
142 static cl::opt<bool, true> HoistRuntimeChecks(
143     "hoist-runtime-checks", cl::Hidden,
144     cl::desc(
145         "Hoist inner loop runtime memory checks to outer loop if possible"),
146     cl::location(VectorizerParams::HoistRuntimeChecks), cl::init(true));
147 bool VectorizerParams::HoistRuntimeChecks;
148 
149 bool VectorizerParams::isInterleaveForced() {
150   return ::VectorizationInterleave.getNumOccurrences() > 0;
151 }
152 
153 const SCEV *llvm::replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE,
154                                             const DenseMap<Value *, const SCEV *> &PtrToStride,
155                                             Value *Ptr) {
156   const SCEV *OrigSCEV = PSE.getSCEV(Ptr);
157 
158   // If there is an entry in the map return the SCEV of the pointer with the
159   // symbolic stride replaced by one.
160   DenseMap<Value *, const SCEV *>::const_iterator SI = PtrToStride.find(Ptr);
161   if (SI == PtrToStride.end())
162     // For a non-symbolic stride, just return the original expression.
163     return OrigSCEV;
164 
165   const SCEV *StrideSCEV = SI->second;
166   // Note: This assert is both overly strong and overly weak.  The actual
167   // invariant here is that StrideSCEV should be loop invariant.  The only
168   // such invariant strides we happen to speculate right now are unknowns
169   // and thus this is a reasonable proxy of the actual invariant.
170   assert(isa<SCEVUnknown>(StrideSCEV) && "shouldn't be in map");
171 
172   ScalarEvolution *SE = PSE.getSE();
173   const auto *CT = SE->getOne(StrideSCEV->getType());
174   PSE.addPredicate(*SE->getEqualPredicate(StrideSCEV, CT));
175   auto *Expr = PSE.getSCEV(Ptr);
176 
177   LLVM_DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV
178 	     << " by: " << *Expr << "\n");
179   return Expr;
180 }
181 
182 RuntimeCheckingPtrGroup::RuntimeCheckingPtrGroup(
183     unsigned Index, RuntimePointerChecking &RtCheck)
184     : High(RtCheck.Pointers[Index].End), Low(RtCheck.Pointers[Index].Start),
185       AddressSpace(RtCheck.Pointers[Index]
186                        .PointerValue->getType()
187                        ->getPointerAddressSpace()),
188       NeedsFreeze(RtCheck.Pointers[Index].NeedsFreeze) {
189   Members.push_back(Index);
190 }
191 
192 /// Calculate Start and End points of memory access.
193 /// Let's assume A is the first access and B is a memory access on N-th loop
194 /// iteration. Then B is calculated as:
195 ///   B = A + Step*N .
196 /// Step value may be positive or negative.
197 /// N is a calculated back-edge taken count:
198 ///     N = (TripCount > 0) ? RoundDown(TripCount -1 , VF) : 0
199 /// Start and End points are calculated in the following way:
200 /// Start = UMIN(A, B) ; End = UMAX(A, B) + SizeOfElt,
201 /// where SizeOfElt is the size of single memory access in bytes.
202 ///
203 /// There is no conflict when the intervals are disjoint:
204 /// NoConflict = (P2.Start >= P1.End) || (P1.Start >= P2.End)
205 void RuntimePointerChecking::insert(Loop *Lp, Value *Ptr, const SCEV *PtrExpr,
206                                     Type *AccessTy, bool WritePtr,
207                                     unsigned DepSetId, unsigned ASId,
208                                     PredicatedScalarEvolution &PSE,
209                                     bool NeedsFreeze) {
210   ScalarEvolution *SE = PSE.getSE();
211 
212   const SCEV *ScStart;
213   const SCEV *ScEnd;
214 
215   if (SE->isLoopInvariant(PtrExpr, Lp)) {
216     ScStart = ScEnd = PtrExpr;
217   } else {
218     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrExpr);
219     assert(AR && "Invalid addrec expression");
220     const SCEV *Ex = PSE.getBackedgeTakenCount();
221 
222     ScStart = AR->getStart();
223     ScEnd = AR->evaluateAtIteration(Ex, *SE);
224     const SCEV *Step = AR->getStepRecurrence(*SE);
225 
226     // For expressions with negative step, the upper bound is ScStart and the
227     // lower bound is ScEnd.
228     if (const auto *CStep = dyn_cast<SCEVConstant>(Step)) {
229       if (CStep->getValue()->isNegative())
230         std::swap(ScStart, ScEnd);
231     } else {
232       // Fallback case: the step is not constant, but we can still
233       // get the upper and lower bounds of the interval by using min/max
234       // expressions.
235       ScStart = SE->getUMinExpr(ScStart, ScEnd);
236       ScEnd = SE->getUMaxExpr(AR->getStart(), ScEnd);
237     }
238   }
239   assert(SE->isLoopInvariant(ScStart, Lp) && "ScStart needs to be invariant");
240   assert(SE->isLoopInvariant(ScEnd, Lp)&& "ScEnd needs to be invariant");
241 
242   // Add the size of the pointed element to ScEnd.
243   auto &DL = Lp->getHeader()->getModule()->getDataLayout();
244   Type *IdxTy = DL.getIndexType(Ptr->getType());
245   const SCEV *EltSizeSCEV = SE->getStoreSizeOfExpr(IdxTy, AccessTy);
246   ScEnd = SE->getAddExpr(ScEnd, EltSizeSCEV);
247 
248   Pointers.emplace_back(Ptr, ScStart, ScEnd, WritePtr, DepSetId, ASId, PtrExpr,
249                         NeedsFreeze);
250 }
251 
252 void RuntimePointerChecking::tryToCreateDiffCheck(
253     const RuntimeCheckingPtrGroup &CGI, const RuntimeCheckingPtrGroup &CGJ) {
254   if (!CanUseDiffCheck)
255     return;
256 
257   // If either group contains multiple different pointers, bail out.
258   // TODO: Support multiple pointers by using the minimum or maximum pointer,
259   // depending on src & sink.
260   if (CGI.Members.size() != 1 || CGJ.Members.size() != 1) {
261     CanUseDiffCheck = false;
262     return;
263   }
264 
265   PointerInfo *Src = &Pointers[CGI.Members[0]];
266   PointerInfo *Sink = &Pointers[CGJ.Members[0]];
267 
268   // If either pointer is read and written, multiple checks may be needed. Bail
269   // out.
270   if (!DC.getOrderForAccess(Src->PointerValue, !Src->IsWritePtr).empty() ||
271       !DC.getOrderForAccess(Sink->PointerValue, !Sink->IsWritePtr).empty()) {
272     CanUseDiffCheck = false;
273     return;
274   }
275 
276   ArrayRef<unsigned> AccSrc =
277       DC.getOrderForAccess(Src->PointerValue, Src->IsWritePtr);
278   ArrayRef<unsigned> AccSink =
279       DC.getOrderForAccess(Sink->PointerValue, Sink->IsWritePtr);
280   // If either pointer is accessed multiple times, there may not be a clear
281   // src/sink relation. Bail out for now.
282   if (AccSrc.size() != 1 || AccSink.size() != 1) {
283     CanUseDiffCheck = false;
284     return;
285   }
286   // If the sink is accessed before src, swap src/sink.
287   if (AccSink[0] < AccSrc[0])
288     std::swap(Src, Sink);
289 
290   auto *SrcAR = dyn_cast<SCEVAddRecExpr>(Src->Expr);
291   auto *SinkAR = dyn_cast<SCEVAddRecExpr>(Sink->Expr);
292   if (!SrcAR || !SinkAR || SrcAR->getLoop() != DC.getInnermostLoop() ||
293       SinkAR->getLoop() != DC.getInnermostLoop()) {
294     CanUseDiffCheck = false;
295     return;
296   }
297 
298   SmallVector<Instruction *, 4> SrcInsts =
299       DC.getInstructionsForAccess(Src->PointerValue, Src->IsWritePtr);
300   SmallVector<Instruction *, 4> SinkInsts =
301       DC.getInstructionsForAccess(Sink->PointerValue, Sink->IsWritePtr);
302   Type *SrcTy = getLoadStoreType(SrcInsts[0]);
303   Type *DstTy = getLoadStoreType(SinkInsts[0]);
304   if (isa<ScalableVectorType>(SrcTy) || isa<ScalableVectorType>(DstTy)) {
305     CanUseDiffCheck = false;
306     return;
307   }
308   const DataLayout &DL =
309       SinkAR->getLoop()->getHeader()->getModule()->getDataLayout();
310   unsigned AllocSize =
311       std::max(DL.getTypeAllocSize(SrcTy), DL.getTypeAllocSize(DstTy));
312 
313   // Only matching constant steps matching the AllocSize are supported at the
314   // moment. This simplifies the difference computation. Can be extended in the
315   // future.
316   auto *Step = dyn_cast<SCEVConstant>(SinkAR->getStepRecurrence(*SE));
317   if (!Step || Step != SrcAR->getStepRecurrence(*SE) ||
318       Step->getAPInt().abs() != AllocSize) {
319     CanUseDiffCheck = false;
320     return;
321   }
322 
323   IntegerType *IntTy =
324       IntegerType::get(Src->PointerValue->getContext(),
325                        DL.getPointerSizeInBits(CGI.AddressSpace));
326 
327   // When counting down, the dependence distance needs to be swapped.
328   if (Step->getValue()->isNegative())
329     std::swap(SinkAR, SrcAR);
330 
331   const SCEV *SinkStartInt = SE->getPtrToIntExpr(SinkAR->getStart(), IntTy);
332   const SCEV *SrcStartInt = SE->getPtrToIntExpr(SrcAR->getStart(), IntTy);
333   if (isa<SCEVCouldNotCompute>(SinkStartInt) ||
334       isa<SCEVCouldNotCompute>(SrcStartInt)) {
335     CanUseDiffCheck = false;
336     return;
337   }
338 
339   const Loop *InnerLoop = SrcAR->getLoop();
340   // If the start values for both Src and Sink also vary according to an outer
341   // loop, then it's probably better to avoid creating diff checks because
342   // they may not be hoisted. We should instead let llvm::addRuntimeChecks
343   // do the expanded full range overlap checks, which can be hoisted.
344   if (HoistRuntimeChecks && InnerLoop->getParentLoop() &&
345       isa<SCEVAddRecExpr>(SinkStartInt) && isa<SCEVAddRecExpr>(SrcStartInt)) {
346     auto *SrcStartAR = cast<SCEVAddRecExpr>(SrcStartInt);
347     auto *SinkStartAR = cast<SCEVAddRecExpr>(SinkStartInt);
348     const Loop *StartARLoop = SrcStartAR->getLoop();
349     if (StartARLoop == SinkStartAR->getLoop() &&
350         StartARLoop == InnerLoop->getParentLoop() &&
351         // If the diff check would already be loop invariant (due to the
352         // recurrences being the same), then we prefer to keep the diff checks
353         // because they are cheaper.
354         SrcStartAR->getStepRecurrence(*SE) !=
355             SinkStartAR->getStepRecurrence(*SE)) {
356       LLVM_DEBUG(dbgs() << "LAA: Not creating diff runtime check, since these "
357                            "cannot be hoisted out of the outer loop\n");
358       CanUseDiffCheck = false;
359       return;
360     }
361   }
362 
363   LLVM_DEBUG(dbgs() << "LAA: Creating diff runtime check for:\n"
364                     << "SrcStart: " << *SrcStartInt << '\n'
365                     << "SinkStartInt: " << *SinkStartInt << '\n');
366   DiffChecks.emplace_back(SrcStartInt, SinkStartInt, AllocSize,
367                           Src->NeedsFreeze || Sink->NeedsFreeze);
368 }
369 
370 SmallVector<RuntimePointerCheck, 4> RuntimePointerChecking::generateChecks() {
371   SmallVector<RuntimePointerCheck, 4> Checks;
372 
373   for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
374     for (unsigned J = I + 1; J < CheckingGroups.size(); ++J) {
375       const RuntimeCheckingPtrGroup &CGI = CheckingGroups[I];
376       const RuntimeCheckingPtrGroup &CGJ = CheckingGroups[J];
377 
378       if (needsChecking(CGI, CGJ)) {
379         tryToCreateDiffCheck(CGI, CGJ);
380         Checks.push_back(std::make_pair(&CGI, &CGJ));
381       }
382     }
383   }
384   return Checks;
385 }
386 
387 void RuntimePointerChecking::generateChecks(
388     MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
389   assert(Checks.empty() && "Checks is not empty");
390   groupChecks(DepCands, UseDependencies);
391   Checks = generateChecks();
392 }
393 
394 bool RuntimePointerChecking::needsChecking(
395     const RuntimeCheckingPtrGroup &M, const RuntimeCheckingPtrGroup &N) const {
396   for (unsigned I = 0, EI = M.Members.size(); EI != I; ++I)
397     for (unsigned J = 0, EJ = N.Members.size(); EJ != J; ++J)
398       if (needsChecking(M.Members[I], N.Members[J]))
399         return true;
400   return false;
401 }
402 
403 /// Compare \p I and \p J and return the minimum.
404 /// Return nullptr in case we couldn't find an answer.
405 static const SCEV *getMinFromExprs(const SCEV *I, const SCEV *J,
406                                    ScalarEvolution *SE) {
407   const SCEV *Diff = SE->getMinusSCEV(J, I);
408   const SCEVConstant *C = dyn_cast<const SCEVConstant>(Diff);
409 
410   if (!C)
411     return nullptr;
412   if (C->getValue()->isNegative())
413     return J;
414   return I;
415 }
416 
417 bool RuntimeCheckingPtrGroup::addPointer(unsigned Index,
418                                          RuntimePointerChecking &RtCheck) {
419   return addPointer(
420       Index, RtCheck.Pointers[Index].Start, RtCheck.Pointers[Index].End,
421       RtCheck.Pointers[Index].PointerValue->getType()->getPointerAddressSpace(),
422       RtCheck.Pointers[Index].NeedsFreeze, *RtCheck.SE);
423 }
424 
425 bool RuntimeCheckingPtrGroup::addPointer(unsigned Index, const SCEV *Start,
426                                          const SCEV *End, unsigned AS,
427                                          bool NeedsFreeze,
428                                          ScalarEvolution &SE) {
429   assert(AddressSpace == AS &&
430          "all pointers in a checking group must be in the same address space");
431 
432   // Compare the starts and ends with the known minimum and maximum
433   // of this set. We need to know how we compare against the min/max
434   // of the set in order to be able to emit memchecks.
435   const SCEV *Min0 = getMinFromExprs(Start, Low, &SE);
436   if (!Min0)
437     return false;
438 
439   const SCEV *Min1 = getMinFromExprs(End, High, &SE);
440   if (!Min1)
441     return false;
442 
443   // Update the low bound  expression if we've found a new min value.
444   if (Min0 == Start)
445     Low = Start;
446 
447   // Update the high bound expression if we've found a new max value.
448   if (Min1 != End)
449     High = End;
450 
451   Members.push_back(Index);
452   this->NeedsFreeze |= NeedsFreeze;
453   return true;
454 }
455 
456 void RuntimePointerChecking::groupChecks(
457     MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
458   // We build the groups from dependency candidates equivalence classes
459   // because:
460   //    - We know that pointers in the same equivalence class share
461   //      the same underlying object and therefore there is a chance
462   //      that we can compare pointers
463   //    - We wouldn't be able to merge two pointers for which we need
464   //      to emit a memcheck. The classes in DepCands are already
465   //      conveniently built such that no two pointers in the same
466   //      class need checking against each other.
467 
468   // We use the following (greedy) algorithm to construct the groups
469   // For every pointer in the equivalence class:
470   //   For each existing group:
471   //   - if the difference between this pointer and the min/max bounds
472   //     of the group is a constant, then make the pointer part of the
473   //     group and update the min/max bounds of that group as required.
474 
475   CheckingGroups.clear();
476 
477   // If we need to check two pointers to the same underlying object
478   // with a non-constant difference, we shouldn't perform any pointer
479   // grouping with those pointers. This is because we can easily get
480   // into cases where the resulting check would return false, even when
481   // the accesses are safe.
482   //
483   // The following example shows this:
484   // for (i = 0; i < 1000; ++i)
485   //   a[5000 + i * m] = a[i] + a[i + 9000]
486   //
487   // Here grouping gives a check of (5000, 5000 + 1000 * m) against
488   // (0, 10000) which is always false. However, if m is 1, there is no
489   // dependence. Not grouping the checks for a[i] and a[i + 9000] allows
490   // us to perform an accurate check in this case.
491   //
492   // The above case requires that we have an UnknownDependence between
493   // accesses to the same underlying object. This cannot happen unless
494   // FoundNonConstantDistanceDependence is set, and therefore UseDependencies
495   // is also false. In this case we will use the fallback path and create
496   // separate checking groups for all pointers.
497 
498   // If we don't have the dependency partitions, construct a new
499   // checking pointer group for each pointer. This is also required
500   // for correctness, because in this case we can have checking between
501   // pointers to the same underlying object.
502   if (!UseDependencies) {
503     for (unsigned I = 0; I < Pointers.size(); ++I)
504       CheckingGroups.push_back(RuntimeCheckingPtrGroup(I, *this));
505     return;
506   }
507 
508   unsigned TotalComparisons = 0;
509 
510   DenseMap<Value *, SmallVector<unsigned>> PositionMap;
511   for (unsigned Index = 0; Index < Pointers.size(); ++Index) {
512     auto Iter = PositionMap.insert({Pointers[Index].PointerValue, {}});
513     Iter.first->second.push_back(Index);
514   }
515 
516   // We need to keep track of what pointers we've already seen so we
517   // don't process them twice.
518   SmallSet<unsigned, 2> Seen;
519 
520   // Go through all equivalence classes, get the "pointer check groups"
521   // and add them to the overall solution. We use the order in which accesses
522   // appear in 'Pointers' to enforce determinism.
523   for (unsigned I = 0; I < Pointers.size(); ++I) {
524     // We've seen this pointer before, and therefore already processed
525     // its equivalence class.
526     if (Seen.count(I))
527       continue;
528 
529     MemoryDepChecker::MemAccessInfo Access(Pointers[I].PointerValue,
530                                            Pointers[I].IsWritePtr);
531 
532     SmallVector<RuntimeCheckingPtrGroup, 2> Groups;
533     auto LeaderI = DepCands.findValue(DepCands.getLeaderValue(Access));
534 
535     // Because DepCands is constructed by visiting accesses in the order in
536     // which they appear in alias sets (which is deterministic) and the
537     // iteration order within an equivalence class member is only dependent on
538     // the order in which unions and insertions are performed on the
539     // equivalence class, the iteration order is deterministic.
540     for (auto MI = DepCands.member_begin(LeaderI), ME = DepCands.member_end();
541          MI != ME; ++MI) {
542       auto PointerI = PositionMap.find(MI->getPointer());
543       assert(PointerI != PositionMap.end() &&
544              "pointer in equivalence class not found in PositionMap");
545       for (unsigned Pointer : PointerI->second) {
546         bool Merged = false;
547         // Mark this pointer as seen.
548         Seen.insert(Pointer);
549 
550         // Go through all the existing sets and see if we can find one
551         // which can include this pointer.
552         for (RuntimeCheckingPtrGroup &Group : Groups) {
553           // Don't perform more than a certain amount of comparisons.
554           // This should limit the cost of grouping the pointers to something
555           // reasonable.  If we do end up hitting this threshold, the algorithm
556           // will create separate groups for all remaining pointers.
557           if (TotalComparisons > MemoryCheckMergeThreshold)
558             break;
559 
560           TotalComparisons++;
561 
562           if (Group.addPointer(Pointer, *this)) {
563             Merged = true;
564             break;
565           }
566         }
567 
568         if (!Merged)
569           // We couldn't add this pointer to any existing set or the threshold
570           // for the number of comparisons has been reached. Create a new group
571           // to hold the current pointer.
572           Groups.push_back(RuntimeCheckingPtrGroup(Pointer, *this));
573       }
574     }
575 
576     // We've computed the grouped checks for this partition.
577     // Save the results and continue with the next one.
578     llvm::copy(Groups, std::back_inserter(CheckingGroups));
579   }
580 }
581 
582 bool RuntimePointerChecking::arePointersInSamePartition(
583     const SmallVectorImpl<int> &PtrToPartition, unsigned PtrIdx1,
584     unsigned PtrIdx2) {
585   return (PtrToPartition[PtrIdx1] != -1 &&
586           PtrToPartition[PtrIdx1] == PtrToPartition[PtrIdx2]);
587 }
588 
589 bool RuntimePointerChecking::needsChecking(unsigned I, unsigned J) const {
590   const PointerInfo &PointerI = Pointers[I];
591   const PointerInfo &PointerJ = Pointers[J];
592 
593   // No need to check if two readonly pointers intersect.
594   if (!PointerI.IsWritePtr && !PointerJ.IsWritePtr)
595     return false;
596 
597   // Only need to check pointers between two different dependency sets.
598   if (PointerI.DependencySetId == PointerJ.DependencySetId)
599     return false;
600 
601   // Only need to check pointers in the same alias set.
602   if (PointerI.AliasSetId != PointerJ.AliasSetId)
603     return false;
604 
605   return true;
606 }
607 
608 void RuntimePointerChecking::printChecks(
609     raw_ostream &OS, const SmallVectorImpl<RuntimePointerCheck> &Checks,
610     unsigned Depth) const {
611   unsigned N = 0;
612   for (const auto &Check : Checks) {
613     const auto &First = Check.first->Members, &Second = Check.second->Members;
614 
615     OS.indent(Depth) << "Check " << N++ << ":\n";
616 
617     OS.indent(Depth + 2) << "Comparing group (" << Check.first << "):\n";
618     for (unsigned K = 0; K < First.size(); ++K)
619       OS.indent(Depth + 2) << *Pointers[First[K]].PointerValue << "\n";
620 
621     OS.indent(Depth + 2) << "Against group (" << Check.second << "):\n";
622     for (unsigned K = 0; K < Second.size(); ++K)
623       OS.indent(Depth + 2) << *Pointers[Second[K]].PointerValue << "\n";
624   }
625 }
626 
627 void RuntimePointerChecking::print(raw_ostream &OS, unsigned Depth) const {
628 
629   OS.indent(Depth) << "Run-time memory checks:\n";
630   printChecks(OS, Checks, Depth);
631 
632   OS.indent(Depth) << "Grouped accesses:\n";
633   for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
634     const auto &CG = CheckingGroups[I];
635 
636     OS.indent(Depth + 2) << "Group " << &CG << ":\n";
637     OS.indent(Depth + 4) << "(Low: " << *CG.Low << " High: " << *CG.High
638                          << ")\n";
639     for (unsigned J = 0; J < CG.Members.size(); ++J) {
640       OS.indent(Depth + 6) << "Member: " << *Pointers[CG.Members[J]].Expr
641                            << "\n";
642     }
643   }
644 }
645 
646 namespace {
647 
648 /// Analyses memory accesses in a loop.
649 ///
650 /// Checks whether run time pointer checks are needed and builds sets for data
651 /// dependence checking.
652 class AccessAnalysis {
653 public:
654   /// Read or write access location.
655   typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
656   typedef SmallVector<MemAccessInfo, 8> MemAccessInfoList;
657 
658   AccessAnalysis(Loop *TheLoop, AAResults *AA, LoopInfo *LI,
659                  MemoryDepChecker::DepCandidates &DA,
660                  PredicatedScalarEvolution &PSE)
661       : TheLoop(TheLoop), BAA(*AA), AST(BAA), LI(LI), DepCands(DA), PSE(PSE) {
662     // We're analyzing dependences across loop iterations.
663     BAA.enableCrossIterationMode();
664   }
665 
666   /// Register a load  and whether it is only read from.
667   void addLoad(MemoryLocation &Loc, Type *AccessTy, bool IsReadOnly) {
668     Value *Ptr = const_cast<Value*>(Loc.Ptr);
669     AST.add(Loc.getWithNewSize(LocationSize::beforeOrAfterPointer()));
670     Accesses[MemAccessInfo(Ptr, false)].insert(AccessTy);
671     if (IsReadOnly)
672       ReadOnlyPtr.insert(Ptr);
673   }
674 
675   /// Register a store.
676   void addStore(MemoryLocation &Loc, Type *AccessTy) {
677     Value *Ptr = const_cast<Value*>(Loc.Ptr);
678     AST.add(Loc.getWithNewSize(LocationSize::beforeOrAfterPointer()));
679     Accesses[MemAccessInfo(Ptr, true)].insert(AccessTy);
680   }
681 
682   /// Check if we can emit a run-time no-alias check for \p Access.
683   ///
684   /// Returns true if we can emit a run-time no alias check for \p Access.
685   /// If we can check this access, this also adds it to a dependence set and
686   /// adds a run-time to check for it to \p RtCheck. If \p Assume is true,
687   /// we will attempt to use additional run-time checks in order to get
688   /// the bounds of the pointer.
689   bool createCheckForAccess(RuntimePointerChecking &RtCheck,
690                             MemAccessInfo Access, Type *AccessTy,
691                             const DenseMap<Value *, const SCEV *> &Strides,
692                             DenseMap<Value *, unsigned> &DepSetId,
693                             Loop *TheLoop, unsigned &RunningDepId,
694                             unsigned ASId, bool ShouldCheckStride, bool Assume);
695 
696   /// Check whether we can check the pointers at runtime for
697   /// non-intersection.
698   ///
699   /// Returns true if we need no check or if we do and we can generate them
700   /// (i.e. the pointers have computable bounds).
701   bool canCheckPtrAtRT(RuntimePointerChecking &RtCheck, ScalarEvolution *SE,
702                        Loop *TheLoop, const DenseMap<Value *, const SCEV *> &Strides,
703                        Value *&UncomputablePtr, bool ShouldCheckWrap = false);
704 
705   /// Goes over all memory accesses, checks whether a RT check is needed
706   /// and builds sets of dependent accesses.
707   void buildDependenceSets() {
708     processMemAccesses();
709   }
710 
711   /// Initial processing of memory accesses determined that we need to
712   /// perform dependency checking.
713   ///
714   /// Note that this can later be cleared if we retry memcheck analysis without
715   /// dependency checking (i.e. FoundNonConstantDistanceDependence).
716   bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
717 
718   /// We decided that no dependence analysis would be used.  Reset the state.
719   void resetDepChecks(MemoryDepChecker &DepChecker) {
720     CheckDeps.clear();
721     DepChecker.clearDependences();
722   }
723 
724   MemAccessInfoList &getDependenciesToCheck() { return CheckDeps; }
725 
726   const DenseMap<Value *, SmallVector<const Value *, 16>> &
727   getUnderlyingObjects() {
728     return UnderlyingObjects;
729   }
730 
731 private:
732   typedef MapVector<MemAccessInfo, SmallSetVector<Type *, 1>> PtrAccessMap;
733 
734   /// Go over all memory access and check whether runtime pointer checks
735   /// are needed and build sets of dependency check candidates.
736   void processMemAccesses();
737 
738   /// Map of all accesses. Values are the types used to access memory pointed to
739   /// by the pointer.
740   PtrAccessMap Accesses;
741 
742   /// The loop being checked.
743   const Loop *TheLoop;
744 
745   /// List of accesses that need a further dependence check.
746   MemAccessInfoList CheckDeps;
747 
748   /// Set of pointers that are read only.
749   SmallPtrSet<Value*, 16> ReadOnlyPtr;
750 
751   /// Batched alias analysis results.
752   BatchAAResults BAA;
753 
754   /// An alias set tracker to partition the access set by underlying object and
755   //intrinsic property (such as TBAA metadata).
756   AliasSetTracker AST;
757 
758   LoopInfo *LI;
759 
760   /// Sets of potentially dependent accesses - members of one set share an
761   /// underlying pointer. The set "CheckDeps" identfies which sets really need a
762   /// dependence check.
763   MemoryDepChecker::DepCandidates &DepCands;
764 
765   /// Initial processing of memory accesses determined that we may need
766   /// to add memchecks.  Perform the analysis to determine the necessary checks.
767   ///
768   /// Note that, this is different from isDependencyCheckNeeded.  When we retry
769   /// memcheck analysis without dependency checking
770   /// (i.e. FoundNonConstantDistanceDependence), isDependencyCheckNeeded is
771   /// cleared while this remains set if we have potentially dependent accesses.
772   bool IsRTCheckAnalysisNeeded = false;
773 
774   /// The SCEV predicate containing all the SCEV-related assumptions.
775   PredicatedScalarEvolution &PSE;
776 
777   DenseMap<Value *, SmallVector<const Value *, 16>> UnderlyingObjects;
778 };
779 
780 } // end anonymous namespace
781 
782 /// Check whether a pointer can participate in a runtime bounds check.
783 /// If \p Assume, try harder to prove that we can compute the bounds of \p Ptr
784 /// by adding run-time checks (overflow checks) if necessary.
785 static bool hasComputableBounds(PredicatedScalarEvolution &PSE, Value *Ptr,
786                                 const SCEV *PtrScev, Loop *L, bool Assume) {
787   // The bounds for loop-invariant pointer is trivial.
788   if (PSE.getSE()->isLoopInvariant(PtrScev, L))
789     return true;
790 
791   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
792 
793   if (!AR && Assume)
794     AR = PSE.getAsAddRec(Ptr);
795 
796   if (!AR)
797     return false;
798 
799   return AR->isAffine();
800 }
801 
802 /// Check whether a pointer address cannot wrap.
803 static bool isNoWrap(PredicatedScalarEvolution &PSE,
804                      const DenseMap<Value *, const SCEV *> &Strides, Value *Ptr, Type *AccessTy,
805                      Loop *L) {
806   const SCEV *PtrScev = PSE.getSCEV(Ptr);
807   if (PSE.getSE()->isLoopInvariant(PtrScev, L))
808     return true;
809 
810   int64_t Stride = getPtrStride(PSE, AccessTy, Ptr, L, Strides).value_or(0);
811   if (Stride == 1 || PSE.hasNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW))
812     return true;
813 
814   return false;
815 }
816 
817 static void visitPointers(Value *StartPtr, const Loop &InnermostLoop,
818                           function_ref<void(Value *)> AddPointer) {
819   SmallPtrSet<Value *, 8> Visited;
820   SmallVector<Value *> WorkList;
821   WorkList.push_back(StartPtr);
822 
823   while (!WorkList.empty()) {
824     Value *Ptr = WorkList.pop_back_val();
825     if (!Visited.insert(Ptr).second)
826       continue;
827     auto *PN = dyn_cast<PHINode>(Ptr);
828     // SCEV does not look through non-header PHIs inside the loop. Such phis
829     // can be analyzed by adding separate accesses for each incoming pointer
830     // value.
831     if (PN && InnermostLoop.contains(PN->getParent()) &&
832         PN->getParent() != InnermostLoop.getHeader()) {
833       for (const Use &Inc : PN->incoming_values())
834         WorkList.push_back(Inc);
835     } else
836       AddPointer(Ptr);
837   }
838 }
839 
840 // Walk back through the IR for a pointer, looking for a select like the
841 // following:
842 //
843 //  %offset = select i1 %cmp, i64 %a, i64 %b
844 //  %addr = getelementptr double, double* %base, i64 %offset
845 //  %ld = load double, double* %addr, align 8
846 //
847 // We won't be able to form a single SCEVAddRecExpr from this since the
848 // address for each loop iteration depends on %cmp. We could potentially
849 // produce multiple valid SCEVAddRecExprs, though, and check all of them for
850 // memory safety/aliasing if needed.
851 //
852 // If we encounter some IR we don't yet handle, or something obviously fine
853 // like a constant, then we just add the SCEV for that term to the list passed
854 // in by the caller. If we have a node that may potentially yield a valid
855 // SCEVAddRecExpr then we decompose it into parts and build the SCEV terms
856 // ourselves before adding to the list.
857 static void findForkedSCEVs(
858     ScalarEvolution *SE, const Loop *L, Value *Ptr,
859     SmallVectorImpl<PointerIntPair<const SCEV *, 1, bool>> &ScevList,
860     unsigned Depth) {
861   // If our Value is a SCEVAddRecExpr, loop invariant, not an instruction, or
862   // we've exceeded our limit on recursion, just return whatever we have
863   // regardless of whether it can be used for a forked pointer or not, along
864   // with an indication of whether it might be a poison or undef value.
865   const SCEV *Scev = SE->getSCEV(Ptr);
866   if (isa<SCEVAddRecExpr>(Scev) || L->isLoopInvariant(Ptr) ||
867       !isa<Instruction>(Ptr) || Depth == 0) {
868     ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr));
869     return;
870   }
871 
872   Depth--;
873 
874   auto UndefPoisonCheck = [](PointerIntPair<const SCEV *, 1, bool> S) {
875     return get<1>(S);
876   };
877 
878   auto GetBinOpExpr = [&SE](unsigned Opcode, const SCEV *L, const SCEV *R) {
879     switch (Opcode) {
880     case Instruction::Add:
881       return SE->getAddExpr(L, R);
882     case Instruction::Sub:
883       return SE->getMinusSCEV(L, R);
884     default:
885       llvm_unreachable("Unexpected binary operator when walking ForkedPtrs");
886     }
887   };
888 
889   Instruction *I = cast<Instruction>(Ptr);
890   unsigned Opcode = I->getOpcode();
891   switch (Opcode) {
892   case Instruction::GetElementPtr: {
893     GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
894     Type *SourceTy = GEP->getSourceElementType();
895     // We only handle base + single offset GEPs here for now.
896     // Not dealing with preexisting gathers yet, so no vectors.
897     if (I->getNumOperands() != 2 || SourceTy->isVectorTy()) {
898       ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(GEP));
899       break;
900     }
901     SmallVector<PointerIntPair<const SCEV *, 1, bool>, 2> BaseScevs;
902     SmallVector<PointerIntPair<const SCEV *, 1, bool>, 2> OffsetScevs;
903     findForkedSCEVs(SE, L, I->getOperand(0), BaseScevs, Depth);
904     findForkedSCEVs(SE, L, I->getOperand(1), OffsetScevs, Depth);
905 
906     // See if we need to freeze our fork...
907     bool NeedsFreeze = any_of(BaseScevs, UndefPoisonCheck) ||
908                        any_of(OffsetScevs, UndefPoisonCheck);
909 
910     // Check that we only have a single fork, on either the base or the offset.
911     // Copy the SCEV across for the one without a fork in order to generate
912     // the full SCEV for both sides of the GEP.
913     if (OffsetScevs.size() == 2 && BaseScevs.size() == 1)
914       BaseScevs.push_back(BaseScevs[0]);
915     else if (BaseScevs.size() == 2 && OffsetScevs.size() == 1)
916       OffsetScevs.push_back(OffsetScevs[0]);
917     else {
918       ScevList.emplace_back(Scev, NeedsFreeze);
919       break;
920     }
921 
922     // Find the pointer type we need to extend to.
923     Type *IntPtrTy = SE->getEffectiveSCEVType(
924         SE->getSCEV(GEP->getPointerOperand())->getType());
925 
926     // Find the size of the type being pointed to. We only have a single
927     // index term (guarded above) so we don't need to index into arrays or
928     // structures, just get the size of the scalar value.
929     const SCEV *Size = SE->getSizeOfExpr(IntPtrTy, SourceTy);
930 
931     // Scale up the offsets by the size of the type, then add to the bases.
932     const SCEV *Scaled1 = SE->getMulExpr(
933         Size, SE->getTruncateOrSignExtend(get<0>(OffsetScevs[0]), IntPtrTy));
934     const SCEV *Scaled2 = SE->getMulExpr(
935         Size, SE->getTruncateOrSignExtend(get<0>(OffsetScevs[1]), IntPtrTy));
936     ScevList.emplace_back(SE->getAddExpr(get<0>(BaseScevs[0]), Scaled1),
937                           NeedsFreeze);
938     ScevList.emplace_back(SE->getAddExpr(get<0>(BaseScevs[1]), Scaled2),
939                           NeedsFreeze);
940     break;
941   }
942   case Instruction::Select: {
943     SmallVector<PointerIntPair<const SCEV *, 1, bool>, 2> ChildScevs;
944     // A select means we've found a forked pointer, but we currently only
945     // support a single select per pointer so if there's another behind this
946     // then we just bail out and return the generic SCEV.
947     findForkedSCEVs(SE, L, I->getOperand(1), ChildScevs, Depth);
948     findForkedSCEVs(SE, L, I->getOperand(2), ChildScevs, Depth);
949     if (ChildScevs.size() == 2) {
950       ScevList.push_back(ChildScevs[0]);
951       ScevList.push_back(ChildScevs[1]);
952     } else
953       ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr));
954     break;
955   }
956   case Instruction::PHI: {
957     SmallVector<PointerIntPair<const SCEV *, 1, bool>, 2> ChildScevs;
958     // A phi means we've found a forked pointer, but we currently only
959     // support a single phi per pointer so if there's another behind this
960     // then we just bail out and return the generic SCEV.
961     if (I->getNumOperands() == 2) {
962       findForkedSCEVs(SE, L, I->getOperand(0), ChildScevs, Depth);
963       findForkedSCEVs(SE, L, I->getOperand(1), ChildScevs, Depth);
964     }
965     if (ChildScevs.size() == 2) {
966       ScevList.push_back(ChildScevs[0]);
967       ScevList.push_back(ChildScevs[1]);
968     } else
969       ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr));
970     break;
971   }
972   case Instruction::Add:
973   case Instruction::Sub: {
974     SmallVector<PointerIntPair<const SCEV *, 1, bool>> LScevs;
975     SmallVector<PointerIntPair<const SCEV *, 1, bool>> RScevs;
976     findForkedSCEVs(SE, L, I->getOperand(0), LScevs, Depth);
977     findForkedSCEVs(SE, L, I->getOperand(1), RScevs, Depth);
978 
979     // See if we need to freeze our fork...
980     bool NeedsFreeze =
981         any_of(LScevs, UndefPoisonCheck) || any_of(RScevs, UndefPoisonCheck);
982 
983     // Check that we only have a single fork, on either the left or right side.
984     // Copy the SCEV across for the one without a fork in order to generate
985     // the full SCEV for both sides of the BinOp.
986     if (LScevs.size() == 2 && RScevs.size() == 1)
987       RScevs.push_back(RScevs[0]);
988     else if (RScevs.size() == 2 && LScevs.size() == 1)
989       LScevs.push_back(LScevs[0]);
990     else {
991       ScevList.emplace_back(Scev, NeedsFreeze);
992       break;
993     }
994 
995     ScevList.emplace_back(
996         GetBinOpExpr(Opcode, get<0>(LScevs[0]), get<0>(RScevs[0])),
997         NeedsFreeze);
998     ScevList.emplace_back(
999         GetBinOpExpr(Opcode, get<0>(LScevs[1]), get<0>(RScevs[1])),
1000         NeedsFreeze);
1001     break;
1002   }
1003   default:
1004     // Just return the current SCEV if we haven't handled the instruction yet.
1005     LLVM_DEBUG(dbgs() << "ForkedPtr unhandled instruction: " << *I << "\n");
1006     ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr));
1007     break;
1008   }
1009 }
1010 
1011 static SmallVector<PointerIntPair<const SCEV *, 1, bool>>
1012 findForkedPointer(PredicatedScalarEvolution &PSE,
1013                   const DenseMap<Value *, const SCEV *> &StridesMap, Value *Ptr,
1014                   const Loop *L) {
1015   ScalarEvolution *SE = PSE.getSE();
1016   assert(SE->isSCEVable(Ptr->getType()) && "Value is not SCEVable!");
1017   SmallVector<PointerIntPair<const SCEV *, 1, bool>> Scevs;
1018   findForkedSCEVs(SE, L, Ptr, Scevs, MaxForkedSCEVDepth);
1019 
1020   // For now, we will only accept a forked pointer with two possible SCEVs
1021   // that are either SCEVAddRecExprs or loop invariant.
1022   if (Scevs.size() == 2 &&
1023       (isa<SCEVAddRecExpr>(get<0>(Scevs[0])) ||
1024        SE->isLoopInvariant(get<0>(Scevs[0]), L)) &&
1025       (isa<SCEVAddRecExpr>(get<0>(Scevs[1])) ||
1026        SE->isLoopInvariant(get<0>(Scevs[1]), L))) {
1027     LLVM_DEBUG(dbgs() << "LAA: Found forked pointer: " << *Ptr << "\n");
1028     LLVM_DEBUG(dbgs() << "\t(1) " << *get<0>(Scevs[0]) << "\n");
1029     LLVM_DEBUG(dbgs() << "\t(2) " << *get<0>(Scevs[1]) << "\n");
1030     return Scevs;
1031   }
1032 
1033   return {{replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr), false}};
1034 }
1035 
1036 bool AccessAnalysis::createCheckForAccess(RuntimePointerChecking &RtCheck,
1037                                           MemAccessInfo Access, Type *AccessTy,
1038                                           const DenseMap<Value *, const SCEV *> &StridesMap,
1039                                           DenseMap<Value *, unsigned> &DepSetId,
1040                                           Loop *TheLoop, unsigned &RunningDepId,
1041                                           unsigned ASId, bool ShouldCheckWrap,
1042                                           bool Assume) {
1043   Value *Ptr = Access.getPointer();
1044 
1045   SmallVector<PointerIntPair<const SCEV *, 1, bool>> TranslatedPtrs =
1046       findForkedPointer(PSE, StridesMap, Ptr, TheLoop);
1047 
1048   for (auto &P : TranslatedPtrs) {
1049     const SCEV *PtrExpr = get<0>(P);
1050     if (!hasComputableBounds(PSE, Ptr, PtrExpr, TheLoop, Assume))
1051       return false;
1052 
1053     // When we run after a failing dependency check we have to make sure
1054     // we don't have wrapping pointers.
1055     if (ShouldCheckWrap) {
1056       // Skip wrap checking when translating pointers.
1057       if (TranslatedPtrs.size() > 1)
1058         return false;
1059 
1060       if (!isNoWrap(PSE, StridesMap, Ptr, AccessTy, TheLoop)) {
1061         auto *Expr = PSE.getSCEV(Ptr);
1062         if (!Assume || !isa<SCEVAddRecExpr>(Expr))
1063           return false;
1064         PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
1065       }
1066     }
1067     // If there's only one option for Ptr, look it up after bounds and wrap
1068     // checking, because assumptions might have been added to PSE.
1069     if (TranslatedPtrs.size() == 1)
1070       TranslatedPtrs[0] = {replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr),
1071                            false};
1072   }
1073 
1074   for (auto [PtrExpr, NeedsFreeze] : TranslatedPtrs) {
1075     // The id of the dependence set.
1076     unsigned DepId;
1077 
1078     if (isDependencyCheckNeeded()) {
1079       Value *Leader = DepCands.getLeaderValue(Access).getPointer();
1080       unsigned &LeaderId = DepSetId[Leader];
1081       if (!LeaderId)
1082         LeaderId = RunningDepId++;
1083       DepId = LeaderId;
1084     } else
1085       // Each access has its own dependence set.
1086       DepId = RunningDepId++;
1087 
1088     bool IsWrite = Access.getInt();
1089     RtCheck.insert(TheLoop, Ptr, PtrExpr, AccessTy, IsWrite, DepId, ASId, PSE,
1090                    NeedsFreeze);
1091     LLVM_DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
1092   }
1093 
1094   return true;
1095 }
1096 
1097 bool AccessAnalysis::canCheckPtrAtRT(RuntimePointerChecking &RtCheck,
1098                                      ScalarEvolution *SE, Loop *TheLoop,
1099                                      const DenseMap<Value *, const SCEV *> &StridesMap,
1100                                      Value *&UncomputablePtr, bool ShouldCheckWrap) {
1101   // Find pointers with computable bounds. We are going to use this information
1102   // to place a runtime bound check.
1103   bool CanDoRT = true;
1104 
1105   bool MayNeedRTCheck = false;
1106   if (!IsRTCheckAnalysisNeeded) return true;
1107 
1108   bool IsDepCheckNeeded = isDependencyCheckNeeded();
1109 
1110   // We assign a consecutive id to access from different alias sets.
1111   // Accesses between different groups doesn't need to be checked.
1112   unsigned ASId = 0;
1113   for (auto &AS : AST) {
1114     int NumReadPtrChecks = 0;
1115     int NumWritePtrChecks = 0;
1116     bool CanDoAliasSetRT = true;
1117     ++ASId;
1118     auto ASPointers = AS.getPointers();
1119 
1120     // We assign consecutive id to access from different dependence sets.
1121     // Accesses within the same set don't need a runtime check.
1122     unsigned RunningDepId = 1;
1123     DenseMap<Value *, unsigned> DepSetId;
1124 
1125     SmallVector<std::pair<MemAccessInfo, Type *>, 4> Retries;
1126 
1127     // First, count how many write and read accesses are in the alias set. Also
1128     // collect MemAccessInfos for later.
1129     SmallVector<MemAccessInfo, 4> AccessInfos;
1130     for (const Value *Ptr_ : ASPointers) {
1131       Value *Ptr = const_cast<Value *>(Ptr_);
1132       bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
1133       if (IsWrite)
1134         ++NumWritePtrChecks;
1135       else
1136         ++NumReadPtrChecks;
1137       AccessInfos.emplace_back(Ptr, IsWrite);
1138     }
1139 
1140     // We do not need runtime checks for this alias set, if there are no writes
1141     // or a single write and no reads.
1142     if (NumWritePtrChecks == 0 ||
1143         (NumWritePtrChecks == 1 && NumReadPtrChecks == 0)) {
1144       assert((ASPointers.size() <= 1 ||
1145               all_of(ASPointers,
1146                      [this](const Value *Ptr) {
1147                        MemAccessInfo AccessWrite(const_cast<Value *>(Ptr),
1148                                                  true);
1149                        return DepCands.findValue(AccessWrite) == DepCands.end();
1150                      })) &&
1151              "Can only skip updating CanDoRT below, if all entries in AS "
1152              "are reads or there is at most 1 entry");
1153       continue;
1154     }
1155 
1156     for (auto &Access : AccessInfos) {
1157       for (const auto &AccessTy : Accesses[Access]) {
1158         if (!createCheckForAccess(RtCheck, Access, AccessTy, StridesMap,
1159                                   DepSetId, TheLoop, RunningDepId, ASId,
1160                                   ShouldCheckWrap, false)) {
1161           LLVM_DEBUG(dbgs() << "LAA: Can't find bounds for ptr:"
1162                             << *Access.getPointer() << '\n');
1163           Retries.push_back({Access, AccessTy});
1164           CanDoAliasSetRT = false;
1165         }
1166       }
1167     }
1168 
1169     // Note that this function computes CanDoRT and MayNeedRTCheck
1170     // independently. For example CanDoRT=false, MayNeedRTCheck=false means that
1171     // we have a pointer for which we couldn't find the bounds but we don't
1172     // actually need to emit any checks so it does not matter.
1173     //
1174     // We need runtime checks for this alias set, if there are at least 2
1175     // dependence sets (in which case RunningDepId > 2) or if we need to re-try
1176     // any bound checks (because in that case the number of dependence sets is
1177     // incomplete).
1178     bool NeedsAliasSetRTCheck = RunningDepId > 2 || !Retries.empty();
1179 
1180     // We need to perform run-time alias checks, but some pointers had bounds
1181     // that couldn't be checked.
1182     if (NeedsAliasSetRTCheck && !CanDoAliasSetRT) {
1183       // Reset the CanDoSetRt flag and retry all accesses that have failed.
1184       // We know that we need these checks, so we can now be more aggressive
1185       // and add further checks if required (overflow checks).
1186       CanDoAliasSetRT = true;
1187       for (auto Retry : Retries) {
1188         MemAccessInfo Access = Retry.first;
1189         Type *AccessTy = Retry.second;
1190         if (!createCheckForAccess(RtCheck, Access, AccessTy, StridesMap,
1191                                   DepSetId, TheLoop, RunningDepId, ASId,
1192                                   ShouldCheckWrap, /*Assume=*/true)) {
1193           CanDoAliasSetRT = false;
1194           UncomputablePtr = Access.getPointer();
1195           break;
1196         }
1197       }
1198     }
1199 
1200     CanDoRT &= CanDoAliasSetRT;
1201     MayNeedRTCheck |= NeedsAliasSetRTCheck;
1202     ++ASId;
1203   }
1204 
1205   // If the pointers that we would use for the bounds comparison have different
1206   // address spaces, assume the values aren't directly comparable, so we can't
1207   // use them for the runtime check. We also have to assume they could
1208   // overlap. In the future there should be metadata for whether address spaces
1209   // are disjoint.
1210   unsigned NumPointers = RtCheck.Pointers.size();
1211   for (unsigned i = 0; i < NumPointers; ++i) {
1212     for (unsigned j = i + 1; j < NumPointers; ++j) {
1213       // Only need to check pointers between two different dependency sets.
1214       if (RtCheck.Pointers[i].DependencySetId ==
1215           RtCheck.Pointers[j].DependencySetId)
1216        continue;
1217       // Only need to check pointers in the same alias set.
1218       if (RtCheck.Pointers[i].AliasSetId != RtCheck.Pointers[j].AliasSetId)
1219         continue;
1220 
1221       Value *PtrI = RtCheck.Pointers[i].PointerValue;
1222       Value *PtrJ = RtCheck.Pointers[j].PointerValue;
1223 
1224       unsigned ASi = PtrI->getType()->getPointerAddressSpace();
1225       unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
1226       if (ASi != ASj) {
1227         LLVM_DEBUG(
1228             dbgs() << "LAA: Runtime check would require comparison between"
1229                       " different address spaces\n");
1230         return false;
1231       }
1232     }
1233   }
1234 
1235   if (MayNeedRTCheck && CanDoRT)
1236     RtCheck.generateChecks(DepCands, IsDepCheckNeeded);
1237 
1238   LLVM_DEBUG(dbgs() << "LAA: We need to do " << RtCheck.getNumberOfChecks()
1239                     << " pointer comparisons.\n");
1240 
1241   // If we can do run-time checks, but there are no checks, no runtime checks
1242   // are needed. This can happen when all pointers point to the same underlying
1243   // object for example.
1244   RtCheck.Need = CanDoRT ? RtCheck.getNumberOfChecks() != 0 : MayNeedRTCheck;
1245 
1246   bool CanDoRTIfNeeded = !RtCheck.Need || CanDoRT;
1247   if (!CanDoRTIfNeeded)
1248     RtCheck.reset();
1249   return CanDoRTIfNeeded;
1250 }
1251 
1252 void AccessAnalysis::processMemAccesses() {
1253   // We process the set twice: first we process read-write pointers, last we
1254   // process read-only pointers. This allows us to skip dependence tests for
1255   // read-only pointers.
1256 
1257   LLVM_DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
1258   LLVM_DEBUG(dbgs() << "  AST: "; AST.dump());
1259   LLVM_DEBUG(dbgs() << "LAA:   Accesses(" << Accesses.size() << "):\n");
1260   LLVM_DEBUG({
1261     for (auto A : Accesses)
1262       dbgs() << "\t" << *A.first.getPointer() << " ("
1263              << (A.first.getInt()
1264                      ? "write"
1265                      : (ReadOnlyPtr.count(A.first.getPointer()) ? "read-only"
1266                                                                 : "read"))
1267              << ")\n";
1268   });
1269 
1270   // The AliasSetTracker has nicely partitioned our pointers by metadata
1271   // compatibility and potential for underlying-object overlap. As a result, we
1272   // only need to check for potential pointer dependencies within each alias
1273   // set.
1274   for (const auto &AS : AST) {
1275     // Note that both the alias-set tracker and the alias sets themselves used
1276     // ordered collections internally and so the iteration order here is
1277     // deterministic.
1278     auto ASPointers = AS.getPointers();
1279 
1280     bool SetHasWrite = false;
1281 
1282     // Map of pointers to last access encountered.
1283     typedef DenseMap<const Value*, MemAccessInfo> UnderlyingObjToAccessMap;
1284     UnderlyingObjToAccessMap ObjToLastAccess;
1285 
1286     // Set of access to check after all writes have been processed.
1287     PtrAccessMap DeferredAccesses;
1288 
1289     // Iterate over each alias set twice, once to process read/write pointers,
1290     // and then to process read-only pointers.
1291     for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
1292       bool UseDeferred = SetIteration > 0;
1293       PtrAccessMap &S = UseDeferred ? DeferredAccesses : Accesses;
1294 
1295       for (const Value *Ptr_ : ASPointers) {
1296         Value *Ptr = const_cast<Value *>(Ptr_);
1297 
1298         // For a single memory access in AliasSetTracker, Accesses may contain
1299         // both read and write, and they both need to be handled for CheckDeps.
1300         for (const auto &AC : S) {
1301           if (AC.first.getPointer() != Ptr)
1302             continue;
1303 
1304           bool IsWrite = AC.first.getInt();
1305 
1306           // If we're using the deferred access set, then it contains only
1307           // reads.
1308           bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
1309           if (UseDeferred && !IsReadOnlyPtr)
1310             continue;
1311           // Otherwise, the pointer must be in the PtrAccessSet, either as a
1312           // read or a write.
1313           assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
1314                   S.count(MemAccessInfo(Ptr, false))) &&
1315                  "Alias-set pointer not in the access set?");
1316 
1317           MemAccessInfo Access(Ptr, IsWrite);
1318           DepCands.insert(Access);
1319 
1320           // Memorize read-only pointers for later processing and skip them in
1321           // the first round (they need to be checked after we have seen all
1322           // write pointers). Note: we also mark pointer that are not
1323           // consecutive as "read-only" pointers (so that we check
1324           // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
1325           if (!UseDeferred && IsReadOnlyPtr) {
1326             // We only use the pointer keys, the types vector values don't
1327             // matter.
1328             DeferredAccesses.insert({Access, {}});
1329             continue;
1330           }
1331 
1332           // If this is a write - check other reads and writes for conflicts. If
1333           // this is a read only check other writes for conflicts (but only if
1334           // there is no other write to the ptr - this is an optimization to
1335           // catch "a[i] = a[i] + " without having to do a dependence check).
1336           if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
1337             CheckDeps.push_back(Access);
1338             IsRTCheckAnalysisNeeded = true;
1339           }
1340 
1341           if (IsWrite)
1342             SetHasWrite = true;
1343 
1344           // Create sets of pointers connected by a shared alias set and
1345           // underlying object.
1346           typedef SmallVector<const Value *, 16> ValueVector;
1347           ValueVector TempObjects;
1348 
1349           UnderlyingObjects[Ptr] = {};
1350           SmallVector<const Value *, 16> &UOs = UnderlyingObjects[Ptr];
1351           ::getUnderlyingObjects(Ptr, UOs, LI);
1352           LLVM_DEBUG(dbgs()
1353                      << "Underlying objects for pointer " << *Ptr << "\n");
1354           for (const Value *UnderlyingObj : UOs) {
1355             // nullptr never alias, don't join sets for pointer that have "null"
1356             // in their UnderlyingObjects list.
1357             if (isa<ConstantPointerNull>(UnderlyingObj) &&
1358                 !NullPointerIsDefined(
1359                     TheLoop->getHeader()->getParent(),
1360                     UnderlyingObj->getType()->getPointerAddressSpace()))
1361               continue;
1362 
1363             UnderlyingObjToAccessMap::iterator Prev =
1364                 ObjToLastAccess.find(UnderlyingObj);
1365             if (Prev != ObjToLastAccess.end())
1366               DepCands.unionSets(Access, Prev->second);
1367 
1368             ObjToLastAccess[UnderlyingObj] = Access;
1369             LLVM_DEBUG(dbgs() << "  " << *UnderlyingObj << "\n");
1370           }
1371         }
1372       }
1373     }
1374   }
1375 }
1376 
1377 /// Return true if an AddRec pointer \p Ptr is unsigned non-wrapping,
1378 /// i.e. monotonically increasing/decreasing.
1379 static bool isNoWrapAddRec(Value *Ptr, const SCEVAddRecExpr *AR,
1380                            PredicatedScalarEvolution &PSE, const Loop *L) {
1381 
1382   // FIXME: This should probably only return true for NUW.
1383   if (AR->getNoWrapFlags(SCEV::NoWrapMask))
1384     return true;
1385 
1386   if (PSE.hasNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW))
1387     return true;
1388 
1389   // Scalar evolution does not propagate the non-wrapping flags to values that
1390   // are derived from a non-wrapping induction variable because non-wrapping
1391   // could be flow-sensitive.
1392   //
1393   // Look through the potentially overflowing instruction to try to prove
1394   // non-wrapping for the *specific* value of Ptr.
1395 
1396   // The arithmetic implied by an inbounds GEP can't overflow.
1397   auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
1398   if (!GEP || !GEP->isInBounds())
1399     return false;
1400 
1401   // Make sure there is only one non-const index and analyze that.
1402   Value *NonConstIndex = nullptr;
1403   for (Value *Index : GEP->indices())
1404     if (!isa<ConstantInt>(Index)) {
1405       if (NonConstIndex)
1406         return false;
1407       NonConstIndex = Index;
1408     }
1409   if (!NonConstIndex)
1410     // The recurrence is on the pointer, ignore for now.
1411     return false;
1412 
1413   // The index in GEP is signed.  It is non-wrapping if it's derived from a NSW
1414   // AddRec using a NSW operation.
1415   if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(NonConstIndex))
1416     if (OBO->hasNoSignedWrap() &&
1417         // Assume constant for other the operand so that the AddRec can be
1418         // easily found.
1419         isa<ConstantInt>(OBO->getOperand(1))) {
1420       auto *OpScev = PSE.getSCEV(OBO->getOperand(0));
1421 
1422       if (auto *OpAR = dyn_cast<SCEVAddRecExpr>(OpScev))
1423         return OpAR->getLoop() == L && OpAR->getNoWrapFlags(SCEV::FlagNSW);
1424     }
1425 
1426   return false;
1427 }
1428 
1429 /// Check whether the access through \p Ptr has a constant stride.
1430 std::optional<int64_t> llvm::getPtrStride(PredicatedScalarEvolution &PSE,
1431                                           Type *AccessTy, Value *Ptr,
1432                                           const Loop *Lp,
1433                                           const DenseMap<Value *, const SCEV *> &StridesMap,
1434                                           bool Assume, bool ShouldCheckWrap) {
1435   Type *Ty = Ptr->getType();
1436   assert(Ty->isPointerTy() && "Unexpected non-ptr");
1437 
1438   if (isa<ScalableVectorType>(AccessTy)) {
1439     LLVM_DEBUG(dbgs() << "LAA: Bad stride - Scalable object: " << *AccessTy
1440                       << "\n");
1441     return std::nullopt;
1442   }
1443 
1444   const SCEV *PtrScev = replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr);
1445 
1446   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
1447   if (Assume && !AR)
1448     AR = PSE.getAsAddRec(Ptr);
1449 
1450   if (!AR) {
1451     LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer " << *Ptr
1452                       << " SCEV: " << *PtrScev << "\n");
1453     return std::nullopt;
1454   }
1455 
1456   // The access function must stride over the innermost loop.
1457   if (Lp != AR->getLoop()) {
1458     LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop "
1459                       << *Ptr << " SCEV: " << *AR << "\n");
1460     return std::nullopt;
1461   }
1462 
1463   // Check the step is constant.
1464   const SCEV *Step = AR->getStepRecurrence(*PSE.getSE());
1465 
1466   // Calculate the pointer stride and check if it is constant.
1467   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
1468   if (!C) {
1469     LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr
1470                       << " SCEV: " << *AR << "\n");
1471     return std::nullopt;
1472   }
1473 
1474   auto &DL = Lp->getHeader()->getModule()->getDataLayout();
1475   TypeSize AllocSize = DL.getTypeAllocSize(AccessTy);
1476   int64_t Size = AllocSize.getFixedValue();
1477   const APInt &APStepVal = C->getAPInt();
1478 
1479   // Huge step value - give up.
1480   if (APStepVal.getBitWidth() > 64)
1481     return std::nullopt;
1482 
1483   int64_t StepVal = APStepVal.getSExtValue();
1484 
1485   // Strided access.
1486   int64_t Stride = StepVal / Size;
1487   int64_t Rem = StepVal % Size;
1488   if (Rem)
1489     return std::nullopt;
1490 
1491   if (!ShouldCheckWrap)
1492     return Stride;
1493 
1494   // The address calculation must not wrap. Otherwise, a dependence could be
1495   // inverted.
1496   if (isNoWrapAddRec(Ptr, AR, PSE, Lp))
1497     return Stride;
1498 
1499   // An inbounds getelementptr that is a AddRec with a unit stride
1500   // cannot wrap per definition.  If it did, the result would be poison
1501   // and any memory access dependent on it would be immediate UB
1502   // when executed.
1503   if (auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
1504       GEP && GEP->isInBounds() && (Stride == 1 || Stride == -1))
1505     return Stride;
1506 
1507   // If the null pointer is undefined, then a access sequence which would
1508   // otherwise access it can be assumed not to unsigned wrap.  Note that this
1509   // assumes the object in memory is aligned to the natural alignment.
1510   unsigned AddrSpace = Ty->getPointerAddressSpace();
1511   if (!NullPointerIsDefined(Lp->getHeader()->getParent(), AddrSpace) &&
1512       (Stride == 1 || Stride == -1))
1513     return Stride;
1514 
1515   if (Assume) {
1516     PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
1517     LLVM_DEBUG(dbgs() << "LAA: Pointer may wrap:\n"
1518                       << "LAA:   Pointer: " << *Ptr << "\n"
1519                       << "LAA:   SCEV: " << *AR << "\n"
1520                       << "LAA:   Added an overflow assumption\n");
1521     return Stride;
1522   }
1523   LLVM_DEBUG(
1524       dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
1525              << *Ptr << " SCEV: " << *AR << "\n");
1526   return std::nullopt;
1527 }
1528 
1529 std::optional<int> llvm::getPointersDiff(Type *ElemTyA, Value *PtrA,
1530                                          Type *ElemTyB, Value *PtrB,
1531                                          const DataLayout &DL,
1532                                          ScalarEvolution &SE, bool StrictCheck,
1533                                          bool CheckType) {
1534   assert(PtrA && PtrB && "Expected non-nullptr pointers.");
1535 
1536   // Make sure that A and B are different pointers.
1537   if (PtrA == PtrB)
1538     return 0;
1539 
1540   // Make sure that the element types are the same if required.
1541   if (CheckType && ElemTyA != ElemTyB)
1542     return std::nullopt;
1543 
1544   unsigned ASA = PtrA->getType()->getPointerAddressSpace();
1545   unsigned ASB = PtrB->getType()->getPointerAddressSpace();
1546 
1547   // Check that the address spaces match.
1548   if (ASA != ASB)
1549     return std::nullopt;
1550   unsigned IdxWidth = DL.getIndexSizeInBits(ASA);
1551 
1552   APInt OffsetA(IdxWidth, 0), OffsetB(IdxWidth, 0);
1553   Value *PtrA1 = PtrA->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetA);
1554   Value *PtrB1 = PtrB->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetB);
1555 
1556   int Val;
1557   if (PtrA1 == PtrB1) {
1558     // Retrieve the address space again as pointer stripping now tracks through
1559     // `addrspacecast`.
1560     ASA = cast<PointerType>(PtrA1->getType())->getAddressSpace();
1561     ASB = cast<PointerType>(PtrB1->getType())->getAddressSpace();
1562     // Check that the address spaces match and that the pointers are valid.
1563     if (ASA != ASB)
1564       return std::nullopt;
1565 
1566     IdxWidth = DL.getIndexSizeInBits(ASA);
1567     OffsetA = OffsetA.sextOrTrunc(IdxWidth);
1568     OffsetB = OffsetB.sextOrTrunc(IdxWidth);
1569 
1570     OffsetB -= OffsetA;
1571     Val = OffsetB.getSExtValue();
1572   } else {
1573     // Otherwise compute the distance with SCEV between the base pointers.
1574     const SCEV *PtrSCEVA = SE.getSCEV(PtrA);
1575     const SCEV *PtrSCEVB = SE.getSCEV(PtrB);
1576     const auto *Diff =
1577         dyn_cast<SCEVConstant>(SE.getMinusSCEV(PtrSCEVB, PtrSCEVA));
1578     if (!Diff)
1579       return std::nullopt;
1580     Val = Diff->getAPInt().getSExtValue();
1581   }
1582   int Size = DL.getTypeStoreSize(ElemTyA);
1583   int Dist = Val / Size;
1584 
1585   // Ensure that the calculated distance matches the type-based one after all
1586   // the bitcasts removal in the provided pointers.
1587   if (!StrictCheck || Dist * Size == Val)
1588     return Dist;
1589   return std::nullopt;
1590 }
1591 
1592 bool llvm::sortPtrAccesses(ArrayRef<Value *> VL, Type *ElemTy,
1593                            const DataLayout &DL, ScalarEvolution &SE,
1594                            SmallVectorImpl<unsigned> &SortedIndices) {
1595   assert(llvm::all_of(
1596              VL, [](const Value *V) { return V->getType()->isPointerTy(); }) &&
1597          "Expected list of pointer operands.");
1598   // Walk over the pointers, and map each of them to an offset relative to
1599   // first pointer in the array.
1600   Value *Ptr0 = VL[0];
1601 
1602   using DistOrdPair = std::pair<int64_t, int>;
1603   auto Compare = llvm::less_first();
1604   std::set<DistOrdPair, decltype(Compare)> Offsets(Compare);
1605   Offsets.emplace(0, 0);
1606   int Cnt = 1;
1607   bool IsConsecutive = true;
1608   for (auto *Ptr : VL.drop_front()) {
1609     std::optional<int> Diff = getPointersDiff(ElemTy, Ptr0, ElemTy, Ptr, DL, SE,
1610                                               /*StrictCheck=*/true);
1611     if (!Diff)
1612       return false;
1613 
1614     // Check if the pointer with the same offset is found.
1615     int64_t Offset = *Diff;
1616     auto Res = Offsets.emplace(Offset, Cnt);
1617     if (!Res.second)
1618       return false;
1619     // Consecutive order if the inserted element is the last one.
1620     IsConsecutive = IsConsecutive && std::next(Res.first) == Offsets.end();
1621     ++Cnt;
1622   }
1623   SortedIndices.clear();
1624   if (!IsConsecutive) {
1625     // Fill SortedIndices array only if it is non-consecutive.
1626     SortedIndices.resize(VL.size());
1627     Cnt = 0;
1628     for (const std::pair<int64_t, int> &Pair : Offsets) {
1629       SortedIndices[Cnt] = Pair.second;
1630       ++Cnt;
1631     }
1632   }
1633   return true;
1634 }
1635 
1636 /// Returns true if the memory operations \p A and \p B are consecutive.
1637 bool llvm::isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL,
1638                                ScalarEvolution &SE, bool CheckType) {
1639   Value *PtrA = getLoadStorePointerOperand(A);
1640   Value *PtrB = getLoadStorePointerOperand(B);
1641   if (!PtrA || !PtrB)
1642     return false;
1643   Type *ElemTyA = getLoadStoreType(A);
1644   Type *ElemTyB = getLoadStoreType(B);
1645   std::optional<int> Diff =
1646       getPointersDiff(ElemTyA, PtrA, ElemTyB, PtrB, DL, SE,
1647                       /*StrictCheck=*/true, CheckType);
1648   return Diff && *Diff == 1;
1649 }
1650 
1651 void MemoryDepChecker::addAccess(StoreInst *SI) {
1652   visitPointers(SI->getPointerOperand(), *InnermostLoop,
1653                 [this, SI](Value *Ptr) {
1654                   Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
1655                   InstMap.push_back(SI);
1656                   ++AccessIdx;
1657                 });
1658 }
1659 
1660 void MemoryDepChecker::addAccess(LoadInst *LI) {
1661   visitPointers(LI->getPointerOperand(), *InnermostLoop,
1662                 [this, LI](Value *Ptr) {
1663                   Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
1664                   InstMap.push_back(LI);
1665                   ++AccessIdx;
1666                 });
1667 }
1668 
1669 MemoryDepChecker::VectorizationSafetyStatus
1670 MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
1671   switch (Type) {
1672   case NoDep:
1673   case Forward:
1674   case BackwardVectorizable:
1675     return VectorizationSafetyStatus::Safe;
1676 
1677   case Unknown:
1678     return VectorizationSafetyStatus::PossiblySafeWithRtChecks;
1679   case ForwardButPreventsForwarding:
1680   case Backward:
1681   case BackwardVectorizableButPreventsForwarding:
1682   case IndirectUnsafe:
1683     return VectorizationSafetyStatus::Unsafe;
1684   }
1685   llvm_unreachable("unexpected DepType!");
1686 }
1687 
1688 bool MemoryDepChecker::Dependence::isBackward() const {
1689   switch (Type) {
1690   case NoDep:
1691   case Forward:
1692   case ForwardButPreventsForwarding:
1693   case Unknown:
1694   case IndirectUnsafe:
1695     return false;
1696 
1697   case BackwardVectorizable:
1698   case Backward:
1699   case BackwardVectorizableButPreventsForwarding:
1700     return true;
1701   }
1702   llvm_unreachable("unexpected DepType!");
1703 }
1704 
1705 bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
1706   return isBackward() || Type == Unknown;
1707 }
1708 
1709 bool MemoryDepChecker::Dependence::isForward() const {
1710   switch (Type) {
1711   case Forward:
1712   case ForwardButPreventsForwarding:
1713     return true;
1714 
1715   case NoDep:
1716   case Unknown:
1717   case BackwardVectorizable:
1718   case Backward:
1719   case BackwardVectorizableButPreventsForwarding:
1720   case IndirectUnsafe:
1721     return false;
1722   }
1723   llvm_unreachable("unexpected DepType!");
1724 }
1725 
1726 bool MemoryDepChecker::couldPreventStoreLoadForward(uint64_t Distance,
1727                                                     uint64_t TypeByteSize) {
1728   // If loads occur at a distance that is not a multiple of a feasible vector
1729   // factor store-load forwarding does not take place.
1730   // Positive dependences might cause troubles because vectorizing them might
1731   // prevent store-load forwarding making vectorized code run a lot slower.
1732   //   a[i] = a[i-3] ^ a[i-8];
1733   //   The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
1734   //   hence on your typical architecture store-load forwarding does not take
1735   //   place. Vectorizing in such cases does not make sense.
1736   // Store-load forwarding distance.
1737 
1738   // After this many iterations store-to-load forwarding conflicts should not
1739   // cause any slowdowns.
1740   const uint64_t NumItersForStoreLoadThroughMemory = 8 * TypeByteSize;
1741   // Maximum vector factor.
1742   uint64_t MaxVFWithoutSLForwardIssues = std::min(
1743       VectorizerParams::MaxVectorWidth * TypeByteSize, MinDepDistBytes);
1744 
1745   // Compute the smallest VF at which the store and load would be misaligned.
1746   for (uint64_t VF = 2 * TypeByteSize; VF <= MaxVFWithoutSLForwardIssues;
1747        VF *= 2) {
1748     // If the number of vector iteration between the store and the load are
1749     // small we could incur conflicts.
1750     if (Distance % VF && Distance / VF < NumItersForStoreLoadThroughMemory) {
1751       MaxVFWithoutSLForwardIssues = (VF >> 1);
1752       break;
1753     }
1754   }
1755 
1756   if (MaxVFWithoutSLForwardIssues < 2 * TypeByteSize) {
1757     LLVM_DEBUG(
1758         dbgs() << "LAA: Distance " << Distance
1759                << " that could cause a store-load forwarding conflict\n");
1760     return true;
1761   }
1762 
1763   if (MaxVFWithoutSLForwardIssues < MinDepDistBytes &&
1764       MaxVFWithoutSLForwardIssues !=
1765           VectorizerParams::MaxVectorWidth * TypeByteSize)
1766     MinDepDistBytes = MaxVFWithoutSLForwardIssues;
1767   return false;
1768 }
1769 
1770 void MemoryDepChecker::mergeInStatus(VectorizationSafetyStatus S) {
1771   if (Status < S)
1772     Status = S;
1773 }
1774 
1775 /// Given a dependence-distance \p Dist between two
1776 /// memory accesses, that have the same stride whose absolute value is given
1777 /// in \p Stride, and that have the same type size \p TypeByteSize,
1778 /// in a loop whose takenCount is \p BackedgeTakenCount, check if it is
1779 /// possible to prove statically that the dependence distance is larger
1780 /// than the range that the accesses will travel through the execution of
1781 /// the loop. If so, return true; false otherwise. This is useful for
1782 /// example in loops such as the following (PR31098):
1783 ///     for (i = 0; i < D; ++i) {
1784 ///                = out[i];
1785 ///       out[i+D] =
1786 ///     }
1787 static bool isSafeDependenceDistance(const DataLayout &DL, ScalarEvolution &SE,
1788                                      const SCEV &BackedgeTakenCount,
1789                                      const SCEV &Dist, uint64_t Stride,
1790                                      uint64_t TypeByteSize) {
1791 
1792   // If we can prove that
1793   //      (**) |Dist| > BackedgeTakenCount * Step
1794   // where Step is the absolute stride of the memory accesses in bytes,
1795   // then there is no dependence.
1796   //
1797   // Rationale:
1798   // We basically want to check if the absolute distance (|Dist/Step|)
1799   // is >= the loop iteration count (or > BackedgeTakenCount).
1800   // This is equivalent to the Strong SIV Test (Practical Dependence Testing,
1801   // Section 4.2.1); Note, that for vectorization it is sufficient to prove
1802   // that the dependence distance is >= VF; This is checked elsewhere.
1803   // But in some cases we can prune dependence distances early, and
1804   // even before selecting the VF, and without a runtime test, by comparing
1805   // the distance against the loop iteration count. Since the vectorized code
1806   // will be executed only if LoopCount >= VF, proving distance >= LoopCount
1807   // also guarantees that distance >= VF.
1808   //
1809   const uint64_t ByteStride = Stride * TypeByteSize;
1810   const SCEV *Step = SE.getConstant(BackedgeTakenCount.getType(), ByteStride);
1811   const SCEV *Product = SE.getMulExpr(&BackedgeTakenCount, Step);
1812 
1813   const SCEV *CastedDist = &Dist;
1814   const SCEV *CastedProduct = Product;
1815   uint64_t DistTypeSizeBits = DL.getTypeSizeInBits(Dist.getType());
1816   uint64_t ProductTypeSizeBits = DL.getTypeSizeInBits(Product->getType());
1817 
1818   // The dependence distance can be positive/negative, so we sign extend Dist;
1819   // The multiplication of the absolute stride in bytes and the
1820   // backedgeTakenCount is non-negative, so we zero extend Product.
1821   if (DistTypeSizeBits > ProductTypeSizeBits)
1822     CastedProduct = SE.getZeroExtendExpr(Product, Dist.getType());
1823   else
1824     CastedDist = SE.getNoopOrSignExtend(&Dist, Product->getType());
1825 
1826   // Is  Dist - (BackedgeTakenCount * Step) > 0 ?
1827   // (If so, then we have proven (**) because |Dist| >= Dist)
1828   const SCEV *Minus = SE.getMinusSCEV(CastedDist, CastedProduct);
1829   if (SE.isKnownPositive(Minus))
1830     return true;
1831 
1832   // Second try: Is  -Dist - (BackedgeTakenCount * Step) > 0 ?
1833   // (If so, then we have proven (**) because |Dist| >= -1*Dist)
1834   const SCEV *NegDist = SE.getNegativeSCEV(CastedDist);
1835   Minus = SE.getMinusSCEV(NegDist, CastedProduct);
1836   if (SE.isKnownPositive(Minus))
1837     return true;
1838 
1839   return false;
1840 }
1841 
1842 /// Check the dependence for two accesses with the same stride \p Stride.
1843 /// \p Distance is the positive distance and \p TypeByteSize is type size in
1844 /// bytes.
1845 ///
1846 /// \returns true if they are independent.
1847 static bool areStridedAccessesIndependent(uint64_t Distance, uint64_t Stride,
1848                                           uint64_t TypeByteSize) {
1849   assert(Stride > 1 && "The stride must be greater than 1");
1850   assert(TypeByteSize > 0 && "The type size in byte must be non-zero");
1851   assert(Distance > 0 && "The distance must be non-zero");
1852 
1853   // Skip if the distance is not multiple of type byte size.
1854   if (Distance % TypeByteSize)
1855     return false;
1856 
1857   uint64_t ScaledDist = Distance / TypeByteSize;
1858 
1859   // No dependence if the scaled distance is not multiple of the stride.
1860   // E.g.
1861   //      for (i = 0; i < 1024 ; i += 4)
1862   //        A[i+2] = A[i] + 1;
1863   //
1864   // Two accesses in memory (scaled distance is 2, stride is 4):
1865   //     | A[0] |      |      |      | A[4] |      |      |      |
1866   //     |      |      | A[2] |      |      |      | A[6] |      |
1867   //
1868   // E.g.
1869   //      for (i = 0; i < 1024 ; i += 3)
1870   //        A[i+4] = A[i] + 1;
1871   //
1872   // Two accesses in memory (scaled distance is 4, stride is 3):
1873   //     | A[0] |      |      | A[3] |      |      | A[6] |      |      |
1874   //     |      |      |      |      | A[4] |      |      | A[7] |      |
1875   return ScaledDist % Stride;
1876 }
1877 
1878 /// Returns true if any of the underlying objects has a loop varying address,
1879 /// i.e. may change in \p L.
1880 static bool
1881 isLoopVariantIndirectAddress(ArrayRef<const Value *> UnderlyingObjects,
1882                              ScalarEvolution &SE, const Loop *L) {
1883   return any_of(UnderlyingObjects, [&SE, L](const Value *UO) {
1884     return !SE.isLoopInvariant(SE.getSCEV(const_cast<Value *>(UO)), L);
1885   });
1886 }
1887 
1888 // Get the dependence distance, stride, type size in whether i is a write for
1889 // the dependence between A and B. Returns a DepType, if we can prove there's
1890 // no dependence or the analysis fails. Outlined to lambda to limit he scope
1891 // of various temporary variables, like A/BPtr, StrideA/BPtr and others.
1892 // Returns either the dependence result, if it could already be determined, or a
1893 // tuple with (Distance, Stride, TypeSize, AIsWrite, BIsWrite).
1894 static std::variant<MemoryDepChecker::Dependence::DepType,
1895                     std::tuple<const SCEV *, uint64_t, uint64_t, bool, bool>>
1896 getDependenceDistanceStrideAndSize(
1897     const AccessAnalysis::MemAccessInfo &A, Instruction *AInst,
1898     const AccessAnalysis::MemAccessInfo &B, Instruction *BInst,
1899     const DenseMap<Value *, const SCEV *> &Strides,
1900     const DenseMap<Value *, SmallVector<const Value *, 16>> &UnderlyingObjects,
1901     PredicatedScalarEvolution &PSE, const Loop *InnermostLoop) {
1902   auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
1903   auto &SE = *PSE.getSE();
1904   auto [APtr, AIsWrite] = A;
1905   auto [BPtr, BIsWrite] = B;
1906 
1907   // Two reads are independent.
1908   if (!AIsWrite && !BIsWrite)
1909     return MemoryDepChecker::Dependence::NoDep;
1910 
1911   Type *ATy = getLoadStoreType(AInst);
1912   Type *BTy = getLoadStoreType(BInst);
1913 
1914   // We cannot check pointers in different address spaces.
1915   if (APtr->getType()->getPointerAddressSpace() !=
1916       BPtr->getType()->getPointerAddressSpace())
1917     return MemoryDepChecker::Dependence::Unknown;
1918 
1919   int64_t StrideAPtr =
1920       getPtrStride(PSE, ATy, APtr, InnermostLoop, Strides, true).value_or(0);
1921   int64_t StrideBPtr =
1922       getPtrStride(PSE, BTy, BPtr, InnermostLoop, Strides, true).value_or(0);
1923 
1924   const SCEV *Src = PSE.getSCEV(APtr);
1925   const SCEV *Sink = PSE.getSCEV(BPtr);
1926 
1927   // If the induction step is negative we have to invert source and sink of the
1928   // dependence when measuring the distance between them. We should not swap
1929   // AIsWrite with BIsWrite, as their uses expect them in program order.
1930   if (StrideAPtr < 0) {
1931     std::swap(Src, Sink);
1932     std::swap(AInst, BInst);
1933   }
1934 
1935   const SCEV *Dist = SE.getMinusSCEV(Sink, Src);
1936 
1937   LLVM_DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
1938                     << "(Induction step: " << StrideAPtr << ")\n");
1939   LLVM_DEBUG(dbgs() << "LAA: Distance for " << *AInst << " to " << *BInst
1940                     << ": " << *Dist << "\n");
1941 
1942   // Needs accesses where the addresses of the accessed underlying objects do
1943   // not change within the loop.
1944   if (isLoopVariantIndirectAddress(UnderlyingObjects.find(APtr)->second, SE,
1945                                    InnermostLoop) ||
1946       isLoopVariantIndirectAddress(UnderlyingObjects.find(BPtr)->second, SE,
1947                                    InnermostLoop))
1948     return MemoryDepChecker::Dependence::IndirectUnsafe;
1949 
1950   // Need accesses with constant stride. We don't want to vectorize
1951   // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap
1952   // in the address space.
1953   if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr) {
1954     LLVM_DEBUG(dbgs() << "Pointer access with non-constant stride\n");
1955     return MemoryDepChecker::Dependence::Unknown;
1956   }
1957 
1958   uint64_t TypeByteSize = DL.getTypeAllocSize(ATy);
1959   bool HasSameSize =
1960       DL.getTypeStoreSizeInBits(ATy) == DL.getTypeStoreSizeInBits(BTy);
1961   if (!HasSameSize)
1962     TypeByteSize = 0;
1963   uint64_t Stride = std::abs(StrideAPtr);
1964   return std::make_tuple(Dist, Stride, TypeByteSize, AIsWrite, BIsWrite);
1965 }
1966 
1967 MemoryDepChecker::Dependence::DepType MemoryDepChecker::isDependent(
1968     const MemAccessInfo &A, unsigned AIdx, const MemAccessInfo &B,
1969     unsigned BIdx, const DenseMap<Value *, const SCEV *> &Strides,
1970     const DenseMap<Value *, SmallVector<const Value *, 16>>
1971         &UnderlyingObjects) {
1972   assert(AIdx < BIdx && "Must pass arguments in program order");
1973 
1974   // Get the dependence distance, stride, type size and what access writes for
1975   // the dependence between A and B.
1976   auto Res = getDependenceDistanceStrideAndSize(
1977       A, InstMap[AIdx], B, InstMap[BIdx], Strides, UnderlyingObjects, PSE,
1978       InnermostLoop);
1979   if (std::holds_alternative<Dependence::DepType>(Res))
1980     return std::get<Dependence::DepType>(Res);
1981 
1982   const auto &[Dist, Stride, TypeByteSize, AIsWrite, BIsWrite] =
1983       std::get<std::tuple<const SCEV *, uint64_t, uint64_t, bool, bool>>(Res);
1984   bool HasSameSize = TypeByteSize > 0;
1985 
1986   ScalarEvolution &SE = *PSE.getSE();
1987   auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
1988   if (!isa<SCEVCouldNotCompute>(Dist) && HasSameSize &&
1989       isSafeDependenceDistance(DL, SE, *(PSE.getBackedgeTakenCount()), *Dist,
1990                                Stride, TypeByteSize))
1991     return Dependence::NoDep;
1992 
1993   const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
1994   if (!C) {
1995     LLVM_DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
1996     FoundNonConstantDistanceDependence = true;
1997     return Dependence::Unknown;
1998   }
1999 
2000   const APInt &Val = C->getAPInt();
2001   int64_t Distance = Val.getSExtValue();
2002 
2003   // Attempt to prove strided accesses independent.
2004   if (std::abs(Distance) > 0 && Stride > 1 && HasSameSize &&
2005       areStridedAccessesIndependent(std::abs(Distance), Stride, TypeByteSize)) {
2006     LLVM_DEBUG(dbgs() << "LAA: Strided accesses are independent\n");
2007     return Dependence::NoDep;
2008   }
2009 
2010   // Negative distances are not plausible dependencies.
2011   if (Val.isNegative()) {
2012     bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
2013     // There is no need to update MaxSafeVectorWidthInBits after call to
2014     // couldPreventStoreLoadForward, even if it changed MinDepDistBytes,
2015     // since a forward dependency will allow vectorization using any width.
2016     if (IsTrueDataDependence && EnableForwardingConflictDetection &&
2017         (!HasSameSize || couldPreventStoreLoadForward(Val.abs().getZExtValue(),
2018                                                       TypeByteSize))) {
2019       LLVM_DEBUG(dbgs() << "LAA: Forward but may prevent st->ld forwarding\n");
2020       return Dependence::ForwardButPreventsForwarding;
2021     }
2022 
2023     LLVM_DEBUG(dbgs() << "LAA: Dependence is negative\n");
2024     return Dependence::Forward;
2025   }
2026 
2027   // Write to the same location with the same size.
2028   if (Val == 0) {
2029     if (HasSameSize)
2030       return Dependence::Forward;
2031     LLVM_DEBUG(
2032         dbgs() << "LAA: Zero dependence difference but different type sizes\n");
2033     return Dependence::Unknown;
2034   }
2035 
2036   assert(Val.isStrictlyPositive() && "Expect a positive value");
2037 
2038   if (!HasSameSize) {
2039     LLVM_DEBUG(dbgs() << "LAA: ReadWrite-Write positive dependency with "
2040                          "different type sizes\n");
2041     return Dependence::Unknown;
2042   }
2043 
2044   // Bail out early if passed-in parameters make vectorization not feasible.
2045   unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
2046                            VectorizerParams::VectorizationFactor : 1);
2047   unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
2048                            VectorizerParams::VectorizationInterleave : 1);
2049   // The minimum number of iterations for a vectorized/unrolled version.
2050   unsigned MinNumIter = std::max(ForcedFactor * ForcedUnroll, 2U);
2051 
2052   // It's not vectorizable if the distance is smaller than the minimum distance
2053   // needed for a vectroized/unrolled version. Vectorizing one iteration in
2054   // front needs TypeByteSize * Stride. Vectorizing the last iteration needs
2055   // TypeByteSize (No need to plus the last gap distance).
2056   //
2057   // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
2058   //      foo(int *A) {
2059   //        int *B = (int *)((char *)A + 14);
2060   //        for (i = 0 ; i < 1024 ; i += 2)
2061   //          B[i] = A[i] + 1;
2062   //      }
2063   //
2064   // Two accesses in memory (stride is 2):
2065   //     | A[0] |      | A[2] |      | A[4] |      | A[6] |      |
2066   //                              | B[0] |      | B[2] |      | B[4] |
2067   //
2068   // Distance needs for vectorizing iterations except the last iteration:
2069   // 4 * 2 * (MinNumIter - 1). Distance needs for the last iteration: 4.
2070   // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4.
2071   //
2072   // If MinNumIter is 2, it is vectorizable as the minimum distance needed is
2073   // 12, which is less than distance.
2074   //
2075   // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4),
2076   // the minimum distance needed is 28, which is greater than distance. It is
2077   // not safe to do vectorization.
2078   uint64_t MinDistanceNeeded =
2079       TypeByteSize * Stride * (MinNumIter - 1) + TypeByteSize;
2080   if (MinDistanceNeeded > static_cast<uint64_t>(Distance)) {
2081     LLVM_DEBUG(dbgs() << "LAA: Failure because of positive distance "
2082                       << Distance << '\n');
2083     return Dependence::Backward;
2084   }
2085 
2086   // Unsafe if the minimum distance needed is greater than smallest dependence
2087   // distance distance.
2088   if (MinDistanceNeeded > MinDepDistBytes) {
2089     LLVM_DEBUG(dbgs() << "LAA: Failure because it needs at least "
2090                       << MinDistanceNeeded << " size in bytes\n");
2091     return Dependence::Backward;
2092   }
2093 
2094   // Positive distance bigger than max vectorization factor.
2095   // FIXME: Should use max factor instead of max distance in bytes, which could
2096   // not handle different types.
2097   // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
2098   //      void foo (int *A, char *B) {
2099   //        for (unsigned i = 0; i < 1024; i++) {
2100   //          A[i+2] = A[i] + 1;
2101   //          B[i+2] = B[i] + 1;
2102   //        }
2103   //      }
2104   //
2105   // This case is currently unsafe according to the max safe distance. If we
2106   // analyze the two accesses on array B, the max safe dependence distance
2107   // is 2. Then we analyze the accesses on array A, the minimum distance needed
2108   // is 8, which is less than 2 and forbidden vectorization, But actually
2109   // both A and B could be vectorized by 2 iterations.
2110   MinDepDistBytes =
2111       std::min(static_cast<uint64_t>(Distance), MinDepDistBytes);
2112 
2113   bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
2114   uint64_t MinDepDistBytesOld = MinDepDistBytes;
2115   if (IsTrueDataDependence && EnableForwardingConflictDetection &&
2116       couldPreventStoreLoadForward(Distance, TypeByteSize)) {
2117     // Sanity check that we didn't update MinDepDistBytes when calling
2118     // couldPreventStoreLoadForward
2119     assert(MinDepDistBytes == MinDepDistBytesOld &&
2120            "An update to MinDepDistBytes requires an update to "
2121            "MaxSafeVectorWidthInBits");
2122     (void)MinDepDistBytesOld;
2123     return Dependence::BackwardVectorizableButPreventsForwarding;
2124   }
2125 
2126   // An update to MinDepDistBytes requires an update to MaxSafeVectorWidthInBits
2127   // since there is a backwards dependency.
2128   uint64_t MaxVF = MinDepDistBytes / (TypeByteSize * Stride);
2129   LLVM_DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue()
2130                     << " with max VF = " << MaxVF << '\n');
2131   uint64_t MaxVFInBits = MaxVF * TypeByteSize * 8;
2132   MaxSafeVectorWidthInBits = std::min(MaxSafeVectorWidthInBits, MaxVFInBits);
2133   return Dependence::BackwardVectorizable;
2134 }
2135 
2136 bool MemoryDepChecker::areDepsSafe(
2137     DepCandidates &AccessSets, MemAccessInfoList &CheckDeps,
2138     const DenseMap<Value *, const SCEV *> &Strides,
2139     const DenseMap<Value *, SmallVector<const Value *, 16>>
2140         &UnderlyingObjects) {
2141 
2142   MinDepDistBytes = -1;
2143   SmallPtrSet<MemAccessInfo, 8> Visited;
2144   for (MemAccessInfo CurAccess : CheckDeps) {
2145     if (Visited.count(CurAccess))
2146       continue;
2147 
2148     // Get the relevant memory access set.
2149     EquivalenceClasses<MemAccessInfo>::iterator I =
2150       AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
2151 
2152     // Check accesses within this set.
2153     EquivalenceClasses<MemAccessInfo>::member_iterator AI =
2154         AccessSets.member_begin(I);
2155     EquivalenceClasses<MemAccessInfo>::member_iterator AE =
2156         AccessSets.member_end();
2157 
2158     // Check every access pair.
2159     while (AI != AE) {
2160       Visited.insert(*AI);
2161       bool AIIsWrite = AI->getInt();
2162       // Check loads only against next equivalent class, but stores also against
2163       // other stores in the same equivalence class - to the same address.
2164       EquivalenceClasses<MemAccessInfo>::member_iterator OI =
2165           (AIIsWrite ? AI : std::next(AI));
2166       while (OI != AE) {
2167         // Check every accessing instruction pair in program order.
2168         for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
2169              I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
2170           // Scan all accesses of another equivalence class, but only the next
2171           // accesses of the same equivalent class.
2172           for (std::vector<unsigned>::iterator
2173                    I2 = (OI == AI ? std::next(I1) : Accesses[*OI].begin()),
2174                    I2E = (OI == AI ? I1E : Accesses[*OI].end());
2175                I2 != I2E; ++I2) {
2176             auto A = std::make_pair(&*AI, *I1);
2177             auto B = std::make_pair(&*OI, *I2);
2178 
2179             assert(*I1 != *I2);
2180             if (*I1 > *I2)
2181               std::swap(A, B);
2182 
2183             Dependence::DepType Type =
2184                 isDependent(*A.first, A.second, *B.first, B.second, Strides,
2185                             UnderlyingObjects);
2186             mergeInStatus(Dependence::isSafeForVectorization(Type));
2187 
2188             // Gather dependences unless we accumulated MaxDependences
2189             // dependences.  In that case return as soon as we find the first
2190             // unsafe dependence.  This puts a limit on this quadratic
2191             // algorithm.
2192             if (RecordDependences) {
2193               if (Type != Dependence::NoDep)
2194                 Dependences.push_back(Dependence(A.second, B.second, Type));
2195 
2196               if (Dependences.size() >= MaxDependences) {
2197                 RecordDependences = false;
2198                 Dependences.clear();
2199                 LLVM_DEBUG(dbgs()
2200                            << "Too many dependences, stopped recording\n");
2201               }
2202             }
2203             if (!RecordDependences && !isSafeForVectorization())
2204               return false;
2205           }
2206         ++OI;
2207       }
2208       AI++;
2209     }
2210   }
2211 
2212   LLVM_DEBUG(dbgs() << "Total Dependences: " << Dependences.size() << "\n");
2213   return isSafeForVectorization();
2214 }
2215 
2216 SmallVector<Instruction *, 4>
2217 MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const {
2218   MemAccessInfo Access(Ptr, isWrite);
2219   auto &IndexVector = Accesses.find(Access)->second;
2220 
2221   SmallVector<Instruction *, 4> Insts;
2222   transform(IndexVector,
2223                  std::back_inserter(Insts),
2224                  [&](unsigned Idx) { return this->InstMap[Idx]; });
2225   return Insts;
2226 }
2227 
2228 const char *MemoryDepChecker::Dependence::DepName[] = {
2229     "NoDep",
2230     "Unknown",
2231     "IndidrectUnsafe",
2232     "Forward",
2233     "ForwardButPreventsForwarding",
2234     "Backward",
2235     "BackwardVectorizable",
2236     "BackwardVectorizableButPreventsForwarding"};
2237 
2238 void MemoryDepChecker::Dependence::print(
2239     raw_ostream &OS, unsigned Depth,
2240     const SmallVectorImpl<Instruction *> &Instrs) const {
2241   OS.indent(Depth) << DepName[Type] << ":\n";
2242   OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
2243   OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
2244 }
2245 
2246 bool LoopAccessInfo::canAnalyzeLoop() {
2247   // We need to have a loop header.
2248   LLVM_DEBUG(dbgs() << "LAA: Found a loop in "
2249                     << TheLoop->getHeader()->getParent()->getName() << ": "
2250                     << TheLoop->getHeader()->getName() << '\n');
2251 
2252   // We can only analyze innermost loops.
2253   if (!TheLoop->isInnermost()) {
2254     LLVM_DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
2255     recordAnalysis("NotInnerMostLoop") << "loop is not the innermost loop";
2256     return false;
2257   }
2258 
2259   // We must have a single backedge.
2260   if (TheLoop->getNumBackEdges() != 1) {
2261     LLVM_DEBUG(
2262         dbgs() << "LAA: loop control flow is not understood by analyzer\n");
2263     recordAnalysis("CFGNotUnderstood")
2264         << "loop control flow is not understood by analyzer";
2265     return false;
2266   }
2267 
2268   // ScalarEvolution needs to be able to find the exit count.
2269   const SCEV *ExitCount = PSE->getBackedgeTakenCount();
2270   if (isa<SCEVCouldNotCompute>(ExitCount)) {
2271     recordAnalysis("CantComputeNumberOfIterations")
2272         << "could not determine number of loop iterations";
2273     LLVM_DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
2274     return false;
2275   }
2276 
2277   return true;
2278 }
2279 
2280 void LoopAccessInfo::analyzeLoop(AAResults *AA, LoopInfo *LI,
2281                                  const TargetLibraryInfo *TLI,
2282                                  DominatorTree *DT) {
2283   // Holds the Load and Store instructions.
2284   SmallVector<LoadInst *, 16> Loads;
2285   SmallVector<StoreInst *, 16> Stores;
2286 
2287   // Holds all the different accesses in the loop.
2288   unsigned NumReads = 0;
2289   unsigned NumReadWrites = 0;
2290 
2291   bool HasComplexMemInst = false;
2292 
2293   // A runtime check is only legal to insert if there are no convergent calls.
2294   HasConvergentOp = false;
2295 
2296   PtrRtChecking->Pointers.clear();
2297   PtrRtChecking->Need = false;
2298 
2299   const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
2300 
2301   const bool EnableMemAccessVersioningOfLoop =
2302       EnableMemAccessVersioning &&
2303       !TheLoop->getHeader()->getParent()->hasOptSize();
2304 
2305   // Traverse blocks in fixed RPOT order, regardless of their storage in the
2306   // loop info, as it may be arbitrary.
2307   LoopBlocksRPO RPOT(TheLoop);
2308   RPOT.perform(LI);
2309   for (BasicBlock *BB : RPOT) {
2310     // Scan the BB and collect legal loads and stores. Also detect any
2311     // convergent instructions.
2312     for (Instruction &I : *BB) {
2313       if (auto *Call = dyn_cast<CallBase>(&I)) {
2314         if (Call->isConvergent())
2315           HasConvergentOp = true;
2316       }
2317 
2318       // With both a non-vectorizable memory instruction and a convergent
2319       // operation, found in this loop, no reason to continue the search.
2320       if (HasComplexMemInst && HasConvergentOp) {
2321         CanVecMem = false;
2322         return;
2323       }
2324 
2325       // Avoid hitting recordAnalysis multiple times.
2326       if (HasComplexMemInst)
2327         continue;
2328 
2329       // Many math library functions read the rounding mode. We will only
2330       // vectorize a loop if it contains known function calls that don't set
2331       // the flag. Therefore, it is safe to ignore this read from memory.
2332       auto *Call = dyn_cast<CallInst>(&I);
2333       if (Call && getVectorIntrinsicIDForCall(Call, TLI))
2334         continue;
2335 
2336       // If this is a load, save it. If this instruction can read from memory
2337       // but is not a load, then we quit. Notice that we don't handle function
2338       // calls that read or write.
2339       if (I.mayReadFromMemory()) {
2340         // If the function has an explicit vectorized counterpart, we can safely
2341         // assume that it can be vectorized.
2342         if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
2343             !VFDatabase::getMappings(*Call).empty())
2344           continue;
2345 
2346         auto *Ld = dyn_cast<LoadInst>(&I);
2347         if (!Ld) {
2348           recordAnalysis("CantVectorizeInstruction", Ld)
2349             << "instruction cannot be vectorized";
2350           HasComplexMemInst = true;
2351           continue;
2352         }
2353         if (!Ld->isSimple() && !IsAnnotatedParallel) {
2354           recordAnalysis("NonSimpleLoad", Ld)
2355               << "read with atomic ordering or volatile read";
2356           LLVM_DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
2357           HasComplexMemInst = true;
2358           continue;
2359         }
2360         NumLoads++;
2361         Loads.push_back(Ld);
2362         DepChecker->addAccess(Ld);
2363         if (EnableMemAccessVersioningOfLoop)
2364           collectStridedAccess(Ld);
2365         continue;
2366       }
2367 
2368       // Save 'store' instructions. Abort if other instructions write to memory.
2369       if (I.mayWriteToMemory()) {
2370         auto *St = dyn_cast<StoreInst>(&I);
2371         if (!St) {
2372           recordAnalysis("CantVectorizeInstruction", St)
2373               << "instruction cannot be vectorized";
2374           HasComplexMemInst = true;
2375           continue;
2376         }
2377         if (!St->isSimple() && !IsAnnotatedParallel) {
2378           recordAnalysis("NonSimpleStore", St)
2379               << "write with atomic ordering or volatile write";
2380           LLVM_DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
2381           HasComplexMemInst = true;
2382           continue;
2383         }
2384         NumStores++;
2385         Stores.push_back(St);
2386         DepChecker->addAccess(St);
2387         if (EnableMemAccessVersioningOfLoop)
2388           collectStridedAccess(St);
2389       }
2390     } // Next instr.
2391   } // Next block.
2392 
2393   if (HasComplexMemInst) {
2394     CanVecMem = false;
2395     return;
2396   }
2397 
2398   // Now we have two lists that hold the loads and the stores.
2399   // Next, we find the pointers that they use.
2400 
2401   // Check if we see any stores. If there are no stores, then we don't
2402   // care if the pointers are *restrict*.
2403   if (!Stores.size()) {
2404     LLVM_DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
2405     CanVecMem = true;
2406     return;
2407   }
2408 
2409   MemoryDepChecker::DepCandidates DependentAccesses;
2410   AccessAnalysis Accesses(TheLoop, AA, LI, DependentAccesses, *PSE);
2411 
2412   // Holds the analyzed pointers. We don't want to call getUnderlyingObjects
2413   // multiple times on the same object. If the ptr is accessed twice, once
2414   // for read and once for write, it will only appear once (on the write
2415   // list). This is okay, since we are going to check for conflicts between
2416   // writes and between reads and writes, but not between reads and reads.
2417   SmallSet<std::pair<Value *, Type *>, 16> Seen;
2418 
2419   // Record uniform store addresses to identify if we have multiple stores
2420   // to the same address.
2421   SmallPtrSet<Value *, 16> UniformStores;
2422 
2423   for (StoreInst *ST : Stores) {
2424     Value *Ptr = ST->getPointerOperand();
2425 
2426     if (isInvariant(Ptr)) {
2427       // Record store instructions to loop invariant addresses
2428       StoresToInvariantAddresses.push_back(ST);
2429       HasDependenceInvolvingLoopInvariantAddress |=
2430           !UniformStores.insert(Ptr).second;
2431     }
2432 
2433     // If we did *not* see this pointer before, insert it to  the read-write
2434     // list. At this phase it is only a 'write' list.
2435     Type *AccessTy = getLoadStoreType(ST);
2436     if (Seen.insert({Ptr, AccessTy}).second) {
2437       ++NumReadWrites;
2438 
2439       MemoryLocation Loc = MemoryLocation::get(ST);
2440       // The TBAA metadata could have a control dependency on the predication
2441       // condition, so we cannot rely on it when determining whether or not we
2442       // need runtime pointer checks.
2443       if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
2444         Loc.AATags.TBAA = nullptr;
2445 
2446       visitPointers(const_cast<Value *>(Loc.Ptr), *TheLoop,
2447                     [&Accesses, AccessTy, Loc](Value *Ptr) {
2448                       MemoryLocation NewLoc = Loc.getWithNewPtr(Ptr);
2449                       Accesses.addStore(NewLoc, AccessTy);
2450                     });
2451     }
2452   }
2453 
2454   if (IsAnnotatedParallel) {
2455     LLVM_DEBUG(
2456         dbgs() << "LAA: A loop annotated parallel, ignore memory dependency "
2457                << "checks.\n");
2458     CanVecMem = true;
2459     return;
2460   }
2461 
2462   for (LoadInst *LD : Loads) {
2463     Value *Ptr = LD->getPointerOperand();
2464     // If we did *not* see this pointer before, insert it to the
2465     // read list. If we *did* see it before, then it is already in
2466     // the read-write list. This allows us to vectorize expressions
2467     // such as A[i] += x;  Because the address of A[i] is a read-write
2468     // pointer. This only works if the index of A[i] is consecutive.
2469     // If the address of i is unknown (for example A[B[i]]) then we may
2470     // read a few words, modify, and write a few words, and some of the
2471     // words may be written to the same address.
2472     bool IsReadOnlyPtr = false;
2473     Type *AccessTy = getLoadStoreType(LD);
2474     if (Seen.insert({Ptr, AccessTy}).second ||
2475         !getPtrStride(*PSE, LD->getType(), Ptr, TheLoop, SymbolicStrides).value_or(0)) {
2476       ++NumReads;
2477       IsReadOnlyPtr = true;
2478     }
2479 
2480     // See if there is an unsafe dependency between a load to a uniform address and
2481     // store to the same uniform address.
2482     if (UniformStores.count(Ptr)) {
2483       LLVM_DEBUG(dbgs() << "LAA: Found an unsafe dependency between a uniform "
2484                            "load and uniform store to the same address!\n");
2485       HasDependenceInvolvingLoopInvariantAddress = true;
2486     }
2487 
2488     MemoryLocation Loc = MemoryLocation::get(LD);
2489     // The TBAA metadata could have a control dependency on the predication
2490     // condition, so we cannot rely on it when determining whether or not we
2491     // need runtime pointer checks.
2492     if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
2493       Loc.AATags.TBAA = nullptr;
2494 
2495     visitPointers(const_cast<Value *>(Loc.Ptr), *TheLoop,
2496                   [&Accesses, AccessTy, Loc, IsReadOnlyPtr](Value *Ptr) {
2497                     MemoryLocation NewLoc = Loc.getWithNewPtr(Ptr);
2498                     Accesses.addLoad(NewLoc, AccessTy, IsReadOnlyPtr);
2499                   });
2500   }
2501 
2502   // If we write (or read-write) to a single destination and there are no
2503   // other reads in this loop then is it safe to vectorize.
2504   if (NumReadWrites == 1 && NumReads == 0) {
2505     LLVM_DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
2506     CanVecMem = true;
2507     return;
2508   }
2509 
2510   // Build dependence sets and check whether we need a runtime pointer bounds
2511   // check.
2512   Accesses.buildDependenceSets();
2513 
2514   // Find pointers with computable bounds. We are going to use this information
2515   // to place a runtime bound check.
2516   Value *UncomputablePtr = nullptr;
2517   bool CanDoRTIfNeeded =
2518       Accesses.canCheckPtrAtRT(*PtrRtChecking, PSE->getSE(), TheLoop,
2519                                SymbolicStrides, UncomputablePtr, false);
2520   if (!CanDoRTIfNeeded) {
2521     auto *I = dyn_cast_or_null<Instruction>(UncomputablePtr);
2522     recordAnalysis("CantIdentifyArrayBounds", I)
2523         << "cannot identify array bounds";
2524     LLVM_DEBUG(dbgs() << "LAA: We can't vectorize because we can't find "
2525                       << "the array bounds.\n");
2526     CanVecMem = false;
2527     return;
2528   }
2529 
2530   LLVM_DEBUG(
2531     dbgs() << "LAA: May be able to perform a memory runtime check if needed.\n");
2532 
2533   CanVecMem = true;
2534   if (Accesses.isDependencyCheckNeeded()) {
2535     LLVM_DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
2536     CanVecMem = DepChecker->areDepsSafe(
2537         DependentAccesses, Accesses.getDependenciesToCheck(), SymbolicStrides,
2538         Accesses.getUnderlyingObjects());
2539 
2540     if (!CanVecMem && DepChecker->shouldRetryWithRuntimeCheck()) {
2541       LLVM_DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
2542 
2543       // Clear the dependency checks. We assume they are not needed.
2544       Accesses.resetDepChecks(*DepChecker);
2545 
2546       PtrRtChecking->reset();
2547       PtrRtChecking->Need = true;
2548 
2549       auto *SE = PSE->getSE();
2550       UncomputablePtr = nullptr;
2551       CanDoRTIfNeeded = Accesses.canCheckPtrAtRT(
2552           *PtrRtChecking, SE, TheLoop, SymbolicStrides, UncomputablePtr, true);
2553 
2554       // Check that we found the bounds for the pointer.
2555       if (!CanDoRTIfNeeded) {
2556         auto *I = dyn_cast_or_null<Instruction>(UncomputablePtr);
2557         recordAnalysis("CantCheckMemDepsAtRunTime", I)
2558             << "cannot check memory dependencies at runtime";
2559         LLVM_DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
2560         CanVecMem = false;
2561         return;
2562       }
2563 
2564       CanVecMem = true;
2565     }
2566   }
2567 
2568   if (HasConvergentOp) {
2569     recordAnalysis("CantInsertRuntimeCheckWithConvergent")
2570       << "cannot add control dependency to convergent operation";
2571     LLVM_DEBUG(dbgs() << "LAA: We can't vectorize because a runtime check "
2572                          "would be needed with a convergent operation\n");
2573     CanVecMem = false;
2574     return;
2575   }
2576 
2577   if (CanVecMem)
2578     LLVM_DEBUG(
2579         dbgs() << "LAA: No unsafe dependent memory operations in loop.  We"
2580                << (PtrRtChecking->Need ? "" : " don't")
2581                << " need runtime memory checks.\n");
2582   else
2583     emitUnsafeDependenceRemark();
2584 }
2585 
2586 void LoopAccessInfo::emitUnsafeDependenceRemark() {
2587   auto Deps = getDepChecker().getDependences();
2588   if (!Deps)
2589     return;
2590   auto Found = llvm::find_if(*Deps, [](const MemoryDepChecker::Dependence &D) {
2591     return MemoryDepChecker::Dependence::isSafeForVectorization(D.Type) !=
2592            MemoryDepChecker::VectorizationSafetyStatus::Safe;
2593   });
2594   if (Found == Deps->end())
2595     return;
2596   MemoryDepChecker::Dependence Dep = *Found;
2597 
2598   LLVM_DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
2599 
2600   // Emit remark for first unsafe dependence
2601   bool HasForcedDistribution = false;
2602   std::optional<const MDOperand *> Value =
2603       findStringMetadataForLoop(TheLoop, "llvm.loop.distribute.enable");
2604   if (Value) {
2605     const MDOperand *Op = *Value;
2606     assert(Op && mdconst::hasa<ConstantInt>(*Op) && "invalid metadata");
2607     HasForcedDistribution = mdconst::extract<ConstantInt>(*Op)->getZExtValue();
2608   }
2609 
2610   const std::string Info =
2611       HasForcedDistribution
2612           ? "unsafe dependent memory operations in loop."
2613           : "unsafe dependent memory operations in loop. Use "
2614             "#pragma clang loop distribute(enable) to allow loop distribution "
2615             "to attempt to isolate the offending operations into a separate "
2616             "loop";
2617   OptimizationRemarkAnalysis &R =
2618       recordAnalysis("UnsafeDep", Dep.getDestination(*this)) << Info;
2619 
2620   switch (Dep.Type) {
2621   case MemoryDepChecker::Dependence::NoDep:
2622   case MemoryDepChecker::Dependence::Forward:
2623   case MemoryDepChecker::Dependence::BackwardVectorizable:
2624     llvm_unreachable("Unexpected dependence");
2625   case MemoryDepChecker::Dependence::Backward:
2626     R << "\nBackward loop carried data dependence.";
2627     break;
2628   case MemoryDepChecker::Dependence::ForwardButPreventsForwarding:
2629     R << "\nForward loop carried data dependence that prevents "
2630          "store-to-load forwarding.";
2631     break;
2632   case MemoryDepChecker::Dependence::BackwardVectorizableButPreventsForwarding:
2633     R << "\nBackward loop carried data dependence that prevents "
2634          "store-to-load forwarding.";
2635     break;
2636   case MemoryDepChecker::Dependence::IndirectUnsafe:
2637     R << "\nUnsafe indirect dependence.";
2638     break;
2639   case MemoryDepChecker::Dependence::Unknown:
2640     R << "\nUnknown data dependence.";
2641     break;
2642   }
2643 
2644   if (Instruction *I = Dep.getSource(*this)) {
2645     DebugLoc SourceLoc = I->getDebugLoc();
2646     if (auto *DD = dyn_cast_or_null<Instruction>(getPointerOperand(I)))
2647       SourceLoc = DD->getDebugLoc();
2648     if (SourceLoc)
2649       R << " Memory location is the same as accessed at "
2650         << ore::NV("Location", SourceLoc);
2651   }
2652 }
2653 
2654 bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
2655                                            DominatorTree *DT)  {
2656   assert(TheLoop->contains(BB) && "Unknown block used");
2657 
2658   // Blocks that do not dominate the latch need predication.
2659   BasicBlock* Latch = TheLoop->getLoopLatch();
2660   return !DT->dominates(BB, Latch);
2661 }
2662 
2663 OptimizationRemarkAnalysis &LoopAccessInfo::recordAnalysis(StringRef RemarkName,
2664                                                            Instruction *I) {
2665   assert(!Report && "Multiple reports generated");
2666 
2667   Value *CodeRegion = TheLoop->getHeader();
2668   DebugLoc DL = TheLoop->getStartLoc();
2669 
2670   if (I) {
2671     CodeRegion = I->getParent();
2672     // If there is no debug location attached to the instruction, revert back to
2673     // using the loop's.
2674     if (I->getDebugLoc())
2675       DL = I->getDebugLoc();
2676   }
2677 
2678   Report = std::make_unique<OptimizationRemarkAnalysis>(DEBUG_TYPE, RemarkName, DL,
2679                                                    CodeRegion);
2680   return *Report;
2681 }
2682 
2683 bool LoopAccessInfo::isInvariant(Value *V) const {
2684   auto *SE = PSE->getSE();
2685   // TODO: Is this really what we want? Even without FP SCEV, we may want some
2686   // trivially loop-invariant FP values to be considered invariant.
2687   if (!SE->isSCEVable(V->getType()))
2688     return false;
2689   const SCEV *S = SE->getSCEV(V);
2690   return SE->isLoopInvariant(S, TheLoop);
2691 }
2692 
2693 /// Find the operand of the GEP that should be checked for consecutive
2694 /// stores. This ignores trailing indices that have no effect on the final
2695 /// pointer.
2696 static unsigned getGEPInductionOperand(const GetElementPtrInst *Gep) {
2697   const DataLayout &DL = Gep->getModule()->getDataLayout();
2698   unsigned LastOperand = Gep->getNumOperands() - 1;
2699   TypeSize GEPAllocSize = DL.getTypeAllocSize(Gep->getResultElementType());
2700 
2701   // Walk backwards and try to peel off zeros.
2702   while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
2703     // Find the type we're currently indexing into.
2704     gep_type_iterator GEPTI = gep_type_begin(Gep);
2705     std::advance(GEPTI, LastOperand - 2);
2706 
2707     // If it's a type with the same allocation size as the result of the GEP we
2708     // can peel off the zero index.
2709     TypeSize ElemSize = GEPTI.isStruct()
2710                             ? DL.getTypeAllocSize(GEPTI.getIndexedType())
2711                             : GEPTI.getSequentialElementStride(DL);
2712     if (ElemSize != GEPAllocSize)
2713       break;
2714     --LastOperand;
2715   }
2716 
2717   return LastOperand;
2718 }
2719 
2720 /// If the argument is a GEP, then returns the operand identified by
2721 /// getGEPInductionOperand. However, if there is some other non-loop-invariant
2722 /// operand, it returns that instead.
2723 static Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
2724   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
2725   if (!GEP)
2726     return Ptr;
2727 
2728   unsigned InductionOperand = getGEPInductionOperand(GEP);
2729 
2730   // Check that all of the gep indices are uniform except for our induction
2731   // operand.
2732   for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
2733     if (i != InductionOperand &&
2734         !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
2735       return Ptr;
2736   return GEP->getOperand(InductionOperand);
2737 }
2738 
2739 /// If a value has only one user that is a CastInst, return it.
2740 static Value *getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
2741   Value *UniqueCast = nullptr;
2742   for (User *U : Ptr->users()) {
2743     CastInst *CI = dyn_cast<CastInst>(U);
2744     if (CI && CI->getType() == Ty) {
2745       if (!UniqueCast)
2746         UniqueCast = CI;
2747       else
2748         return nullptr;
2749     }
2750   }
2751   return UniqueCast;
2752 }
2753 
2754 /// Get the stride of a pointer access in a loop. Looks for symbolic
2755 /// strides "a[i*stride]". Returns the symbolic stride, or null otherwise.
2756 static const SCEV *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
2757   auto *PtrTy = dyn_cast<PointerType>(Ptr->getType());
2758   if (!PtrTy || PtrTy->isAggregateType())
2759     return nullptr;
2760 
2761   // Try to remove a gep instruction to make the pointer (actually index at this
2762   // point) easier analyzable. If OrigPtr is equal to Ptr we are analyzing the
2763   // pointer, otherwise, we are analyzing the index.
2764   Value *OrigPtr = Ptr;
2765 
2766   // The size of the pointer access.
2767   int64_t PtrAccessSize = 1;
2768 
2769   Ptr = stripGetElementPtr(Ptr, SE, Lp);
2770   const SCEV *V = SE->getSCEV(Ptr);
2771 
2772   if (Ptr != OrigPtr)
2773     // Strip off casts.
2774     while (const SCEVIntegralCastExpr *C = dyn_cast<SCEVIntegralCastExpr>(V))
2775       V = C->getOperand();
2776 
2777   const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
2778   if (!S)
2779     return nullptr;
2780 
2781   // If the pointer is invariant then there is no stride and it makes no
2782   // sense to add it here.
2783   if (Lp != S->getLoop())
2784     return nullptr;
2785 
2786   V = S->getStepRecurrence(*SE);
2787   if (!V)
2788     return nullptr;
2789 
2790   // Strip off the size of access multiplication if we are still analyzing the
2791   // pointer.
2792   if (OrigPtr == Ptr) {
2793     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
2794       if (M->getOperand(0)->getSCEVType() != scConstant)
2795         return nullptr;
2796 
2797       const APInt &APStepVal = cast<SCEVConstant>(M->getOperand(0))->getAPInt();
2798 
2799       // Huge step value - give up.
2800       if (APStepVal.getBitWidth() > 64)
2801         return nullptr;
2802 
2803       int64_t StepVal = APStepVal.getSExtValue();
2804       if (PtrAccessSize != StepVal)
2805         return nullptr;
2806       V = M->getOperand(1);
2807     }
2808   }
2809 
2810   // Note that the restriction after this loop invariant check are only
2811   // profitability restrictions.
2812   if (!SE->isLoopInvariant(V, Lp))
2813     return nullptr;
2814 
2815   // Look for the loop invariant symbolic value.
2816   const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
2817   if (!U) {
2818     const auto *C = dyn_cast<SCEVIntegralCastExpr>(V);
2819     if (!C)
2820       return nullptr;
2821     U = dyn_cast<SCEVUnknown>(C->getOperand());
2822     if (!U)
2823       return nullptr;
2824 
2825     // Match legacy behavior - this is not needed for correctness
2826     if (!getUniqueCastUse(U->getValue(), Lp, V->getType()))
2827       return nullptr;
2828   }
2829 
2830   return V;
2831 }
2832 
2833 void LoopAccessInfo::collectStridedAccess(Value *MemAccess) {
2834   Value *Ptr = getLoadStorePointerOperand(MemAccess);
2835   if (!Ptr)
2836     return;
2837 
2838   // Note: getStrideFromPointer is a *profitability* heuristic.  We
2839   // could broaden the scope of values returned here - to anything
2840   // which happens to be loop invariant and contributes to the
2841   // computation of an interesting IV - but we chose not to as we
2842   // don't have a cost model here, and broadening the scope exposes
2843   // far too many unprofitable cases.
2844   const SCEV *StrideExpr = getStrideFromPointer(Ptr, PSE->getSE(), TheLoop);
2845   if (!StrideExpr)
2846     return;
2847 
2848   LLVM_DEBUG(dbgs() << "LAA: Found a strided access that is a candidate for "
2849                        "versioning:");
2850   LLVM_DEBUG(dbgs() << "  Ptr: " << *Ptr << " Stride: " << *StrideExpr << "\n");
2851 
2852   if (!SpeculateUnitStride) {
2853     LLVM_DEBUG(dbgs() << "  Chose not to due to -laa-speculate-unit-stride\n");
2854     return;
2855   }
2856 
2857   // Avoid adding the "Stride == 1" predicate when we know that
2858   // Stride >= Trip-Count. Such a predicate will effectively optimize a single
2859   // or zero iteration loop, as Trip-Count <= Stride == 1.
2860   //
2861   // TODO: We are currently not making a very informed decision on when it is
2862   // beneficial to apply stride versioning. It might make more sense that the
2863   // users of this analysis (such as the vectorizer) will trigger it, based on
2864   // their specific cost considerations; For example, in cases where stride
2865   // versioning does  not help resolving memory accesses/dependences, the
2866   // vectorizer should evaluate the cost of the runtime test, and the benefit
2867   // of various possible stride specializations, considering the alternatives
2868   // of using gather/scatters (if available).
2869 
2870   const SCEV *BETakenCount = PSE->getBackedgeTakenCount();
2871 
2872   // Match the types so we can compare the stride and the BETakenCount.
2873   // The Stride can be positive/negative, so we sign extend Stride;
2874   // The backedgeTakenCount is non-negative, so we zero extend BETakenCount.
2875   const DataLayout &DL = TheLoop->getHeader()->getModule()->getDataLayout();
2876   uint64_t StrideTypeSizeBits = DL.getTypeSizeInBits(StrideExpr->getType());
2877   uint64_t BETypeSizeBits = DL.getTypeSizeInBits(BETakenCount->getType());
2878   const SCEV *CastedStride = StrideExpr;
2879   const SCEV *CastedBECount = BETakenCount;
2880   ScalarEvolution *SE = PSE->getSE();
2881   if (BETypeSizeBits >= StrideTypeSizeBits)
2882     CastedStride = SE->getNoopOrSignExtend(StrideExpr, BETakenCount->getType());
2883   else
2884     CastedBECount = SE->getZeroExtendExpr(BETakenCount, StrideExpr->getType());
2885   const SCEV *StrideMinusBETaken = SE->getMinusSCEV(CastedStride, CastedBECount);
2886   // Since TripCount == BackEdgeTakenCount + 1, checking:
2887   // "Stride >= TripCount" is equivalent to checking:
2888   // Stride - BETakenCount > 0
2889   if (SE->isKnownPositive(StrideMinusBETaken)) {
2890     LLVM_DEBUG(
2891         dbgs() << "LAA: Stride>=TripCount; No point in versioning as the "
2892                   "Stride==1 predicate will imply that the loop executes "
2893                   "at most once.\n");
2894     return;
2895   }
2896   LLVM_DEBUG(dbgs() << "LAA: Found a strided access that we can version.\n");
2897 
2898   // Strip back off the integer cast, and check that our result is a
2899   // SCEVUnknown as we expect.
2900   const SCEV *StrideBase = StrideExpr;
2901   if (const auto *C = dyn_cast<SCEVIntegralCastExpr>(StrideBase))
2902     StrideBase = C->getOperand();
2903   SymbolicStrides[Ptr] = cast<SCEVUnknown>(StrideBase);
2904 }
2905 
2906 LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
2907                                const TargetLibraryInfo *TLI, AAResults *AA,
2908                                DominatorTree *DT, LoopInfo *LI)
2909     : PSE(std::make_unique<PredicatedScalarEvolution>(*SE, *L)),
2910       PtrRtChecking(nullptr),
2911       DepChecker(std::make_unique<MemoryDepChecker>(*PSE, L)), TheLoop(L) {
2912   PtrRtChecking = std::make_unique<RuntimePointerChecking>(*DepChecker, SE);
2913   if (canAnalyzeLoop()) {
2914     analyzeLoop(AA, LI, TLI, DT);
2915   }
2916 }
2917 
2918 void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
2919   if (CanVecMem) {
2920     OS.indent(Depth) << "Memory dependences are safe";
2921     const MemoryDepChecker &DC = getDepChecker();
2922     if (!DC.isSafeForAnyVectorWidth())
2923       OS << " with a maximum safe vector width of "
2924          << DC.getMaxSafeVectorWidthInBits() << " bits";
2925     if (PtrRtChecking->Need)
2926       OS << " with run-time checks";
2927     OS << "\n";
2928   }
2929 
2930   if (HasConvergentOp)
2931     OS.indent(Depth) << "Has convergent operation in loop\n";
2932 
2933   if (Report)
2934     OS.indent(Depth) << "Report: " << Report->getMsg() << "\n";
2935 
2936   if (auto *Dependences = DepChecker->getDependences()) {
2937     OS.indent(Depth) << "Dependences:\n";
2938     for (const auto &Dep : *Dependences) {
2939       Dep.print(OS, Depth + 2, DepChecker->getMemoryInstructions());
2940       OS << "\n";
2941     }
2942   } else
2943     OS.indent(Depth) << "Too many dependences, not recorded\n";
2944 
2945   // List the pair of accesses need run-time checks to prove independence.
2946   PtrRtChecking->print(OS, Depth);
2947   OS << "\n";
2948 
2949   OS.indent(Depth) << "Non vectorizable stores to invariant address were "
2950                    << (HasDependenceInvolvingLoopInvariantAddress ? "" : "not ")
2951                    << "found in loop.\n";
2952 
2953   OS.indent(Depth) << "SCEV assumptions:\n";
2954   PSE->getPredicate().print(OS, Depth);
2955 
2956   OS << "\n";
2957 
2958   OS.indent(Depth) << "Expressions re-written:\n";
2959   PSE->print(OS, Depth);
2960 }
2961 
2962 const LoopAccessInfo &LoopAccessInfoManager::getInfo(Loop &L) {
2963   auto I = LoopAccessInfoMap.insert({&L, nullptr});
2964 
2965   if (I.second)
2966     I.first->second =
2967         std::make_unique<LoopAccessInfo>(&L, &SE, TLI, &AA, &DT, &LI);
2968 
2969   return *I.first->second;
2970 }
2971 
2972 bool LoopAccessInfoManager::invalidate(
2973     Function &F, const PreservedAnalyses &PA,
2974     FunctionAnalysisManager::Invalidator &Inv) {
2975   // Check whether our analysis is preserved.
2976   auto PAC = PA.getChecker<LoopAccessAnalysis>();
2977   if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<Function>>())
2978     // If not, give up now.
2979     return true;
2980 
2981   // Check whether the analyses we depend on became invalid for any reason.
2982   // Skip checking TargetLibraryAnalysis as it is immutable and can't become
2983   // invalid.
2984   return Inv.invalidate<AAManager>(F, PA) ||
2985          Inv.invalidate<ScalarEvolutionAnalysis>(F, PA) ||
2986          Inv.invalidate<LoopAnalysis>(F, PA) ||
2987          Inv.invalidate<DominatorTreeAnalysis>(F, PA);
2988 }
2989 
2990 LoopAccessInfoManager LoopAccessAnalysis::run(Function &F,
2991                                               FunctionAnalysisManager &FAM) {
2992   auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
2993   auto &AA = FAM.getResult<AAManager>(F);
2994   auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
2995   auto &LI = FAM.getResult<LoopAnalysis>(F);
2996   auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
2997   return LoopAccessInfoManager(SE, AA, DT, LI, &TLI);
2998 }
2999 
3000 AnalysisKey LoopAccessAnalysis::Key;
3001