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