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