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