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