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