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