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