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