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