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