1 //===- LoopAccessAnalysis.cpp - Loop Access Analysis Implementation --------==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // The implementation for the loop memory dependence that was originally
11 // developed for the loop vectorizer.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Analysis/LoopAccessAnalysis.h"
16 #include "llvm/Analysis/LoopInfo.h"
17 #include "llvm/Analysis/LoopPassManager.h"
18 #include "llvm/Analysis/OptimizationDiagnosticInfo.h"
19 #include "llvm/Analysis/ScalarEvolutionExpander.h"
20 #include "llvm/Analysis/TargetLibraryInfo.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/Analysis/VectorUtils.h"
23 #include "llvm/IR/Dominators.h"
24 #include "llvm/IR/IRBuilder.h"
25 #include "llvm/IR/PassManager.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/raw_ostream.h"
28 using namespace llvm;
29 
30 #define DEBUG_TYPE "loop-accesses"
31 
32 static cl::opt<unsigned, true>
33 VectorizationFactor("force-vector-width", cl::Hidden,
34                     cl::desc("Sets the SIMD width. Zero is autoselect."),
35                     cl::location(VectorizerParams::VectorizationFactor));
36 unsigned VectorizerParams::VectorizationFactor;
37 
38 static cl::opt<unsigned, true>
39 VectorizationInterleave("force-vector-interleave", cl::Hidden,
40                         cl::desc("Sets the vectorization interleave count. "
41                                  "Zero is autoselect."),
42                         cl::location(
43                             VectorizerParams::VectorizationInterleave));
44 unsigned VectorizerParams::VectorizationInterleave;
45 
46 static cl::opt<unsigned, true> RuntimeMemoryCheckThreshold(
47     "runtime-memory-check-threshold", cl::Hidden,
48     cl::desc("When performing memory disambiguation checks at runtime do not "
49              "generate more than this number of comparisons (default = 8)."),
50     cl::location(VectorizerParams::RuntimeMemoryCheckThreshold), cl::init(8));
51 unsigned VectorizerParams::RuntimeMemoryCheckThreshold;
52 
53 /// \brief The maximum iterations used to merge memory checks
54 static cl::opt<unsigned> MemoryCheckMergeThreshold(
55     "memory-check-merge-threshold", cl::Hidden,
56     cl::desc("Maximum number of comparisons done when trying to merge "
57              "runtime memory checks. (default = 100)"),
58     cl::init(100));
59 
60 /// Maximum SIMD width.
61 const unsigned VectorizerParams::MaxVectorWidth = 64;
62 
63 /// \brief We collect dependences up to this threshold.
64 static cl::opt<unsigned>
65     MaxDependences("max-dependences", cl::Hidden,
66                    cl::desc("Maximum number of dependences collected by "
67                             "loop-access analysis (default = 100)"),
68                    cl::init(100));
69 
70 /// This enables versioning on the strides of symbolically striding memory
71 /// accesses in code like the following.
72 ///   for (i = 0; i < N; ++i)
73 ///     A[i * Stride1] += B[i * Stride2] ...
74 ///
75 /// Will be roughly translated to
76 ///    if (Stride1 == 1 && Stride2 == 1) {
77 ///      for (i = 0; i < N; i+=4)
78 ///       A[i:i+3] += ...
79 ///    } else
80 ///      ...
81 static cl::opt<bool> EnableMemAccessVersioning(
82     "enable-mem-access-versioning", cl::init(true), cl::Hidden,
83     cl::desc("Enable symbolic stride memory access versioning"));
84 
85 /// \brief Enable store-to-load forwarding conflict detection. This option can
86 /// be disabled for correctness testing.
87 static cl::opt<bool> EnableForwardingConflictDetection(
88     "store-to-load-forwarding-conflict-detection", cl::Hidden,
89     cl::desc("Enable conflict detection in loop-access analysis"),
90     cl::init(true));
91 
92 bool VectorizerParams::isInterleaveForced() {
93   return ::VectorizationInterleave.getNumOccurrences() > 0;
94 }
95 
96 void LoopAccessReport::emitAnalysis(const LoopAccessReport &Message,
97                                     const Loop *TheLoop, const char *PassName,
98                                     OptimizationRemarkEmitter &ORE) {
99   DebugLoc DL = TheLoop->getStartLoc();
100   const Value *V = TheLoop->getHeader();
101   if (const Instruction *I = Message.getInstr()) {
102     DL = I->getDebugLoc();
103     V = I->getParent();
104   }
105   ORE.emitOptimizationRemarkAnalysis(PassName, DL, V, Message.str());
106 }
107 
108 Value *llvm::stripIntegerCast(Value *V) {
109   if (auto *CI = dyn_cast<CastInst>(V))
110     if (CI->getOperand(0)->getType()->isIntegerTy())
111       return CI->getOperand(0);
112   return V;
113 }
114 
115 const SCEV *llvm::replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE,
116                                             const ValueToValueMap &PtrToStride,
117                                             Value *Ptr, Value *OrigPtr) {
118   const SCEV *OrigSCEV = PSE.getSCEV(Ptr);
119 
120   // If there is an entry in the map return the SCEV of the pointer with the
121   // symbolic stride replaced by one.
122   ValueToValueMap::const_iterator SI =
123       PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
124   if (SI != PtrToStride.end()) {
125     Value *StrideVal = SI->second;
126 
127     // Strip casts.
128     StrideVal = stripIntegerCast(StrideVal);
129 
130     // Replace symbolic stride by one.
131     Value *One = ConstantInt::get(StrideVal->getType(), 1);
132     ValueToValueMap RewriteMap;
133     RewriteMap[StrideVal] = One;
134 
135     ScalarEvolution *SE = PSE.getSE();
136     const auto *U = cast<SCEVUnknown>(SE->getSCEV(StrideVal));
137     const auto *CT =
138         static_cast<const SCEVConstant *>(SE->getOne(StrideVal->getType()));
139 
140     PSE.addPredicate(*SE->getEqualPredicate(U, CT));
141     auto *Expr = PSE.getSCEV(Ptr);
142 
143     DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV << " by: " << *Expr
144                  << "\n");
145     return Expr;
146   }
147 
148   // Otherwise, just return the SCEV of the original pointer.
149   return OrigSCEV;
150 }
151 
152 /// Calculate Start and End points of memory access.
153 /// Let's assume A is the first access and B is a memory access on N-th loop
154 /// iteration. Then B is calculated as:
155 ///   B = A + Step*N .
156 /// Step value may be positive or negative.
157 /// N is a calculated back-edge taken count:
158 ///     N = (TripCount > 0) ? RoundDown(TripCount -1 , VF) : 0
159 /// Start and End points are calculated in the following way:
160 /// Start = UMIN(A, B) ; End = UMAX(A, B) + SizeOfElt,
161 /// where SizeOfElt is the size of single memory access in bytes.
162 ///
163 /// There is no conflict when the intervals are disjoint:
164 /// NoConflict = (P2.Start >= P1.End) || (P1.Start >= P2.End)
165 void RuntimePointerChecking::insert(Loop *Lp, Value *Ptr, bool WritePtr,
166                                     unsigned DepSetId, unsigned ASId,
167                                     const ValueToValueMap &Strides,
168                                     PredicatedScalarEvolution &PSE) {
169   // Get the stride replaced scev.
170   const SCEV *Sc = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
171   ScalarEvolution *SE = PSE.getSE();
172 
173   const SCEV *ScStart;
174   const SCEV *ScEnd;
175 
176   if (SE->isLoopInvariant(Sc, Lp))
177     ScStart = ScEnd = Sc;
178   else {
179     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
180     assert(AR && "Invalid addrec expression");
181     const SCEV *Ex = PSE.getBackedgeTakenCount();
182 
183     ScStart = AR->getStart();
184     ScEnd = AR->evaluateAtIteration(Ex, *SE);
185     const SCEV *Step = AR->getStepRecurrence(*SE);
186 
187     // For expressions with negative step, the upper bound is ScStart and the
188     // lower bound is ScEnd.
189     if (const auto *CStep = dyn_cast<SCEVConstant>(Step)) {
190       if (CStep->getValue()->isNegative())
191         std::swap(ScStart, ScEnd);
192     } else {
193       // Fallback case: the step is not constant, but we can still
194       // get the upper and lower bounds of the interval by using min/max
195       // expressions.
196       ScStart = SE->getUMinExpr(ScStart, ScEnd);
197       ScEnd = SE->getUMaxExpr(AR->getStart(), ScEnd);
198     }
199     // Add the size of the pointed element to ScEnd.
200     unsigned EltSize =
201       Ptr->getType()->getPointerElementType()->getScalarSizeInBits() / 8;
202     const SCEV *EltSizeSCEV = SE->getConstant(ScEnd->getType(), EltSize);
203     ScEnd = SE->getAddExpr(ScEnd, EltSizeSCEV);
204   }
205 
206   Pointers.emplace_back(Ptr, ScStart, ScEnd, WritePtr, DepSetId, ASId, Sc);
207 }
208 
209 SmallVector<RuntimePointerChecking::PointerCheck, 4>
210 RuntimePointerChecking::generateChecks() const {
211   SmallVector<PointerCheck, 4> Checks;
212 
213   for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
214     for (unsigned J = I + 1; J < CheckingGroups.size(); ++J) {
215       const RuntimePointerChecking::CheckingPtrGroup &CGI = CheckingGroups[I];
216       const RuntimePointerChecking::CheckingPtrGroup &CGJ = CheckingGroups[J];
217 
218       if (needsChecking(CGI, CGJ))
219         Checks.push_back(std::make_pair(&CGI, &CGJ));
220     }
221   }
222   return Checks;
223 }
224 
225 void RuntimePointerChecking::generateChecks(
226     MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
227   assert(Checks.empty() && "Checks is not empty");
228   groupChecks(DepCands, UseDependencies);
229   Checks = generateChecks();
230 }
231 
232 bool RuntimePointerChecking::needsChecking(const CheckingPtrGroup &M,
233                                            const CheckingPtrGroup &N) const {
234   for (unsigned I = 0, EI = M.Members.size(); EI != I; ++I)
235     for (unsigned J = 0, EJ = N.Members.size(); EJ != J; ++J)
236       if (needsChecking(M.Members[I], N.Members[J]))
237         return true;
238   return false;
239 }
240 
241 /// Compare \p I and \p J and return the minimum.
242 /// Return nullptr in case we couldn't find an answer.
243 static const SCEV *getMinFromExprs(const SCEV *I, const SCEV *J,
244                                    ScalarEvolution *SE) {
245   const SCEV *Diff = SE->getMinusSCEV(J, I);
246   const SCEVConstant *C = dyn_cast<const SCEVConstant>(Diff);
247 
248   if (!C)
249     return nullptr;
250   if (C->getValue()->isNegative())
251     return J;
252   return I;
253 }
254 
255 bool RuntimePointerChecking::CheckingPtrGroup::addPointer(unsigned Index) {
256   const SCEV *Start = RtCheck.Pointers[Index].Start;
257   const SCEV *End = RtCheck.Pointers[Index].End;
258 
259   // Compare the starts and ends with the known minimum and maximum
260   // of this set. We need to know how we compare against the min/max
261   // of the set in order to be able to emit memchecks.
262   const SCEV *Min0 = getMinFromExprs(Start, Low, RtCheck.SE);
263   if (!Min0)
264     return false;
265 
266   const SCEV *Min1 = getMinFromExprs(End, High, RtCheck.SE);
267   if (!Min1)
268     return false;
269 
270   // Update the low bound  expression if we've found a new min value.
271   if (Min0 == Start)
272     Low = Start;
273 
274   // Update the high bound expression if we've found a new max value.
275   if (Min1 != End)
276     High = End;
277 
278   Members.push_back(Index);
279   return true;
280 }
281 
282 void RuntimePointerChecking::groupChecks(
283     MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
284   // We build the groups from dependency candidates equivalence classes
285   // because:
286   //    - We know that pointers in the same equivalence class share
287   //      the same underlying object and therefore there is a chance
288   //      that we can compare pointers
289   //    - We wouldn't be able to merge two pointers for which we need
290   //      to emit a memcheck. The classes in DepCands are already
291   //      conveniently built such that no two pointers in the same
292   //      class need checking against each other.
293 
294   // We use the following (greedy) algorithm to construct the groups
295   // For every pointer in the equivalence class:
296   //   For each existing group:
297   //   - if the difference between this pointer and the min/max bounds
298   //     of the group is a constant, then make the pointer part of the
299   //     group and update the min/max bounds of that group as required.
300 
301   CheckingGroups.clear();
302 
303   // If we need to check two pointers to the same underlying object
304   // with a non-constant difference, we shouldn't perform any pointer
305   // grouping with those pointers. This is because we can easily get
306   // into cases where the resulting check would return false, even when
307   // the accesses are safe.
308   //
309   // The following example shows this:
310   // for (i = 0; i < 1000; ++i)
311   //   a[5000 + i * m] = a[i] + a[i + 9000]
312   //
313   // Here grouping gives a check of (5000, 5000 + 1000 * m) against
314   // (0, 10000) which is always false. However, if m is 1, there is no
315   // dependence. Not grouping the checks for a[i] and a[i + 9000] allows
316   // us to perform an accurate check in this case.
317   //
318   // The above case requires that we have an UnknownDependence between
319   // accesses to the same underlying object. This cannot happen unless
320   // ShouldRetryWithRuntimeCheck is set, and therefore UseDependencies
321   // is also false. In this case we will use the fallback path and create
322   // separate checking groups for all pointers.
323 
324   // If we don't have the dependency partitions, construct a new
325   // checking pointer group for each pointer. This is also required
326   // for correctness, because in this case we can have checking between
327   // pointers to the same underlying object.
328   if (!UseDependencies) {
329     for (unsigned I = 0; I < Pointers.size(); ++I)
330       CheckingGroups.push_back(CheckingPtrGroup(I, *this));
331     return;
332   }
333 
334   unsigned TotalComparisons = 0;
335 
336   DenseMap<Value *, unsigned> PositionMap;
337   for (unsigned Index = 0; Index < Pointers.size(); ++Index)
338     PositionMap[Pointers[Index].PointerValue] = Index;
339 
340   // We need to keep track of what pointers we've already seen so we
341   // don't process them twice.
342   SmallSet<unsigned, 2> Seen;
343 
344   // Go through all equivalence classes, get the "pointer check groups"
345   // and add them to the overall solution. We use the order in which accesses
346   // appear in 'Pointers' to enforce determinism.
347   for (unsigned I = 0; I < Pointers.size(); ++I) {
348     // We've seen this pointer before, and therefore already processed
349     // its equivalence class.
350     if (Seen.count(I))
351       continue;
352 
353     MemoryDepChecker::MemAccessInfo Access(Pointers[I].PointerValue,
354                                            Pointers[I].IsWritePtr);
355 
356     SmallVector<CheckingPtrGroup, 2> Groups;
357     auto LeaderI = DepCands.findValue(DepCands.getLeaderValue(Access));
358 
359     // Because DepCands is constructed by visiting accesses in the order in
360     // which they appear in alias sets (which is deterministic) and the
361     // iteration order within an equivalence class member is only dependent on
362     // the order in which unions and insertions are performed on the
363     // equivalence class, the iteration order is deterministic.
364     for (auto MI = DepCands.member_begin(LeaderI), ME = DepCands.member_end();
365          MI != ME; ++MI) {
366       unsigned Pointer = PositionMap[MI->getPointer()];
367       bool Merged = false;
368       // Mark this pointer as seen.
369       Seen.insert(Pointer);
370 
371       // Go through all the existing sets and see if we can find one
372       // which can include this pointer.
373       for (CheckingPtrGroup &Group : Groups) {
374         // Don't perform more than a certain amount of comparisons.
375         // This should limit the cost of grouping the pointers to something
376         // reasonable.  If we do end up hitting this threshold, the algorithm
377         // will create separate groups for all remaining pointers.
378         if (TotalComparisons > MemoryCheckMergeThreshold)
379           break;
380 
381         TotalComparisons++;
382 
383         if (Group.addPointer(Pointer)) {
384           Merged = true;
385           break;
386         }
387       }
388 
389       if (!Merged)
390         // We couldn't add this pointer to any existing set or the threshold
391         // for the number of comparisons has been reached. Create a new group
392         // to hold the current pointer.
393         Groups.push_back(CheckingPtrGroup(Pointer, *this));
394     }
395 
396     // We've computed the grouped checks for this partition.
397     // Save the results and continue with the next one.
398     std::copy(Groups.begin(), Groups.end(), std::back_inserter(CheckingGroups));
399   }
400 }
401 
402 bool RuntimePointerChecking::arePointersInSamePartition(
403     const SmallVectorImpl<int> &PtrToPartition, unsigned PtrIdx1,
404     unsigned PtrIdx2) {
405   return (PtrToPartition[PtrIdx1] != -1 &&
406           PtrToPartition[PtrIdx1] == PtrToPartition[PtrIdx2]);
407 }
408 
409 bool RuntimePointerChecking::needsChecking(unsigned I, unsigned J) const {
410   const PointerInfo &PointerI = Pointers[I];
411   const PointerInfo &PointerJ = Pointers[J];
412 
413   // No need to check if two readonly pointers intersect.
414   if (!PointerI.IsWritePtr && !PointerJ.IsWritePtr)
415     return false;
416 
417   // Only need to check pointers between two different dependency sets.
418   if (PointerI.DependencySetId == PointerJ.DependencySetId)
419     return false;
420 
421   // Only need to check pointers in the same alias set.
422   if (PointerI.AliasSetId != PointerJ.AliasSetId)
423     return false;
424 
425   return true;
426 }
427 
428 void RuntimePointerChecking::printChecks(
429     raw_ostream &OS, const SmallVectorImpl<PointerCheck> &Checks,
430     unsigned Depth) const {
431   unsigned N = 0;
432   for (const auto &Check : Checks) {
433     const auto &First = Check.first->Members, &Second = Check.second->Members;
434 
435     OS.indent(Depth) << "Check " << N++ << ":\n";
436 
437     OS.indent(Depth + 2) << "Comparing group (" << Check.first << "):\n";
438     for (unsigned K = 0; K < First.size(); ++K)
439       OS.indent(Depth + 2) << *Pointers[First[K]].PointerValue << "\n";
440 
441     OS.indent(Depth + 2) << "Against group (" << Check.second << "):\n";
442     for (unsigned K = 0; K < Second.size(); ++K)
443       OS.indent(Depth + 2) << *Pointers[Second[K]].PointerValue << "\n";
444   }
445 }
446 
447 void RuntimePointerChecking::print(raw_ostream &OS, unsigned Depth) const {
448 
449   OS.indent(Depth) << "Run-time memory checks:\n";
450   printChecks(OS, Checks, Depth);
451 
452   OS.indent(Depth) << "Grouped accesses:\n";
453   for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
454     const auto &CG = CheckingGroups[I];
455 
456     OS.indent(Depth + 2) << "Group " << &CG << ":\n";
457     OS.indent(Depth + 4) << "(Low: " << *CG.Low << " High: " << *CG.High
458                          << ")\n";
459     for (unsigned J = 0; J < CG.Members.size(); ++J) {
460       OS.indent(Depth + 6) << "Member: " << *Pointers[CG.Members[J]].Expr
461                            << "\n";
462     }
463   }
464 }
465 
466 namespace {
467 /// \brief Analyses memory accesses in a loop.
468 ///
469 /// Checks whether run time pointer checks are needed and builds sets for data
470 /// dependence checking.
471 class AccessAnalysis {
472 public:
473   /// \brief Read or write access location.
474   typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
475   typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
476 
477   AccessAnalysis(const DataLayout &Dl, AliasAnalysis *AA, LoopInfo *LI,
478                  MemoryDepChecker::DepCandidates &DA,
479                  PredicatedScalarEvolution &PSE)
480       : DL(Dl), AST(*AA), LI(LI), DepCands(DA), IsRTCheckAnalysisNeeded(false),
481         PSE(PSE) {}
482 
483   /// \brief Register a load  and whether it is only read from.
484   void addLoad(MemoryLocation &Loc, bool IsReadOnly) {
485     Value *Ptr = const_cast<Value*>(Loc.Ptr);
486     AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
487     Accesses.insert(MemAccessInfo(Ptr, false));
488     if (IsReadOnly)
489       ReadOnlyPtr.insert(Ptr);
490   }
491 
492   /// \brief Register a store.
493   void addStore(MemoryLocation &Loc) {
494     Value *Ptr = const_cast<Value*>(Loc.Ptr);
495     AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
496     Accesses.insert(MemAccessInfo(Ptr, true));
497   }
498 
499   /// \brief Check whether we can check the pointers at runtime for
500   /// non-intersection.
501   ///
502   /// Returns true if we need no check or if we do and we can generate them
503   /// (i.e. the pointers have computable bounds).
504   bool canCheckPtrAtRT(RuntimePointerChecking &RtCheck, ScalarEvolution *SE,
505                        Loop *TheLoop, const ValueToValueMap &Strides,
506                        bool ShouldCheckWrap = false);
507 
508   /// \brief Goes over all memory accesses, checks whether a RT check is needed
509   /// and builds sets of dependent accesses.
510   void buildDependenceSets() {
511     processMemAccesses();
512   }
513 
514   /// \brief Initial processing of memory accesses determined that we need to
515   /// perform dependency checking.
516   ///
517   /// Note that this can later be cleared if we retry memcheck analysis without
518   /// dependency checking (i.e. ShouldRetryWithRuntimeCheck).
519   bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
520 
521   /// We decided that no dependence analysis would be used.  Reset the state.
522   void resetDepChecks(MemoryDepChecker &DepChecker) {
523     CheckDeps.clear();
524     DepChecker.clearDependences();
525   }
526 
527   MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
528 
529 private:
530   typedef SetVector<MemAccessInfo> PtrAccessSet;
531 
532   /// \brief Go over all memory access and check whether runtime pointer checks
533   /// are needed and build sets of dependency check candidates.
534   void processMemAccesses();
535 
536   /// Set of all accesses.
537   PtrAccessSet Accesses;
538 
539   const DataLayout &DL;
540 
541   /// Set of accesses that need a further dependence check.
542   MemAccessInfoSet CheckDeps;
543 
544   /// Set of pointers that are read only.
545   SmallPtrSet<Value*, 16> ReadOnlyPtr;
546 
547   /// An alias set tracker to partition the access set by underlying object and
548   //intrinsic property (such as TBAA metadata).
549   AliasSetTracker AST;
550 
551   LoopInfo *LI;
552 
553   /// Sets of potentially dependent accesses - members of one set share an
554   /// underlying pointer. The set "CheckDeps" identfies which sets really need a
555   /// dependence check.
556   MemoryDepChecker::DepCandidates &DepCands;
557 
558   /// \brief Initial processing of memory accesses determined that we may need
559   /// to add memchecks.  Perform the analysis to determine the necessary checks.
560   ///
561   /// Note that, this is different from isDependencyCheckNeeded.  When we retry
562   /// memcheck analysis without dependency checking
563   /// (i.e. ShouldRetryWithRuntimeCheck), isDependencyCheckNeeded is cleared
564   /// while this remains set if we have potentially dependent accesses.
565   bool IsRTCheckAnalysisNeeded;
566 
567   /// The SCEV predicate containing all the SCEV-related assumptions.
568   PredicatedScalarEvolution &PSE;
569 };
570 
571 } // end anonymous namespace
572 
573 /// \brief Check whether a pointer can participate in a runtime bounds check.
574 static bool hasComputableBounds(PredicatedScalarEvolution &PSE,
575                                 const ValueToValueMap &Strides, Value *Ptr,
576                                 Loop *L) {
577   const SCEV *PtrScev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
578 
579   // The bounds for loop-invariant pointer is trivial.
580   if (PSE.getSE()->isLoopInvariant(PtrScev, L))
581     return true;
582 
583   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
584   if (!AR)
585     return false;
586 
587   return AR->isAffine();
588 }
589 
590 /// \brief Check whether a pointer address cannot wrap.
591 static bool isNoWrap(PredicatedScalarEvolution &PSE,
592                      const ValueToValueMap &Strides, Value *Ptr, Loop *L) {
593   const SCEV *PtrScev = PSE.getSCEV(Ptr);
594   if (PSE.getSE()->isLoopInvariant(PtrScev, L))
595     return true;
596 
597   int64_t Stride = getPtrStride(PSE, Ptr, L, Strides);
598   return Stride == 1;
599 }
600 
601 bool AccessAnalysis::canCheckPtrAtRT(RuntimePointerChecking &RtCheck,
602                                      ScalarEvolution *SE, Loop *TheLoop,
603                                      const ValueToValueMap &StridesMap,
604                                      bool ShouldCheckWrap) {
605   // Find pointers with computable bounds. We are going to use this information
606   // to place a runtime bound check.
607   bool CanDoRT = true;
608 
609   bool NeedRTCheck = false;
610   if (!IsRTCheckAnalysisNeeded) return true;
611 
612   bool IsDepCheckNeeded = isDependencyCheckNeeded();
613 
614   // We assign a consecutive id to access from different alias sets.
615   // Accesses between different groups doesn't need to be checked.
616   unsigned ASId = 1;
617   for (auto &AS : AST) {
618     int NumReadPtrChecks = 0;
619     int NumWritePtrChecks = 0;
620 
621     // We assign consecutive id to access from different dependence sets.
622     // Accesses within the same set don't need a runtime check.
623     unsigned RunningDepId = 1;
624     DenseMap<Value *, unsigned> DepSetId;
625 
626     for (auto A : AS) {
627       Value *Ptr = A.getValue();
628       bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
629       MemAccessInfo Access(Ptr, IsWrite);
630 
631       if (IsWrite)
632         ++NumWritePtrChecks;
633       else
634         ++NumReadPtrChecks;
635 
636       if (hasComputableBounds(PSE, StridesMap, Ptr, TheLoop) &&
637           // When we run after a failing dependency check we have to make sure
638           // we don't have wrapping pointers.
639           (!ShouldCheckWrap || isNoWrap(PSE, StridesMap, Ptr, TheLoop))) {
640         // The id of the dependence set.
641         unsigned DepId;
642 
643         if (IsDepCheckNeeded) {
644           Value *Leader = DepCands.getLeaderValue(Access).getPointer();
645           unsigned &LeaderId = DepSetId[Leader];
646           if (!LeaderId)
647             LeaderId = RunningDepId++;
648           DepId = LeaderId;
649         } else
650           // Each access has its own dependence set.
651           DepId = RunningDepId++;
652 
653         RtCheck.insert(TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap, PSE);
654 
655         DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
656       } else {
657         DEBUG(dbgs() << "LAA: Can't find bounds for ptr:" << *Ptr << '\n');
658         CanDoRT = false;
659       }
660     }
661 
662     // If we have at least two writes or one write and a read then we need to
663     // check them.  But there is no need to checks if there is only one
664     // dependence set for this alias set.
665     //
666     // Note that this function computes CanDoRT and NeedRTCheck independently.
667     // For example CanDoRT=false, NeedRTCheck=false means that we have a pointer
668     // for which we couldn't find the bounds but we don't actually need to emit
669     // any checks so it does not matter.
670     if (!(IsDepCheckNeeded && CanDoRT && RunningDepId == 2))
671       NeedRTCheck |= (NumWritePtrChecks >= 2 || (NumReadPtrChecks >= 1 &&
672                                                  NumWritePtrChecks >= 1));
673 
674     ++ASId;
675   }
676 
677   // If the pointers that we would use for the bounds comparison have different
678   // address spaces, assume the values aren't directly comparable, so we can't
679   // use them for the runtime check. We also have to assume they could
680   // overlap. In the future there should be metadata for whether address spaces
681   // are disjoint.
682   unsigned NumPointers = RtCheck.Pointers.size();
683   for (unsigned i = 0; i < NumPointers; ++i) {
684     for (unsigned j = i + 1; j < NumPointers; ++j) {
685       // Only need to check pointers between two different dependency sets.
686       if (RtCheck.Pointers[i].DependencySetId ==
687           RtCheck.Pointers[j].DependencySetId)
688        continue;
689       // Only need to check pointers in the same alias set.
690       if (RtCheck.Pointers[i].AliasSetId != RtCheck.Pointers[j].AliasSetId)
691         continue;
692 
693       Value *PtrI = RtCheck.Pointers[i].PointerValue;
694       Value *PtrJ = RtCheck.Pointers[j].PointerValue;
695 
696       unsigned ASi = PtrI->getType()->getPointerAddressSpace();
697       unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
698       if (ASi != ASj) {
699         DEBUG(dbgs() << "LAA: Runtime check would require comparison between"
700                        " different address spaces\n");
701         return false;
702       }
703     }
704   }
705 
706   if (NeedRTCheck && CanDoRT)
707     RtCheck.generateChecks(DepCands, IsDepCheckNeeded);
708 
709   DEBUG(dbgs() << "LAA: We need to do " << RtCheck.getNumberOfChecks()
710                << " pointer comparisons.\n");
711 
712   RtCheck.Need = NeedRTCheck;
713 
714   bool CanDoRTIfNeeded = !NeedRTCheck || CanDoRT;
715   if (!CanDoRTIfNeeded)
716     RtCheck.reset();
717   return CanDoRTIfNeeded;
718 }
719 
720 void AccessAnalysis::processMemAccesses() {
721   // We process the set twice: first we process read-write pointers, last we
722   // process read-only pointers. This allows us to skip dependence tests for
723   // read-only pointers.
724 
725   DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
726   DEBUG(dbgs() << "  AST: "; AST.dump());
727   DEBUG(dbgs() << "LAA:   Accesses(" << Accesses.size() << "):\n");
728   DEBUG({
729     for (auto A : Accesses)
730       dbgs() << "\t" << *A.getPointer() << " (" <<
731                 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
732                                          "read-only" : "read")) << ")\n";
733   });
734 
735   // The AliasSetTracker has nicely partitioned our pointers by metadata
736   // compatibility and potential for underlying-object overlap. As a result, we
737   // only need to check for potential pointer dependencies within each alias
738   // set.
739   for (auto &AS : AST) {
740     // Note that both the alias-set tracker and the alias sets themselves used
741     // linked lists internally and so the iteration order here is deterministic
742     // (matching the original instruction order within each set).
743 
744     bool SetHasWrite = false;
745 
746     // Map of pointers to last access encountered.
747     typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
748     UnderlyingObjToAccessMap ObjToLastAccess;
749 
750     // Set of access to check after all writes have been processed.
751     PtrAccessSet DeferredAccesses;
752 
753     // Iterate over each alias set twice, once to process read/write pointers,
754     // and then to process read-only pointers.
755     for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
756       bool UseDeferred = SetIteration > 0;
757       PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
758 
759       for (auto AV : AS) {
760         Value *Ptr = AV.getValue();
761 
762         // For a single memory access in AliasSetTracker, Accesses may contain
763         // both read and write, and they both need to be handled for CheckDeps.
764         for (auto AC : S) {
765           if (AC.getPointer() != Ptr)
766             continue;
767 
768           bool IsWrite = AC.getInt();
769 
770           // If we're using the deferred access set, then it contains only
771           // reads.
772           bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
773           if (UseDeferred && !IsReadOnlyPtr)
774             continue;
775           // Otherwise, the pointer must be in the PtrAccessSet, either as a
776           // read or a write.
777           assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
778                   S.count(MemAccessInfo(Ptr, false))) &&
779                  "Alias-set pointer not in the access set?");
780 
781           MemAccessInfo Access(Ptr, IsWrite);
782           DepCands.insert(Access);
783 
784           // Memorize read-only pointers for later processing and skip them in
785           // the first round (they need to be checked after we have seen all
786           // write pointers). Note: we also mark pointer that are not
787           // consecutive as "read-only" pointers (so that we check
788           // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
789           if (!UseDeferred && IsReadOnlyPtr) {
790             DeferredAccesses.insert(Access);
791             continue;
792           }
793 
794           // If this is a write - check other reads and writes for conflicts. If
795           // this is a read only check other writes for conflicts (but only if
796           // there is no other write to the ptr - this is an optimization to
797           // catch "a[i] = a[i] + " without having to do a dependence check).
798           if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
799             CheckDeps.insert(Access);
800             IsRTCheckAnalysisNeeded = true;
801           }
802 
803           if (IsWrite)
804             SetHasWrite = true;
805 
806           // Create sets of pointers connected by a shared alias set and
807           // underlying object.
808           typedef SmallVector<Value *, 16> ValueVector;
809           ValueVector TempObjects;
810 
811           GetUnderlyingObjects(Ptr, TempObjects, DL, LI);
812           DEBUG(dbgs() << "Underlying objects for pointer " << *Ptr << "\n");
813           for (Value *UnderlyingObj : TempObjects) {
814             // nullptr never alias, don't join sets for pointer that have "null"
815             // in their UnderlyingObjects list.
816             if (isa<ConstantPointerNull>(UnderlyingObj))
817               continue;
818 
819             UnderlyingObjToAccessMap::iterator Prev =
820                 ObjToLastAccess.find(UnderlyingObj);
821             if (Prev != ObjToLastAccess.end())
822               DepCands.unionSets(Access, Prev->second);
823 
824             ObjToLastAccess[UnderlyingObj] = Access;
825             DEBUG(dbgs() << "  " << *UnderlyingObj << "\n");
826           }
827         }
828       }
829     }
830   }
831 }
832 
833 static bool isInBoundsGep(Value *Ptr) {
834   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
835     return GEP->isInBounds();
836   return false;
837 }
838 
839 /// \brief Return true if an AddRec pointer \p Ptr is unsigned non-wrapping,
840 /// i.e. monotonically increasing/decreasing.
841 static bool isNoWrapAddRec(Value *Ptr, const SCEVAddRecExpr *AR,
842                            PredicatedScalarEvolution &PSE, const Loop *L) {
843   // FIXME: This should probably only return true for NUW.
844   if (AR->getNoWrapFlags(SCEV::NoWrapMask))
845     return true;
846 
847   // Scalar evolution does not propagate the non-wrapping flags to values that
848   // are derived from a non-wrapping induction variable because non-wrapping
849   // could be flow-sensitive.
850   //
851   // Look through the potentially overflowing instruction to try to prove
852   // non-wrapping for the *specific* value of Ptr.
853 
854   // The arithmetic implied by an inbounds GEP can't overflow.
855   auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
856   if (!GEP || !GEP->isInBounds())
857     return false;
858 
859   // Make sure there is only one non-const index and analyze that.
860   Value *NonConstIndex = nullptr;
861   for (Value *Index : make_range(GEP->idx_begin(), GEP->idx_end()))
862     if (!isa<ConstantInt>(Index)) {
863       if (NonConstIndex)
864         return false;
865       NonConstIndex = Index;
866     }
867   if (!NonConstIndex)
868     // The recurrence is on the pointer, ignore for now.
869     return false;
870 
871   // The index in GEP is signed.  It is non-wrapping if it's derived from a NSW
872   // AddRec using a NSW operation.
873   if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(NonConstIndex))
874     if (OBO->hasNoSignedWrap() &&
875         // Assume constant for other the operand so that the AddRec can be
876         // easily found.
877         isa<ConstantInt>(OBO->getOperand(1))) {
878       auto *OpScev = PSE.getSCEV(OBO->getOperand(0));
879 
880       if (auto *OpAR = dyn_cast<SCEVAddRecExpr>(OpScev))
881         return OpAR->getLoop() == L && OpAR->getNoWrapFlags(SCEV::FlagNSW);
882     }
883 
884   return false;
885 }
886 
887 /// \brief Check whether the access through \p Ptr has a constant stride.
888 int64_t llvm::getPtrStride(PredicatedScalarEvolution &PSE, Value *Ptr,
889                            const Loop *Lp, const ValueToValueMap &StridesMap,
890                            bool Assume) {
891   Type *Ty = Ptr->getType();
892   assert(Ty->isPointerTy() && "Unexpected non-ptr");
893 
894   // Make sure that the pointer does not point to aggregate types.
895   auto *PtrTy = cast<PointerType>(Ty);
896   if (PtrTy->getElementType()->isAggregateType()) {
897     DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type" << *Ptr
898                  << "\n");
899     return 0;
900   }
901 
902   const SCEV *PtrScev = replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr);
903 
904   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
905   if (Assume && !AR)
906     AR = PSE.getAsAddRec(Ptr);
907 
908   if (!AR) {
909     DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer " << *Ptr
910                  << " SCEV: " << *PtrScev << "\n");
911     return 0;
912   }
913 
914   // The accesss function must stride over the innermost loop.
915   if (Lp != AR->getLoop()) {
916     DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " <<
917           *Ptr << " SCEV: " << *AR << "\n");
918     return 0;
919   }
920 
921   // The address calculation must not wrap. Otherwise, a dependence could be
922   // inverted.
923   // An inbounds getelementptr that is a AddRec with a unit stride
924   // cannot wrap per definition. The unit stride requirement is checked later.
925   // An getelementptr without an inbounds attribute and unit stride would have
926   // to access the pointer value "0" which is undefined behavior in address
927   // space 0, therefore we can also vectorize this case.
928   bool IsInBoundsGEP = isInBoundsGep(Ptr);
929   bool IsNoWrapAddRec =
930       PSE.hasNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW) ||
931       isNoWrapAddRec(Ptr, AR, PSE, Lp);
932   bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
933   if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
934     if (Assume) {
935       PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
936       IsNoWrapAddRec = true;
937       DEBUG(dbgs() << "LAA: Pointer may wrap in the address space:\n"
938                    << "LAA:   Pointer: " << *Ptr << "\n"
939                    << "LAA:   SCEV: " << *AR << "\n"
940                    << "LAA:   Added an overflow assumption\n");
941     } else {
942       DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
943                    << *Ptr << " SCEV: " << *AR << "\n");
944       return 0;
945     }
946   }
947 
948   // Check the step is constant.
949   const SCEV *Step = AR->getStepRecurrence(*PSE.getSE());
950 
951   // Calculate the pointer stride and check if it is constant.
952   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
953   if (!C) {
954     DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr <<
955           " SCEV: " << *AR << "\n");
956     return 0;
957   }
958 
959   auto &DL = Lp->getHeader()->getModule()->getDataLayout();
960   int64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
961   const APInt &APStepVal = C->getAPInt();
962 
963   // Huge step value - give up.
964   if (APStepVal.getBitWidth() > 64)
965     return 0;
966 
967   int64_t StepVal = APStepVal.getSExtValue();
968 
969   // Strided access.
970   int64_t Stride = StepVal / Size;
971   int64_t Rem = StepVal % Size;
972   if (Rem)
973     return 0;
974 
975   // If the SCEV could wrap but we have an inbounds gep with a unit stride we
976   // know we can't "wrap around the address space". In case of address space
977   // zero we know that this won't happen without triggering undefined behavior.
978   if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
979       Stride != 1 && Stride != -1) {
980     if (Assume) {
981       // We can avoid this case by adding a run-time check.
982       DEBUG(dbgs() << "LAA: Non unit strided pointer which is not either "
983                    << "inbouds or in address space 0 may wrap:\n"
984                    << "LAA:   Pointer: " << *Ptr << "\n"
985                    << "LAA:   SCEV: " << *AR << "\n"
986                    << "LAA:   Added an overflow assumption\n");
987       PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
988     } else
989       return 0;
990   }
991 
992   return Stride;
993 }
994 
995 /// Take the pointer operand from the Load/Store instruction.
996 /// Returns NULL if this is not a valid Load/Store instruction.
997 static Value *getPointerOperand(Value *I) {
998   if (auto *LI = dyn_cast<LoadInst>(I))
999     return LI->getPointerOperand();
1000   if (auto *SI = dyn_cast<StoreInst>(I))
1001     return SI->getPointerOperand();
1002   return nullptr;
1003 }
1004 
1005 /// Take the address space operand from the Load/Store instruction.
1006 /// Returns -1 if this is not a valid Load/Store instruction.
1007 static unsigned getAddressSpaceOperand(Value *I) {
1008   if (LoadInst *L = dyn_cast<LoadInst>(I))
1009     return L->getPointerAddressSpace();
1010   if (StoreInst *S = dyn_cast<StoreInst>(I))
1011     return S->getPointerAddressSpace();
1012   return -1;
1013 }
1014 
1015 /// Returns true if the memory operations \p A and \p B are consecutive.
1016 bool llvm::isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL,
1017                                ScalarEvolution &SE, bool CheckType) {
1018   Value *PtrA = getPointerOperand(A);
1019   Value *PtrB = getPointerOperand(B);
1020   unsigned ASA = getAddressSpaceOperand(A);
1021   unsigned ASB = getAddressSpaceOperand(B);
1022 
1023   // Check that the address spaces match and that the pointers are valid.
1024   if (!PtrA || !PtrB || (ASA != ASB))
1025     return false;
1026 
1027   // Make sure that A and B are different pointers.
1028   if (PtrA == PtrB)
1029     return false;
1030 
1031   // Make sure that A and B have the same type if required.
1032   if (CheckType && PtrA->getType() != PtrB->getType())
1033     return false;
1034 
1035   unsigned PtrBitWidth = DL.getPointerSizeInBits(ASA);
1036   Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1037   APInt Size(PtrBitWidth, DL.getTypeStoreSize(Ty));
1038 
1039   APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1040   PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetA);
1041   PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetB);
1042 
1043   //  OffsetDelta = OffsetB - OffsetA;
1044   const SCEV *OffsetSCEVA = SE.getConstant(OffsetA);
1045   const SCEV *OffsetSCEVB = SE.getConstant(OffsetB);
1046   const SCEV *OffsetDeltaSCEV = SE.getMinusSCEV(OffsetSCEVB, OffsetSCEVA);
1047   const SCEVConstant *OffsetDeltaC = dyn_cast<SCEVConstant>(OffsetDeltaSCEV);
1048   const APInt &OffsetDelta = OffsetDeltaC->getAPInt();
1049   // Check if they are based on the same pointer. That makes the offsets
1050   // sufficient.
1051   if (PtrA == PtrB)
1052     return OffsetDelta == Size;
1053 
1054   // Compute the necessary base pointer delta to have the necessary final delta
1055   // equal to the size.
1056   // BaseDelta = Size - OffsetDelta;
1057   const SCEV *SizeSCEV = SE.getConstant(Size);
1058   const SCEV *BaseDelta = SE.getMinusSCEV(SizeSCEV, OffsetDeltaSCEV);
1059 
1060   // Otherwise compute the distance with SCEV between the base pointers.
1061   const SCEV *PtrSCEVA = SE.getSCEV(PtrA);
1062   const SCEV *PtrSCEVB = SE.getSCEV(PtrB);
1063   const SCEV *X = SE.getAddExpr(PtrSCEVA, BaseDelta);
1064   return X == PtrSCEVB;
1065 }
1066 
1067 bool MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
1068   switch (Type) {
1069   case NoDep:
1070   case Forward:
1071   case BackwardVectorizable:
1072     return true;
1073 
1074   case Unknown:
1075   case ForwardButPreventsForwarding:
1076   case Backward:
1077   case BackwardVectorizableButPreventsForwarding:
1078     return false;
1079   }
1080   llvm_unreachable("unexpected DepType!");
1081 }
1082 
1083 bool MemoryDepChecker::Dependence::isBackward() const {
1084   switch (Type) {
1085   case NoDep:
1086   case Forward:
1087   case ForwardButPreventsForwarding:
1088   case Unknown:
1089     return false;
1090 
1091   case BackwardVectorizable:
1092   case Backward:
1093   case BackwardVectorizableButPreventsForwarding:
1094     return true;
1095   }
1096   llvm_unreachable("unexpected DepType!");
1097 }
1098 
1099 bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
1100   return isBackward() || Type == Unknown;
1101 }
1102 
1103 bool MemoryDepChecker::Dependence::isForward() const {
1104   switch (Type) {
1105   case Forward:
1106   case ForwardButPreventsForwarding:
1107     return true;
1108 
1109   case NoDep:
1110   case Unknown:
1111   case BackwardVectorizable:
1112   case Backward:
1113   case BackwardVectorizableButPreventsForwarding:
1114     return false;
1115   }
1116   llvm_unreachable("unexpected DepType!");
1117 }
1118 
1119 bool MemoryDepChecker::couldPreventStoreLoadForward(uint64_t Distance,
1120                                                     uint64_t TypeByteSize) {
1121   // If loads occur at a distance that is not a multiple of a feasible vector
1122   // factor store-load forwarding does not take place.
1123   // Positive dependences might cause troubles because vectorizing them might
1124   // prevent store-load forwarding making vectorized code run a lot slower.
1125   //   a[i] = a[i-3] ^ a[i-8];
1126   //   The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
1127   //   hence on your typical architecture store-load forwarding does not take
1128   //   place. Vectorizing in such cases does not make sense.
1129   // Store-load forwarding distance.
1130 
1131   // After this many iterations store-to-load forwarding conflicts should not
1132   // cause any slowdowns.
1133   const uint64_t NumItersForStoreLoadThroughMemory = 8 * TypeByteSize;
1134   // Maximum vector factor.
1135   uint64_t MaxVFWithoutSLForwardIssues = std::min(
1136       VectorizerParams::MaxVectorWidth * TypeByteSize, MaxSafeDepDistBytes);
1137 
1138   // Compute the smallest VF at which the store and load would be misaligned.
1139   for (uint64_t VF = 2 * TypeByteSize; VF <= MaxVFWithoutSLForwardIssues;
1140        VF *= 2) {
1141     // If the number of vector iteration between the store and the load are
1142     // small we could incur conflicts.
1143     if (Distance % VF && Distance / VF < NumItersForStoreLoadThroughMemory) {
1144       MaxVFWithoutSLForwardIssues = (VF >>= 1);
1145       break;
1146     }
1147   }
1148 
1149   if (MaxVFWithoutSLForwardIssues < 2 * TypeByteSize) {
1150     DEBUG(dbgs() << "LAA: Distance " << Distance
1151                  << " that could cause a store-load forwarding conflict\n");
1152     return true;
1153   }
1154 
1155   if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
1156       MaxVFWithoutSLForwardIssues !=
1157           VectorizerParams::MaxVectorWidth * TypeByteSize)
1158     MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
1159   return false;
1160 }
1161 
1162 /// \brief Check the dependence for two accesses with the same stride \p Stride.
1163 /// \p Distance is the positive distance and \p TypeByteSize is type size in
1164 /// bytes.
1165 ///
1166 /// \returns true if they are independent.
1167 static bool areStridedAccessesIndependent(uint64_t Distance, uint64_t Stride,
1168                                           uint64_t TypeByteSize) {
1169   assert(Stride > 1 && "The stride must be greater than 1");
1170   assert(TypeByteSize > 0 && "The type size in byte must be non-zero");
1171   assert(Distance > 0 && "The distance must be non-zero");
1172 
1173   // Skip if the distance is not multiple of type byte size.
1174   if (Distance % TypeByteSize)
1175     return false;
1176 
1177   uint64_t ScaledDist = Distance / TypeByteSize;
1178 
1179   // No dependence if the scaled distance is not multiple of the stride.
1180   // E.g.
1181   //      for (i = 0; i < 1024 ; i += 4)
1182   //        A[i+2] = A[i] + 1;
1183   //
1184   // Two accesses in memory (scaled distance is 2, stride is 4):
1185   //     | A[0] |      |      |      | A[4] |      |      |      |
1186   //     |      |      | A[2] |      |      |      | A[6] |      |
1187   //
1188   // E.g.
1189   //      for (i = 0; i < 1024 ; i += 3)
1190   //        A[i+4] = A[i] + 1;
1191   //
1192   // Two accesses in memory (scaled distance is 4, stride is 3):
1193   //     | A[0] |      |      | A[3] |      |      | A[6] |      |      |
1194   //     |      |      |      |      | A[4] |      |      | A[7] |      |
1195   return ScaledDist % Stride;
1196 }
1197 
1198 MemoryDepChecker::Dependence::DepType
1199 MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
1200                               const MemAccessInfo &B, unsigned BIdx,
1201                               const ValueToValueMap &Strides) {
1202   assert (AIdx < BIdx && "Must pass arguments in program order");
1203 
1204   Value *APtr = A.getPointer();
1205   Value *BPtr = B.getPointer();
1206   bool AIsWrite = A.getInt();
1207   bool BIsWrite = B.getInt();
1208 
1209   // Two reads are independent.
1210   if (!AIsWrite && !BIsWrite)
1211     return Dependence::NoDep;
1212 
1213   // We cannot check pointers in different address spaces.
1214   if (APtr->getType()->getPointerAddressSpace() !=
1215       BPtr->getType()->getPointerAddressSpace())
1216     return Dependence::Unknown;
1217 
1218   int64_t StrideAPtr = getPtrStride(PSE, APtr, InnermostLoop, Strides, true);
1219   int64_t StrideBPtr = getPtrStride(PSE, BPtr, InnermostLoop, Strides, true);
1220 
1221   const SCEV *Src = PSE.getSCEV(APtr);
1222   const SCEV *Sink = PSE.getSCEV(BPtr);
1223 
1224   // If the induction step is negative we have to invert source and sink of the
1225   // dependence.
1226   if (StrideAPtr < 0) {
1227     std::swap(APtr, BPtr);
1228     std::swap(Src, Sink);
1229     std::swap(AIsWrite, BIsWrite);
1230     std::swap(AIdx, BIdx);
1231     std::swap(StrideAPtr, StrideBPtr);
1232   }
1233 
1234   const SCEV *Dist = PSE.getSE()->getMinusSCEV(Sink, Src);
1235 
1236   DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
1237                << "(Induction step: " << StrideAPtr << ")\n");
1238   DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
1239                << *InstMap[BIdx] << ": " << *Dist << "\n");
1240 
1241   // Need accesses with constant stride. We don't want to vectorize
1242   // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
1243   // the address space.
1244   if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
1245     DEBUG(dbgs() << "Pointer access with non-constant stride\n");
1246     return Dependence::Unknown;
1247   }
1248 
1249   const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
1250   if (!C) {
1251     DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
1252     ShouldRetryWithRuntimeCheck = true;
1253     return Dependence::Unknown;
1254   }
1255 
1256   Type *ATy = APtr->getType()->getPointerElementType();
1257   Type *BTy = BPtr->getType()->getPointerElementType();
1258   auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
1259   uint64_t TypeByteSize = DL.getTypeAllocSize(ATy);
1260 
1261   const APInt &Val = C->getAPInt();
1262   int64_t Distance = Val.getSExtValue();
1263   uint64_t Stride = std::abs(StrideAPtr);
1264 
1265   // Attempt to prove strided accesses independent.
1266   if (std::abs(Distance) > 0 && Stride > 1 && ATy == BTy &&
1267       areStridedAccessesIndependent(std::abs(Distance), Stride, TypeByteSize)) {
1268     DEBUG(dbgs() << "LAA: Strided accesses are independent\n");
1269     return Dependence::NoDep;
1270   }
1271 
1272   // Negative distances are not plausible dependencies.
1273   if (Val.isNegative()) {
1274     bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
1275     if (IsTrueDataDependence && EnableForwardingConflictDetection &&
1276         (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
1277          ATy != BTy)) {
1278       DEBUG(dbgs() << "LAA: Forward but may prevent st->ld forwarding\n");
1279       return Dependence::ForwardButPreventsForwarding;
1280     }
1281 
1282     DEBUG(dbgs() << "LAA: Dependence is negative\n");
1283     return Dependence::Forward;
1284   }
1285 
1286   // Write to the same location with the same size.
1287   // Could be improved to assert type sizes are the same (i32 == float, etc).
1288   if (Val == 0) {
1289     if (ATy == BTy)
1290       return Dependence::Forward;
1291     DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n");
1292     return Dependence::Unknown;
1293   }
1294 
1295   assert(Val.isStrictlyPositive() && "Expect a positive value");
1296 
1297   if (ATy != BTy) {
1298     DEBUG(dbgs() <<
1299           "LAA: ReadWrite-Write positive dependency with different types\n");
1300     return Dependence::Unknown;
1301   }
1302 
1303   // Bail out early if passed-in parameters make vectorization not feasible.
1304   unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
1305                            VectorizerParams::VectorizationFactor : 1);
1306   unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
1307                            VectorizerParams::VectorizationInterleave : 1);
1308   // The minimum number of iterations for a vectorized/unrolled version.
1309   unsigned MinNumIter = std::max(ForcedFactor * ForcedUnroll, 2U);
1310 
1311   // It's not vectorizable if the distance is smaller than the minimum distance
1312   // needed for a vectroized/unrolled version. Vectorizing one iteration in
1313   // front needs TypeByteSize * Stride. Vectorizing the last iteration needs
1314   // TypeByteSize (No need to plus the last gap distance).
1315   //
1316   // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1317   //      foo(int *A) {
1318   //        int *B = (int *)((char *)A + 14);
1319   //        for (i = 0 ; i < 1024 ; i += 2)
1320   //          B[i] = A[i] + 1;
1321   //      }
1322   //
1323   // Two accesses in memory (stride is 2):
1324   //     | A[0] |      | A[2] |      | A[4] |      | A[6] |      |
1325   //                              | B[0] |      | B[2] |      | B[4] |
1326   //
1327   // Distance needs for vectorizing iterations except the last iteration:
1328   // 4 * 2 * (MinNumIter - 1). Distance needs for the last iteration: 4.
1329   // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4.
1330   //
1331   // If MinNumIter is 2, it is vectorizable as the minimum distance needed is
1332   // 12, which is less than distance.
1333   //
1334   // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4),
1335   // the minimum distance needed is 28, which is greater than distance. It is
1336   // not safe to do vectorization.
1337   uint64_t MinDistanceNeeded =
1338       TypeByteSize * Stride * (MinNumIter - 1) + TypeByteSize;
1339   if (MinDistanceNeeded > static_cast<uint64_t>(Distance)) {
1340     DEBUG(dbgs() << "LAA: Failure because of positive distance " << Distance
1341                  << '\n');
1342     return Dependence::Backward;
1343   }
1344 
1345   // Unsafe if the minimum distance needed is greater than max safe distance.
1346   if (MinDistanceNeeded > MaxSafeDepDistBytes) {
1347     DEBUG(dbgs() << "LAA: Failure because it needs at least "
1348                  << MinDistanceNeeded << " size in bytes");
1349     return Dependence::Backward;
1350   }
1351 
1352   // Positive distance bigger than max vectorization factor.
1353   // FIXME: Should use max factor instead of max distance in bytes, which could
1354   // not handle different types.
1355   // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1356   //      void foo (int *A, char *B) {
1357   //        for (unsigned i = 0; i < 1024; i++) {
1358   //          A[i+2] = A[i] + 1;
1359   //          B[i+2] = B[i] + 1;
1360   //        }
1361   //      }
1362   //
1363   // This case is currently unsafe according to the max safe distance. If we
1364   // analyze the two accesses on array B, the max safe dependence distance
1365   // is 2. Then we analyze the accesses on array A, the minimum distance needed
1366   // is 8, which is less than 2 and forbidden vectorization, But actually
1367   // both A and B could be vectorized by 2 iterations.
1368   MaxSafeDepDistBytes =
1369       std::min(static_cast<uint64_t>(Distance), MaxSafeDepDistBytes);
1370 
1371   bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
1372   if (IsTrueDataDependence && EnableForwardingConflictDetection &&
1373       couldPreventStoreLoadForward(Distance, TypeByteSize))
1374     return Dependence::BackwardVectorizableButPreventsForwarding;
1375 
1376   DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue()
1377                << " with max VF = "
1378                << MaxSafeDepDistBytes / (TypeByteSize * Stride) << '\n');
1379 
1380   return Dependence::BackwardVectorizable;
1381 }
1382 
1383 bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets,
1384                                    MemAccessInfoSet &CheckDeps,
1385                                    const ValueToValueMap &Strides) {
1386 
1387   MaxSafeDepDistBytes = -1;
1388   while (!CheckDeps.empty()) {
1389     MemAccessInfo CurAccess = *CheckDeps.begin();
1390 
1391     // Get the relevant memory access set.
1392     EquivalenceClasses<MemAccessInfo>::iterator I =
1393       AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
1394 
1395     // Check accesses within this set.
1396     EquivalenceClasses<MemAccessInfo>::member_iterator AI =
1397         AccessSets.member_begin(I);
1398     EquivalenceClasses<MemAccessInfo>::member_iterator AE =
1399         AccessSets.member_end();
1400 
1401     // Check every access pair.
1402     while (AI != AE) {
1403       CheckDeps.erase(*AI);
1404       EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
1405       while (OI != AE) {
1406         // Check every accessing instruction pair in program order.
1407         for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
1408              I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
1409           for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
1410                I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
1411             auto A = std::make_pair(&*AI, *I1);
1412             auto B = std::make_pair(&*OI, *I2);
1413 
1414             assert(*I1 != *I2);
1415             if (*I1 > *I2)
1416               std::swap(A, B);
1417 
1418             Dependence::DepType Type =
1419                 isDependent(*A.first, A.second, *B.first, B.second, Strides);
1420             SafeForVectorization &= Dependence::isSafeForVectorization(Type);
1421 
1422             // Gather dependences unless we accumulated MaxDependences
1423             // dependences.  In that case return as soon as we find the first
1424             // unsafe dependence.  This puts a limit on this quadratic
1425             // algorithm.
1426             if (RecordDependences) {
1427               if (Type != Dependence::NoDep)
1428                 Dependences.push_back(Dependence(A.second, B.second, Type));
1429 
1430               if (Dependences.size() >= MaxDependences) {
1431                 RecordDependences = false;
1432                 Dependences.clear();
1433                 DEBUG(dbgs() << "Too many dependences, stopped recording\n");
1434               }
1435             }
1436             if (!RecordDependences && !SafeForVectorization)
1437               return false;
1438           }
1439         ++OI;
1440       }
1441       AI++;
1442     }
1443   }
1444 
1445   DEBUG(dbgs() << "Total Dependences: " << Dependences.size() << "\n");
1446   return SafeForVectorization;
1447 }
1448 
1449 SmallVector<Instruction *, 4>
1450 MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const {
1451   MemAccessInfo Access(Ptr, isWrite);
1452   auto &IndexVector = Accesses.find(Access)->second;
1453 
1454   SmallVector<Instruction *, 4> Insts;
1455   transform(IndexVector,
1456                  std::back_inserter(Insts),
1457                  [&](unsigned Idx) { return this->InstMap[Idx]; });
1458   return Insts;
1459 }
1460 
1461 const char *MemoryDepChecker::Dependence::DepName[] = {
1462     "NoDep", "Unknown", "Forward", "ForwardButPreventsForwarding", "Backward",
1463     "BackwardVectorizable", "BackwardVectorizableButPreventsForwarding"};
1464 
1465 void MemoryDepChecker::Dependence::print(
1466     raw_ostream &OS, unsigned Depth,
1467     const SmallVectorImpl<Instruction *> &Instrs) const {
1468   OS.indent(Depth) << DepName[Type] << ":\n";
1469   OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
1470   OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
1471 }
1472 
1473 bool LoopAccessInfo::canAnalyzeLoop() {
1474   // We need to have a loop header.
1475   DEBUG(dbgs() << "LAA: Found a loop in "
1476                << TheLoop->getHeader()->getParent()->getName() << ": "
1477                << TheLoop->getHeader()->getName() << '\n');
1478 
1479   // We can only analyze innermost loops.
1480   if (!TheLoop->empty()) {
1481     DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
1482     emitAnalysis(LoopAccessReport() << "loop is not the innermost loop");
1483     return false;
1484   }
1485 
1486   // We must have a single backedge.
1487   if (TheLoop->getNumBackEdges() != 1) {
1488     DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
1489     emitAnalysis(
1490         LoopAccessReport() <<
1491         "loop control flow is not understood by analyzer");
1492     return false;
1493   }
1494 
1495   // We must have a single exiting block.
1496   if (!TheLoop->getExitingBlock()) {
1497     DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
1498     emitAnalysis(
1499         LoopAccessReport() <<
1500         "loop control flow is not understood by analyzer");
1501     return false;
1502   }
1503 
1504   // We only handle bottom-tested loops, i.e. loop in which the condition is
1505   // checked at the end of each iteration. With that we can assume that all
1506   // instructions in the loop are executed the same number of times.
1507   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
1508     DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
1509     emitAnalysis(
1510         LoopAccessReport() <<
1511         "loop control flow is not understood by analyzer");
1512     return false;
1513   }
1514 
1515   // ScalarEvolution needs to be able to find the exit count.
1516   const SCEV *ExitCount = PSE->getBackedgeTakenCount();
1517   if (ExitCount == PSE->getSE()->getCouldNotCompute()) {
1518     emitAnalysis(LoopAccessReport()
1519                  << "could not determine number of loop iterations");
1520     DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
1521     return false;
1522   }
1523 
1524   return true;
1525 }
1526 
1527 void LoopAccessInfo::analyzeLoop(AliasAnalysis *AA, LoopInfo *LI,
1528                                  const TargetLibraryInfo *TLI,
1529                                  DominatorTree *DT) {
1530   typedef SmallPtrSet<Value*, 16> ValueSet;
1531 
1532   // Holds the Load and Store instructions.
1533   SmallVector<LoadInst *, 16> Loads;
1534   SmallVector<StoreInst *, 16> Stores;
1535 
1536   // Holds all the different accesses in the loop.
1537   unsigned NumReads = 0;
1538   unsigned NumReadWrites = 0;
1539 
1540   PtrRtChecking->Pointers.clear();
1541   PtrRtChecking->Need = false;
1542 
1543   const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
1544 
1545   // For each block.
1546   for (BasicBlock *BB : TheLoop->blocks()) {
1547     // Scan the BB and collect legal loads and stores.
1548     for (Instruction &I : *BB) {
1549       // If this is a load, save it. If this instruction can read from memory
1550       // but is not a load, then we quit. Notice that we don't handle function
1551       // calls that read or write.
1552       if (I.mayReadFromMemory()) {
1553         // Many math library functions read the rounding mode. We will only
1554         // vectorize a loop if it contains known function calls that don't set
1555         // the flag. Therefore, it is safe to ignore this read from memory.
1556         auto *Call = dyn_cast<CallInst>(&I);
1557         if (Call && getVectorIntrinsicIDForCall(Call, TLI))
1558           continue;
1559 
1560         // If the function has an explicit vectorized counterpart, we can safely
1561         // assume that it can be vectorized.
1562         if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
1563             TLI->isFunctionVectorizable(Call->getCalledFunction()->getName()))
1564           continue;
1565 
1566         auto *Ld = dyn_cast<LoadInst>(&I);
1567         if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
1568           emitAnalysis(LoopAccessReport(Ld)
1569                        << "read with atomic ordering or volatile read");
1570           DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
1571           CanVecMem = false;
1572           return;
1573         }
1574         NumLoads++;
1575         Loads.push_back(Ld);
1576         DepChecker->addAccess(Ld);
1577         if (EnableMemAccessVersioning)
1578           collectStridedAccess(Ld);
1579         continue;
1580       }
1581 
1582       // Save 'store' instructions. Abort if other instructions write to memory.
1583       if (I.mayWriteToMemory()) {
1584         auto *St = dyn_cast<StoreInst>(&I);
1585         if (!St) {
1586           emitAnalysis(LoopAccessReport(St)
1587                        << "instruction cannot be vectorized");
1588           CanVecMem = false;
1589           return;
1590         }
1591         if (!St->isSimple() && !IsAnnotatedParallel) {
1592           emitAnalysis(LoopAccessReport(St)
1593                        << "write with atomic ordering or volatile write");
1594           DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
1595           CanVecMem = false;
1596           return;
1597         }
1598         NumStores++;
1599         Stores.push_back(St);
1600         DepChecker->addAccess(St);
1601         if (EnableMemAccessVersioning)
1602           collectStridedAccess(St);
1603       }
1604     } // Next instr.
1605   } // Next block.
1606 
1607   // Now we have two lists that hold the loads and the stores.
1608   // Next, we find the pointers that they use.
1609 
1610   // Check if we see any stores. If there are no stores, then we don't
1611   // care if the pointers are *restrict*.
1612   if (!Stores.size()) {
1613     DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
1614     CanVecMem = true;
1615     return;
1616   }
1617 
1618   MemoryDepChecker::DepCandidates DependentAccesses;
1619   AccessAnalysis Accesses(TheLoop->getHeader()->getModule()->getDataLayout(),
1620                           AA, LI, DependentAccesses, *PSE);
1621 
1622   // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1623   // multiple times on the same object. If the ptr is accessed twice, once
1624   // for read and once for write, it will only appear once (on the write
1625   // list). This is okay, since we are going to check for conflicts between
1626   // writes and between reads and writes, but not between reads and reads.
1627   ValueSet Seen;
1628 
1629   for (StoreInst *ST : Stores) {
1630     Value *Ptr = ST->getPointerOperand();
1631     // Check for store to loop invariant address.
1632     StoreToLoopInvariantAddress |= isUniform(Ptr);
1633     // If we did *not* see this pointer before, insert it to  the read-write
1634     // list. At this phase it is only a 'write' list.
1635     if (Seen.insert(Ptr).second) {
1636       ++NumReadWrites;
1637 
1638       MemoryLocation Loc = MemoryLocation::get(ST);
1639       // The TBAA metadata could have a control dependency on the predication
1640       // condition, so we cannot rely on it when determining whether or not we
1641       // need runtime pointer checks.
1642       if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
1643         Loc.AATags.TBAA = nullptr;
1644 
1645       Accesses.addStore(Loc);
1646     }
1647   }
1648 
1649   if (IsAnnotatedParallel) {
1650     DEBUG(dbgs()
1651           << "LAA: A loop annotated parallel, ignore memory dependency "
1652           << "checks.\n");
1653     CanVecMem = true;
1654     return;
1655   }
1656 
1657   for (LoadInst *LD : Loads) {
1658     Value *Ptr = LD->getPointerOperand();
1659     // If we did *not* see this pointer before, insert it to the
1660     // read list. If we *did* see it before, then it is already in
1661     // the read-write list. This allows us to vectorize expressions
1662     // such as A[i] += x;  Because the address of A[i] is a read-write
1663     // pointer. This only works if the index of A[i] is consecutive.
1664     // If the address of i is unknown (for example A[B[i]]) then we may
1665     // read a few words, modify, and write a few words, and some of the
1666     // words may be written to the same address.
1667     bool IsReadOnlyPtr = false;
1668     if (Seen.insert(Ptr).second ||
1669         !getPtrStride(*PSE, Ptr, TheLoop, SymbolicStrides)) {
1670       ++NumReads;
1671       IsReadOnlyPtr = true;
1672     }
1673 
1674     MemoryLocation Loc = MemoryLocation::get(LD);
1675     // The TBAA metadata could have a control dependency on the predication
1676     // condition, so we cannot rely on it when determining whether or not we
1677     // need runtime pointer checks.
1678     if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
1679       Loc.AATags.TBAA = nullptr;
1680 
1681     Accesses.addLoad(Loc, IsReadOnlyPtr);
1682   }
1683 
1684   // If we write (or read-write) to a single destination and there are no
1685   // other reads in this loop then is it safe to vectorize.
1686   if (NumReadWrites == 1 && NumReads == 0) {
1687     DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
1688     CanVecMem = true;
1689     return;
1690   }
1691 
1692   // Build dependence sets and check whether we need a runtime pointer bounds
1693   // check.
1694   Accesses.buildDependenceSets();
1695 
1696   // Find pointers with computable bounds. We are going to use this information
1697   // to place a runtime bound check.
1698   bool CanDoRTIfNeeded = Accesses.canCheckPtrAtRT(*PtrRtChecking, PSE->getSE(),
1699                                                   TheLoop, SymbolicStrides);
1700   if (!CanDoRTIfNeeded) {
1701     emitAnalysis(LoopAccessReport() << "cannot identify array bounds");
1702     DEBUG(dbgs() << "LAA: We can't vectorize because we can't find "
1703                  << "the array bounds.\n");
1704     CanVecMem = false;
1705     return;
1706   }
1707 
1708   DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
1709 
1710   CanVecMem = true;
1711   if (Accesses.isDependencyCheckNeeded()) {
1712     DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
1713     CanVecMem = DepChecker->areDepsSafe(
1714         DependentAccesses, Accesses.getDependenciesToCheck(), SymbolicStrides);
1715     MaxSafeDepDistBytes = DepChecker->getMaxSafeDepDistBytes();
1716 
1717     if (!CanVecMem && DepChecker->shouldRetryWithRuntimeCheck()) {
1718       DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
1719 
1720       // Clear the dependency checks. We assume they are not needed.
1721       Accesses.resetDepChecks(*DepChecker);
1722 
1723       PtrRtChecking->reset();
1724       PtrRtChecking->Need = true;
1725 
1726       auto *SE = PSE->getSE();
1727       CanDoRTIfNeeded = Accesses.canCheckPtrAtRT(*PtrRtChecking, SE, TheLoop,
1728                                                  SymbolicStrides, true);
1729 
1730       // Check that we found the bounds for the pointer.
1731       if (!CanDoRTIfNeeded) {
1732         emitAnalysis(LoopAccessReport()
1733                      << "cannot check memory dependencies at runtime");
1734         DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
1735         CanVecMem = false;
1736         return;
1737       }
1738 
1739       CanVecMem = true;
1740     }
1741   }
1742 
1743   if (CanVecMem)
1744     DEBUG(dbgs() << "LAA: No unsafe dependent memory operations in loop.  We"
1745                  << (PtrRtChecking->Need ? "" : " don't")
1746                  << " need runtime memory checks.\n");
1747   else {
1748     emitAnalysis(
1749         LoopAccessReport()
1750         << "unsafe dependent memory operations in loop. Use "
1751            "#pragma loop distribute(enable) to allow loop distribution "
1752            "to attempt to isolate the offending operations into a separate "
1753            "loop");
1754     DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
1755   }
1756 }
1757 
1758 bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
1759                                            DominatorTree *DT)  {
1760   assert(TheLoop->contains(BB) && "Unknown block used");
1761 
1762   // Blocks that do not dominate the latch need predication.
1763   BasicBlock* Latch = TheLoop->getLoopLatch();
1764   return !DT->dominates(BB, Latch);
1765 }
1766 
1767 void LoopAccessInfo::emitAnalysis(LoopAccessReport &Message) {
1768   assert(!Report && "Multiple reports generated");
1769   Report = Message;
1770 }
1771 
1772 bool LoopAccessInfo::isUniform(Value *V) const {
1773   auto *SE = PSE->getSE();
1774   // Since we rely on SCEV for uniformity, if the type is not SCEVable, it is
1775   // never considered uniform.
1776   // TODO: Is this really what we want? Even without FP SCEV, we may want some
1777   // trivially loop-invariant FP values to be considered uniform.
1778   if (!SE->isSCEVable(V->getType()))
1779     return false;
1780   return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1781 }
1782 
1783 // FIXME: this function is currently a duplicate of the one in
1784 // LoopVectorize.cpp.
1785 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1786                                  Instruction *Loc) {
1787   if (FirstInst)
1788     return FirstInst;
1789   if (Instruction *I = dyn_cast<Instruction>(V))
1790     return I->getParent() == Loc->getParent() ? I : nullptr;
1791   return nullptr;
1792 }
1793 
1794 namespace {
1795 /// \brief IR Values for the lower and upper bounds of a pointer evolution.  We
1796 /// need to use value-handles because SCEV expansion can invalidate previously
1797 /// expanded values.  Thus expansion of a pointer can invalidate the bounds for
1798 /// a previous one.
1799 struct PointerBounds {
1800   TrackingVH<Value> Start;
1801   TrackingVH<Value> End;
1802 };
1803 } // end anonymous namespace
1804 
1805 /// \brief Expand code for the lower and upper bound of the pointer group \p CG
1806 /// in \p TheLoop.  \return the values for the bounds.
1807 static PointerBounds
1808 expandBounds(const RuntimePointerChecking::CheckingPtrGroup *CG, Loop *TheLoop,
1809              Instruction *Loc, SCEVExpander &Exp, ScalarEvolution *SE,
1810              const RuntimePointerChecking &PtrRtChecking) {
1811   Value *Ptr = PtrRtChecking.Pointers[CG->Members[0]].PointerValue;
1812   const SCEV *Sc = SE->getSCEV(Ptr);
1813 
1814   if (SE->isLoopInvariant(Sc, TheLoop)) {
1815     DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" << *Ptr
1816                  << "\n");
1817     return {Ptr, Ptr};
1818   } else {
1819     unsigned AS = Ptr->getType()->getPointerAddressSpace();
1820     LLVMContext &Ctx = Loc->getContext();
1821 
1822     // Use this type for pointer arithmetic.
1823     Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1824     Value *Start = nullptr, *End = nullptr;
1825 
1826     DEBUG(dbgs() << "LAA: Adding RT check for range:\n");
1827     Start = Exp.expandCodeFor(CG->Low, PtrArithTy, Loc);
1828     End = Exp.expandCodeFor(CG->High, PtrArithTy, Loc);
1829     DEBUG(dbgs() << "Start: " << *CG->Low << " End: " << *CG->High << "\n");
1830     return {Start, End};
1831   }
1832 }
1833 
1834 /// \brief Turns a collection of checks into a collection of expanded upper and
1835 /// lower bounds for both pointers in the check.
1836 static SmallVector<std::pair<PointerBounds, PointerBounds>, 4> expandBounds(
1837     const SmallVectorImpl<RuntimePointerChecking::PointerCheck> &PointerChecks,
1838     Loop *L, Instruction *Loc, ScalarEvolution *SE, SCEVExpander &Exp,
1839     const RuntimePointerChecking &PtrRtChecking) {
1840   SmallVector<std::pair<PointerBounds, PointerBounds>, 4> ChecksWithBounds;
1841 
1842   // Here we're relying on the SCEV Expander's cache to only emit code for the
1843   // same bounds once.
1844   transform(
1845       PointerChecks, std::back_inserter(ChecksWithBounds),
1846       [&](const RuntimePointerChecking::PointerCheck &Check) {
1847         PointerBounds
1848           First = expandBounds(Check.first, L, Loc, Exp, SE, PtrRtChecking),
1849           Second = expandBounds(Check.second, L, Loc, Exp, SE, PtrRtChecking);
1850         return std::make_pair(First, Second);
1851       });
1852 
1853   return ChecksWithBounds;
1854 }
1855 
1856 std::pair<Instruction *, Instruction *> LoopAccessInfo::addRuntimeChecks(
1857     Instruction *Loc,
1858     const SmallVectorImpl<RuntimePointerChecking::PointerCheck> &PointerChecks)
1859     const {
1860   const DataLayout &DL = TheLoop->getHeader()->getModule()->getDataLayout();
1861   auto *SE = PSE->getSE();
1862   SCEVExpander Exp(*SE, DL, "induction");
1863   auto ExpandedChecks =
1864       expandBounds(PointerChecks, TheLoop, Loc, SE, Exp, *PtrRtChecking);
1865 
1866   LLVMContext &Ctx = Loc->getContext();
1867   Instruction *FirstInst = nullptr;
1868   IRBuilder<> ChkBuilder(Loc);
1869   // Our instructions might fold to a constant.
1870   Value *MemoryRuntimeCheck = nullptr;
1871 
1872   for (const auto &Check : ExpandedChecks) {
1873     const PointerBounds &A = Check.first, &B = Check.second;
1874     // Check if two pointers (A and B) conflict where conflict is computed as:
1875     // start(A) <= end(B) && start(B) <= end(A)
1876     unsigned AS0 = A.Start->getType()->getPointerAddressSpace();
1877     unsigned AS1 = B.Start->getType()->getPointerAddressSpace();
1878 
1879     assert((AS0 == B.End->getType()->getPointerAddressSpace()) &&
1880            (AS1 == A.End->getType()->getPointerAddressSpace()) &&
1881            "Trying to bounds check pointers with different address spaces");
1882 
1883     Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1884     Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
1885 
1886     Value *Start0 = ChkBuilder.CreateBitCast(A.Start, PtrArithTy0, "bc");
1887     Value *Start1 = ChkBuilder.CreateBitCast(B.Start, PtrArithTy1, "bc");
1888     Value *End0 =   ChkBuilder.CreateBitCast(A.End,   PtrArithTy1, "bc");
1889     Value *End1 =   ChkBuilder.CreateBitCast(B.End,   PtrArithTy0, "bc");
1890 
1891     // [A|B].Start points to the first accessed byte under base [A|B].
1892     // [A|B].End points to the last accessed byte, plus one.
1893     // There is no conflict when the intervals are disjoint:
1894     // NoConflict = (B.Start >= A.End) || (A.Start >= B.End)
1895     //
1896     // bound0 = (B.Start < A.End)
1897     // bound1 = (A.Start < B.End)
1898     //  IsConflict = bound0 & bound1
1899     Value *Cmp0 = ChkBuilder.CreateICmpULT(Start0, End1, "bound0");
1900     FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1901     Value *Cmp1 = ChkBuilder.CreateICmpULT(Start1, End0, "bound1");
1902     FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1903     Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1904     FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1905     if (MemoryRuntimeCheck) {
1906       IsConflict =
1907           ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx");
1908       FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1909     }
1910     MemoryRuntimeCheck = IsConflict;
1911   }
1912 
1913   if (!MemoryRuntimeCheck)
1914     return std::make_pair(nullptr, nullptr);
1915 
1916   // We have to do this trickery because the IRBuilder might fold the check to a
1917   // constant expression in which case there is no Instruction anchored in a
1918   // the block.
1919   Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1920                                                  ConstantInt::getTrue(Ctx));
1921   ChkBuilder.Insert(Check, "memcheck.conflict");
1922   FirstInst = getFirstInst(FirstInst, Check, Loc);
1923   return std::make_pair(FirstInst, Check);
1924 }
1925 
1926 std::pair<Instruction *, Instruction *>
1927 LoopAccessInfo::addRuntimeChecks(Instruction *Loc) const {
1928   if (!PtrRtChecking->Need)
1929     return std::make_pair(nullptr, nullptr);
1930 
1931   return addRuntimeChecks(Loc, PtrRtChecking->getChecks());
1932 }
1933 
1934 void LoopAccessInfo::collectStridedAccess(Value *MemAccess) {
1935   Value *Ptr = nullptr;
1936   if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
1937     Ptr = LI->getPointerOperand();
1938   else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
1939     Ptr = SI->getPointerOperand();
1940   else
1941     return;
1942 
1943   Value *Stride = getStrideFromPointer(Ptr, PSE->getSE(), TheLoop);
1944   if (!Stride)
1945     return;
1946 
1947   DEBUG(dbgs() << "LAA: Found a strided access that we can version");
1948   DEBUG(dbgs() << "  Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
1949   SymbolicStrides[Ptr] = Stride;
1950   StrideSet.insert(Stride);
1951 }
1952 
1953 LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
1954                                const TargetLibraryInfo *TLI, AliasAnalysis *AA,
1955                                DominatorTree *DT, LoopInfo *LI)
1956     : PSE(llvm::make_unique<PredicatedScalarEvolution>(*SE, *L)),
1957       PtrRtChecking(llvm::make_unique<RuntimePointerChecking>(SE)),
1958       DepChecker(llvm::make_unique<MemoryDepChecker>(*PSE, L)), TheLoop(L),
1959       NumLoads(0), NumStores(0), MaxSafeDepDistBytes(-1), CanVecMem(false),
1960       StoreToLoopInvariantAddress(false) {
1961   if (canAnalyzeLoop())
1962     analyzeLoop(AA, LI, TLI, DT);
1963 }
1964 
1965 void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
1966   if (CanVecMem) {
1967     OS.indent(Depth) << "Memory dependences are safe";
1968     if (MaxSafeDepDistBytes != -1ULL)
1969       OS << " with a maximum dependence distance of " << MaxSafeDepDistBytes
1970          << " bytes";
1971     if (PtrRtChecking->Need)
1972       OS << " with run-time checks";
1973     OS << "\n";
1974   }
1975 
1976   if (Report)
1977     OS.indent(Depth) << "Report: " << Report->str() << "\n";
1978 
1979   if (auto *Dependences = DepChecker->getDependences()) {
1980     OS.indent(Depth) << "Dependences:\n";
1981     for (auto &Dep : *Dependences) {
1982       Dep.print(OS, Depth + 2, DepChecker->getMemoryInstructions());
1983       OS << "\n";
1984     }
1985   } else
1986     OS.indent(Depth) << "Too many dependences, not recorded\n";
1987 
1988   // List the pair of accesses need run-time checks to prove independence.
1989   PtrRtChecking->print(OS, Depth);
1990   OS << "\n";
1991 
1992   OS.indent(Depth) << "Store to invariant address was "
1993                    << (StoreToLoopInvariantAddress ? "" : "not ")
1994                    << "found in loop.\n";
1995 
1996   OS.indent(Depth) << "SCEV assumptions:\n";
1997   PSE->getUnionPredicate().print(OS, Depth);
1998 
1999   OS << "\n";
2000 
2001   OS.indent(Depth) << "Expressions re-written:\n";
2002   PSE->print(OS, Depth);
2003 }
2004 
2005 const LoopAccessInfo &LoopAccessLegacyAnalysis::getInfo(Loop *L) {
2006   auto &LAI = LoopAccessInfoMap[L];
2007 
2008   if (!LAI)
2009     LAI = llvm::make_unique<LoopAccessInfo>(L, SE, TLI, AA, DT, LI);
2010 
2011   return *LAI.get();
2012 }
2013 
2014 void LoopAccessLegacyAnalysis::print(raw_ostream &OS, const Module *M) const {
2015   LoopAccessLegacyAnalysis &LAA = *const_cast<LoopAccessLegacyAnalysis *>(this);
2016 
2017   for (Loop *TopLevelLoop : *LI)
2018     for (Loop *L : depth_first(TopLevelLoop)) {
2019       OS.indent(2) << L->getHeader()->getName() << ":\n";
2020       auto &LAI = LAA.getInfo(L);
2021       LAI.print(OS, 4);
2022     }
2023 }
2024 
2025 bool LoopAccessLegacyAnalysis::runOnFunction(Function &F) {
2026   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2027   auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2028   TLI = TLIP ? &TLIP->getTLI() : nullptr;
2029   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2030   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2031   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2032 
2033   return false;
2034 }
2035 
2036 void LoopAccessLegacyAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
2037     AU.addRequired<ScalarEvolutionWrapperPass>();
2038     AU.addRequired<AAResultsWrapperPass>();
2039     AU.addRequired<DominatorTreeWrapperPass>();
2040     AU.addRequired<LoopInfoWrapperPass>();
2041 
2042     AU.setPreservesAll();
2043 }
2044 
2045 char LoopAccessLegacyAnalysis::ID = 0;
2046 static const char laa_name[] = "Loop Access Analysis";
2047 #define LAA_NAME "loop-accesses"
2048 
2049 INITIALIZE_PASS_BEGIN(LoopAccessLegacyAnalysis, LAA_NAME, laa_name, false, true)
2050 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
2051 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
2052 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2053 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
2054 INITIALIZE_PASS_END(LoopAccessLegacyAnalysis, LAA_NAME, laa_name, false, true)
2055 
2056 char LoopAccessAnalysis::PassID;
2057 
2058 LoopAccessInfo LoopAccessAnalysis::run(Loop &L, LoopAnalysisManager &AM) {
2059   const FunctionAnalysisManager &FAM =
2060       AM.getResult<FunctionAnalysisManagerLoopProxy>(L).getManager();
2061   Function &F = *L.getHeader()->getParent();
2062   auto *SE = FAM.getCachedResult<ScalarEvolutionAnalysis>(F);
2063   auto *TLI = FAM.getCachedResult<TargetLibraryAnalysis>(F);
2064   auto *AA = FAM.getCachedResult<AAManager>(F);
2065   auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
2066   auto *LI = FAM.getCachedResult<LoopAnalysis>(F);
2067   if (!SE)
2068     report_fatal_error(
2069         "ScalarEvolution must have been cached at a higher level");
2070   if (!AA)
2071     report_fatal_error("AliasAnalysis must have been cached at a higher level");
2072   if (!DT)
2073     report_fatal_error("DominatorTree must have been cached at a higher level");
2074   if (!LI)
2075     report_fatal_error("LoopInfo must have been cached at a higher level");
2076   return LoopAccessInfo(&L, SE, TLI, AA, DT, LI);
2077 }
2078 
2079 PreservedAnalyses LoopAccessInfoPrinterPass::run(Loop &L,
2080                                                  LoopAnalysisManager &AM) {
2081   Function &F = *L.getHeader()->getParent();
2082   auto &LAI = AM.getResult<LoopAccessAnalysis>(L);
2083   OS << "Loop access info in function '" << F.getName() << "':\n";
2084   OS.indent(2) << L.getHeader()->getName() << ":\n";
2085   LAI.print(OS, 4);
2086   return PreservedAnalyses::all();
2087 }
2088 
2089 namespace llvm {
2090   Pass *createLAAPass() {
2091     return new LoopAccessLegacyAnalysis();
2092   }
2093 }
2094