10456327cSAdam Nemet //===- LoopAccessAnalysis.cpp - Loop Access Analysis Implementation --------==//
20456327cSAdam Nemet //
30456327cSAdam Nemet //                     The LLVM Compiler Infrastructure
40456327cSAdam Nemet //
50456327cSAdam Nemet // This file is distributed under the University of Illinois Open Source
60456327cSAdam Nemet // License. See LICENSE.TXT for details.
70456327cSAdam Nemet //
80456327cSAdam Nemet //===----------------------------------------------------------------------===//
90456327cSAdam Nemet //
100456327cSAdam Nemet // The implementation for the loop memory dependence that was originally
110456327cSAdam Nemet // developed for the loop vectorizer.
120456327cSAdam Nemet //
130456327cSAdam Nemet //===----------------------------------------------------------------------===//
140456327cSAdam Nemet 
150456327cSAdam Nemet #include "llvm/Analysis/LoopAccessAnalysis.h"
160456327cSAdam Nemet #include "llvm/Analysis/LoopInfo.h"
177206d7a5SAdam Nemet #include "llvm/Analysis/ScalarEvolutionExpander.h"
18799003bfSBenjamin Kramer #include "llvm/Analysis/TargetLibraryInfo.h"
190456327cSAdam Nemet #include "llvm/Analysis/ValueTracking.h"
200456327cSAdam Nemet #include "llvm/IR/DiagnosticInfo.h"
210456327cSAdam Nemet #include "llvm/IR/Dominators.h"
227206d7a5SAdam Nemet #include "llvm/IR/IRBuilder.h"
230456327cSAdam Nemet #include "llvm/Support/Debug.h"
24799003bfSBenjamin Kramer #include "llvm/Support/raw_ostream.h"
25b447ac64SDavid Blaikie #include "llvm/Analysis/VectorUtils.h"
260456327cSAdam Nemet using namespace llvm;
270456327cSAdam Nemet 
28339f42b3SAdam Nemet #define DEBUG_TYPE "loop-accesses"
290456327cSAdam Nemet 
30f219c647SAdam Nemet static cl::opt<unsigned, true>
31f219c647SAdam Nemet VectorizationFactor("force-vector-width", cl::Hidden,
32f219c647SAdam Nemet                     cl::desc("Sets the SIMD width. Zero is autoselect."),
33f219c647SAdam Nemet                     cl::location(VectorizerParams::VectorizationFactor));
341d862af7SAdam Nemet unsigned VectorizerParams::VectorizationFactor;
35f219c647SAdam Nemet 
36f219c647SAdam Nemet static cl::opt<unsigned, true>
37f219c647SAdam Nemet VectorizationInterleave("force-vector-interleave", cl::Hidden,
38f219c647SAdam Nemet                         cl::desc("Sets the vectorization interleave count. "
39f219c647SAdam Nemet                                  "Zero is autoselect."),
40f219c647SAdam Nemet                         cl::location(
41f219c647SAdam Nemet                             VectorizerParams::VectorizationInterleave));
421d862af7SAdam Nemet unsigned VectorizerParams::VectorizationInterleave;
43f219c647SAdam Nemet 
441d862af7SAdam Nemet static cl::opt<unsigned, true> RuntimeMemoryCheckThreshold(
451d862af7SAdam Nemet     "runtime-memory-check-threshold", cl::Hidden,
461d862af7SAdam Nemet     cl::desc("When performing memory disambiguation checks at runtime do not "
471d862af7SAdam Nemet              "generate more than this number of comparisons (default = 8)."),
481d862af7SAdam Nemet     cl::location(VectorizerParams::RuntimeMemoryCheckThreshold), cl::init(8));
491d862af7SAdam Nemet unsigned VectorizerParams::RuntimeMemoryCheckThreshold;
50f219c647SAdam Nemet 
511b6b50a9SSilviu Baranga /// \brief The maximum iterations used to merge memory checks
521b6b50a9SSilviu Baranga static cl::opt<unsigned> MemoryCheckMergeThreshold(
531b6b50a9SSilviu Baranga     "memory-check-merge-threshold", cl::Hidden,
541b6b50a9SSilviu Baranga     cl::desc("Maximum number of comparisons done when trying to merge "
551b6b50a9SSilviu Baranga              "runtime memory checks. (default = 100)"),
561b6b50a9SSilviu Baranga     cl::init(100));
571b6b50a9SSilviu Baranga 
58f219c647SAdam Nemet /// Maximum SIMD width.
59f219c647SAdam Nemet const unsigned VectorizerParams::MaxVectorWidth = 64;
60f219c647SAdam Nemet 
619c926579SAdam Nemet /// \brief We collect interesting dependences up to this threshold.
629c926579SAdam Nemet static cl::opt<unsigned> MaxInterestingDependence(
639c926579SAdam Nemet     "max-interesting-dependences", cl::Hidden,
649c926579SAdam Nemet     cl::desc("Maximum number of interesting dependences collected by "
659c926579SAdam Nemet              "loop-access analysis (default = 100)"),
669c926579SAdam Nemet     cl::init(100));
679c926579SAdam Nemet 
68f219c647SAdam Nemet bool VectorizerParams::isInterleaveForced() {
69f219c647SAdam Nemet   return ::VectorizationInterleave.getNumOccurrences() > 0;
70f219c647SAdam Nemet }
71f219c647SAdam Nemet 
722bd6e984SAdam Nemet void LoopAccessReport::emitAnalysis(const LoopAccessReport &Message,
730456327cSAdam Nemet                                     const Function *TheFunction,
74339f42b3SAdam Nemet                                     const Loop *TheLoop,
75339f42b3SAdam Nemet                                     const char *PassName) {
760456327cSAdam Nemet   DebugLoc DL = TheLoop->getStartLoc();
773e87634fSAdam Nemet   if (const Instruction *I = Message.getInstr())
780456327cSAdam Nemet     DL = I->getDebugLoc();
79339f42b3SAdam Nemet   emitOptimizationRemarkAnalysis(TheFunction->getContext(), PassName,
800456327cSAdam Nemet                                  *TheFunction, DL, Message.str());
810456327cSAdam Nemet }
820456327cSAdam Nemet 
830456327cSAdam Nemet Value *llvm::stripIntegerCast(Value *V) {
840456327cSAdam Nemet   if (CastInst *CI = dyn_cast<CastInst>(V))
850456327cSAdam Nemet     if (CI->getOperand(0)->getType()->isIntegerTy())
860456327cSAdam Nemet       return CI->getOperand(0);
870456327cSAdam Nemet   return V;
880456327cSAdam Nemet }
890456327cSAdam Nemet 
900456327cSAdam Nemet const SCEV *llvm::replaceSymbolicStrideSCEV(ScalarEvolution *SE,
918bc61df9SAdam Nemet                                             const ValueToValueMap &PtrToStride,
920456327cSAdam Nemet                                             Value *Ptr, Value *OrigPtr) {
930456327cSAdam Nemet 
940456327cSAdam Nemet   const SCEV *OrigSCEV = SE->getSCEV(Ptr);
950456327cSAdam Nemet 
960456327cSAdam Nemet   // If there is an entry in the map return the SCEV of the pointer with the
970456327cSAdam Nemet   // symbolic stride replaced by one.
988bc61df9SAdam Nemet   ValueToValueMap::const_iterator SI =
998bc61df9SAdam Nemet       PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
1000456327cSAdam Nemet   if (SI != PtrToStride.end()) {
1010456327cSAdam Nemet     Value *StrideVal = SI->second;
1020456327cSAdam Nemet 
1030456327cSAdam Nemet     // Strip casts.
1040456327cSAdam Nemet     StrideVal = stripIntegerCast(StrideVal);
1050456327cSAdam Nemet 
1060456327cSAdam Nemet     // Replace symbolic stride by one.
1070456327cSAdam Nemet     Value *One = ConstantInt::get(StrideVal->getType(), 1);
1080456327cSAdam Nemet     ValueToValueMap RewriteMap;
1090456327cSAdam Nemet     RewriteMap[StrideVal] = One;
1100456327cSAdam Nemet 
1110456327cSAdam Nemet     const SCEV *ByOne =
1120456327cSAdam Nemet         SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
113339f42b3SAdam Nemet     DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
1140456327cSAdam Nemet                  << "\n");
1150456327cSAdam Nemet     return ByOne;
1160456327cSAdam Nemet   }
1170456327cSAdam Nemet 
1180456327cSAdam Nemet   // Otherwise, just return the SCEV of the original pointer.
1190456327cSAdam Nemet   return SE->getSCEV(Ptr);
1200456327cSAdam Nemet }
1210456327cSAdam Nemet 
1227cdebac0SAdam Nemet void RuntimePointerChecking::insert(Loop *Lp, Value *Ptr, bool WritePtr,
1237cdebac0SAdam Nemet                                     unsigned DepSetId, unsigned ASId,
1241b6b50a9SSilviu Baranga                                     const ValueToValueMap &Strides) {
1250456327cSAdam Nemet   // Get the stride replaced scev.
1260456327cSAdam Nemet   const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
1270456327cSAdam Nemet   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
1280456327cSAdam Nemet   assert(AR && "Invalid addrec expression");
1290456327cSAdam Nemet   const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
1300e5804a6SSilviu Baranga 
1310e5804a6SSilviu Baranga   const SCEV *ScStart = AR->getStart();
1320456327cSAdam Nemet   const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
1330e5804a6SSilviu Baranga   const SCEV *Step = AR->getStepRecurrence(*SE);
1340e5804a6SSilviu Baranga 
1350e5804a6SSilviu Baranga   // For expressions with negative step, the upper bound is ScStart and the
1360e5804a6SSilviu Baranga   // lower bound is ScEnd.
1370e5804a6SSilviu Baranga   if (const SCEVConstant *CStep = dyn_cast<const SCEVConstant>(Step)) {
1380e5804a6SSilviu Baranga     if (CStep->getValue()->isNegative())
1390e5804a6SSilviu Baranga       std::swap(ScStart, ScEnd);
1400e5804a6SSilviu Baranga   } else {
1410e5804a6SSilviu Baranga     // Fallback case: the step is not constant, but the we can still
1420e5804a6SSilviu Baranga     // get the upper and lower bounds of the interval by using min/max
1430e5804a6SSilviu Baranga     // expressions.
1440e5804a6SSilviu Baranga     ScStart = SE->getUMinExpr(ScStart, ScEnd);
1450e5804a6SSilviu Baranga     ScEnd = SE->getUMaxExpr(AR->getStart(), ScEnd);
1460e5804a6SSilviu Baranga   }
1470e5804a6SSilviu Baranga 
1480e5804a6SSilviu Baranga   Pointers.emplace_back(Ptr, ScStart, ScEnd, WritePtr, DepSetId, ASId, Sc);
1491b6b50a9SSilviu Baranga }
1501b6b50a9SSilviu Baranga 
151bbe1f1deSAdam Nemet SmallVector<RuntimePointerChecking::PointerCheck, 4>
15238530887SAdam Nemet RuntimePointerChecking::generateChecks() const {
153bbe1f1deSAdam Nemet   SmallVector<PointerCheck, 4> Checks;
154bbe1f1deSAdam Nemet 
1557c52e052SAdam Nemet   for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
1567c52e052SAdam Nemet     for (unsigned J = I + 1; J < CheckingGroups.size(); ++J) {
1577c52e052SAdam Nemet       const RuntimePointerChecking::CheckingPtrGroup &CGI = CheckingGroups[I];
1587c52e052SAdam Nemet       const RuntimePointerChecking::CheckingPtrGroup &CGJ = CheckingGroups[J];
159bbe1f1deSAdam Nemet 
16038530887SAdam Nemet       if (needsChecking(CGI, CGJ))
161bbe1f1deSAdam Nemet         Checks.push_back(std::make_pair(&CGI, &CGJ));
162bbe1f1deSAdam Nemet     }
163bbe1f1deSAdam Nemet   }
164bbe1f1deSAdam Nemet   return Checks;
165bbe1f1deSAdam Nemet }
166bbe1f1deSAdam Nemet 
16715840393SAdam Nemet void RuntimePointerChecking::generateChecks(
16815840393SAdam Nemet     MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
16915840393SAdam Nemet   assert(Checks.empty() && "Checks is not empty");
17015840393SAdam Nemet   groupChecks(DepCands, UseDependencies);
17115840393SAdam Nemet   Checks = generateChecks();
17215840393SAdam Nemet }
17315840393SAdam Nemet 
174651a5a24SAdam Nemet bool RuntimePointerChecking::needsChecking(const CheckingPtrGroup &M,
175651a5a24SAdam Nemet                                            const CheckingPtrGroup &N) const {
1761b6b50a9SSilviu Baranga   for (unsigned I = 0, EI = M.Members.size(); EI != I; ++I)
1771b6b50a9SSilviu Baranga     for (unsigned J = 0, EJ = N.Members.size(); EJ != J; ++J)
178651a5a24SAdam Nemet       if (needsChecking(M.Members[I], N.Members[J]))
1791b6b50a9SSilviu Baranga         return true;
1801b6b50a9SSilviu Baranga   return false;
1811b6b50a9SSilviu Baranga }
1821b6b50a9SSilviu Baranga 
1831b6b50a9SSilviu Baranga /// Compare \p I and \p J and return the minimum.
1841b6b50a9SSilviu Baranga /// Return nullptr in case we couldn't find an answer.
1851b6b50a9SSilviu Baranga static const SCEV *getMinFromExprs(const SCEV *I, const SCEV *J,
1861b6b50a9SSilviu Baranga                                    ScalarEvolution *SE) {
1871b6b50a9SSilviu Baranga   const SCEV *Diff = SE->getMinusSCEV(J, I);
1881b6b50a9SSilviu Baranga   const SCEVConstant *C = dyn_cast<const SCEVConstant>(Diff);
1891b6b50a9SSilviu Baranga 
1901b6b50a9SSilviu Baranga   if (!C)
1911b6b50a9SSilviu Baranga     return nullptr;
1921b6b50a9SSilviu Baranga   if (C->getValue()->isNegative())
1931b6b50a9SSilviu Baranga     return J;
1941b6b50a9SSilviu Baranga   return I;
1951b6b50a9SSilviu Baranga }
1961b6b50a9SSilviu Baranga 
1977cdebac0SAdam Nemet bool RuntimePointerChecking::CheckingPtrGroup::addPointer(unsigned Index) {
1989f7dedc3SAdam Nemet   const SCEV *Start = RtCheck.Pointers[Index].Start;
1999f7dedc3SAdam Nemet   const SCEV *End = RtCheck.Pointers[Index].End;
2009f7dedc3SAdam Nemet 
2011b6b50a9SSilviu Baranga   // Compare the starts and ends with the known minimum and maximum
2021b6b50a9SSilviu Baranga   // of this set. We need to know how we compare against the min/max
2031b6b50a9SSilviu Baranga   // of the set in order to be able to emit memchecks.
2049f7dedc3SAdam Nemet   const SCEV *Min0 = getMinFromExprs(Start, Low, RtCheck.SE);
2051b6b50a9SSilviu Baranga   if (!Min0)
2061b6b50a9SSilviu Baranga     return false;
2071b6b50a9SSilviu Baranga 
2089f7dedc3SAdam Nemet   const SCEV *Min1 = getMinFromExprs(End, High, RtCheck.SE);
2091b6b50a9SSilviu Baranga   if (!Min1)
2101b6b50a9SSilviu Baranga     return false;
2111b6b50a9SSilviu Baranga 
2121b6b50a9SSilviu Baranga   // Update the low bound  expression if we've found a new min value.
2139f7dedc3SAdam Nemet   if (Min0 == Start)
2149f7dedc3SAdam Nemet     Low = Start;
2151b6b50a9SSilviu Baranga 
2161b6b50a9SSilviu Baranga   // Update the high bound expression if we've found a new max value.
2179f7dedc3SAdam Nemet   if (Min1 != End)
2189f7dedc3SAdam Nemet     High = End;
2191b6b50a9SSilviu Baranga 
2201b6b50a9SSilviu Baranga   Members.push_back(Index);
2211b6b50a9SSilviu Baranga   return true;
2221b6b50a9SSilviu Baranga }
2231b6b50a9SSilviu Baranga 
2247cdebac0SAdam Nemet void RuntimePointerChecking::groupChecks(
2257cdebac0SAdam Nemet     MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
2261b6b50a9SSilviu Baranga   // We build the groups from dependency candidates equivalence classes
2271b6b50a9SSilviu Baranga   // because:
2281b6b50a9SSilviu Baranga   //    - We know that pointers in the same equivalence class share
2291b6b50a9SSilviu Baranga   //      the same underlying object and therefore there is a chance
2301b6b50a9SSilviu Baranga   //      that we can compare pointers
2311b6b50a9SSilviu Baranga   //    - We wouldn't be able to merge two pointers for which we need
2321b6b50a9SSilviu Baranga   //      to emit a memcheck. The classes in DepCands are already
2331b6b50a9SSilviu Baranga   //      conveniently built such that no two pointers in the same
2341b6b50a9SSilviu Baranga   //      class need checking against each other.
2351b6b50a9SSilviu Baranga 
2361b6b50a9SSilviu Baranga   // We use the following (greedy) algorithm to construct the groups
2371b6b50a9SSilviu Baranga   // For every pointer in the equivalence class:
2381b6b50a9SSilviu Baranga   //   For each existing group:
2391b6b50a9SSilviu Baranga   //   - if the difference between this pointer and the min/max bounds
2401b6b50a9SSilviu Baranga   //     of the group is a constant, then make the pointer part of the
2411b6b50a9SSilviu Baranga   //     group and update the min/max bounds of that group as required.
2421b6b50a9SSilviu Baranga 
2431b6b50a9SSilviu Baranga   CheckingGroups.clear();
2441b6b50a9SSilviu Baranga 
24548250600SSilviu Baranga   // If we need to check two pointers to the same underlying object
24648250600SSilviu Baranga   // with a non-constant difference, we shouldn't perform any pointer
24748250600SSilviu Baranga   // grouping with those pointers. This is because we can easily get
24848250600SSilviu Baranga   // into cases where the resulting check would return false, even when
24948250600SSilviu Baranga   // the accesses are safe.
25048250600SSilviu Baranga   //
25148250600SSilviu Baranga   // The following example shows this:
25248250600SSilviu Baranga   // for (i = 0; i < 1000; ++i)
25348250600SSilviu Baranga   //   a[5000 + i * m] = a[i] + a[i + 9000]
25448250600SSilviu Baranga   //
25548250600SSilviu Baranga   // Here grouping gives a check of (5000, 5000 + 1000 * m) against
25648250600SSilviu Baranga   // (0, 10000) which is always false. However, if m is 1, there is no
25748250600SSilviu Baranga   // dependence. Not grouping the checks for a[i] and a[i + 9000] allows
25848250600SSilviu Baranga   // us to perform an accurate check in this case.
25948250600SSilviu Baranga   //
26048250600SSilviu Baranga   // The above case requires that we have an UnknownDependence between
26148250600SSilviu Baranga   // accesses to the same underlying object. This cannot happen unless
26248250600SSilviu Baranga   // ShouldRetryWithRuntimeCheck is set, and therefore UseDependencies
26348250600SSilviu Baranga   // is also false. In this case we will use the fallback path and create
26448250600SSilviu Baranga   // separate checking groups for all pointers.
26548250600SSilviu Baranga 
2661b6b50a9SSilviu Baranga   // If we don't have the dependency partitions, construct a new
26748250600SSilviu Baranga   // checking pointer group for each pointer. This is also required
26848250600SSilviu Baranga   // for correctness, because in this case we can have checking between
26948250600SSilviu Baranga   // pointers to the same underlying object.
2701b6b50a9SSilviu Baranga   if (!UseDependencies) {
2711b6b50a9SSilviu Baranga     for (unsigned I = 0; I < Pointers.size(); ++I)
2721b6b50a9SSilviu Baranga       CheckingGroups.push_back(CheckingPtrGroup(I, *this));
2731b6b50a9SSilviu Baranga     return;
2741b6b50a9SSilviu Baranga   }
2751b6b50a9SSilviu Baranga 
2761b6b50a9SSilviu Baranga   unsigned TotalComparisons = 0;
2771b6b50a9SSilviu Baranga 
2781b6b50a9SSilviu Baranga   DenseMap<Value *, unsigned> PositionMap;
2799f7dedc3SAdam Nemet   for (unsigned Index = 0; Index < Pointers.size(); ++Index)
2809f7dedc3SAdam Nemet     PositionMap[Pointers[Index].PointerValue] = Index;
2811b6b50a9SSilviu Baranga 
282ce3877fcSSilviu Baranga   // We need to keep track of what pointers we've already seen so we
283ce3877fcSSilviu Baranga   // don't process them twice.
284ce3877fcSSilviu Baranga   SmallSet<unsigned, 2> Seen;
285ce3877fcSSilviu Baranga 
2861b6b50a9SSilviu Baranga   // Go through all equivalence classes, get the the "pointer check groups"
287ce3877fcSSilviu Baranga   // and add them to the overall solution. We use the order in which accesses
288ce3877fcSSilviu Baranga   // appear in 'Pointers' to enforce determinism.
289ce3877fcSSilviu Baranga   for (unsigned I = 0; I < Pointers.size(); ++I) {
290ce3877fcSSilviu Baranga     // We've seen this pointer before, and therefore already processed
291ce3877fcSSilviu Baranga     // its equivalence class.
292ce3877fcSSilviu Baranga     if (Seen.count(I))
2931b6b50a9SSilviu Baranga       continue;
2941b6b50a9SSilviu Baranga 
2959f7dedc3SAdam Nemet     MemoryDepChecker::MemAccessInfo Access(Pointers[I].PointerValue,
2969f7dedc3SAdam Nemet                                            Pointers[I].IsWritePtr);
2971b6b50a9SSilviu Baranga 
298ce3877fcSSilviu Baranga     SmallVector<CheckingPtrGroup, 2> Groups;
299ce3877fcSSilviu Baranga     auto LeaderI = DepCands.findValue(DepCands.getLeaderValue(Access));
300ce3877fcSSilviu Baranga 
301a647c30fSSilviu Baranga     // Because DepCands is constructed by visiting accesses in the order in
302a647c30fSSilviu Baranga     // which they appear in alias sets (which is deterministic) and the
303a647c30fSSilviu Baranga     // iteration order within an equivalence class member is only dependent on
304a647c30fSSilviu Baranga     // the order in which unions and insertions are performed on the
305a647c30fSSilviu Baranga     // equivalence class, the iteration order is deterministic.
306ce3877fcSSilviu Baranga     for (auto MI = DepCands.member_begin(LeaderI), ME = DepCands.member_end();
3071b6b50a9SSilviu Baranga          MI != ME; ++MI) {
3081b6b50a9SSilviu Baranga       unsigned Pointer = PositionMap[MI->getPointer()];
3091b6b50a9SSilviu Baranga       bool Merged = false;
310ce3877fcSSilviu Baranga       // Mark this pointer as seen.
311ce3877fcSSilviu Baranga       Seen.insert(Pointer);
3121b6b50a9SSilviu Baranga 
3131b6b50a9SSilviu Baranga       // Go through all the existing sets and see if we can find one
3141b6b50a9SSilviu Baranga       // which can include this pointer.
3151b6b50a9SSilviu Baranga       for (CheckingPtrGroup &Group : Groups) {
3161b6b50a9SSilviu Baranga         // Don't perform more than a certain amount of comparisons.
3171b6b50a9SSilviu Baranga         // This should limit the cost of grouping the pointers to something
3181b6b50a9SSilviu Baranga         // reasonable.  If we do end up hitting this threshold, the algorithm
3191b6b50a9SSilviu Baranga         // will create separate groups for all remaining pointers.
3201b6b50a9SSilviu Baranga         if (TotalComparisons > MemoryCheckMergeThreshold)
3211b6b50a9SSilviu Baranga           break;
3221b6b50a9SSilviu Baranga 
3231b6b50a9SSilviu Baranga         TotalComparisons++;
3241b6b50a9SSilviu Baranga 
3251b6b50a9SSilviu Baranga         if (Group.addPointer(Pointer)) {
3261b6b50a9SSilviu Baranga           Merged = true;
3271b6b50a9SSilviu Baranga           break;
3281b6b50a9SSilviu Baranga         }
3291b6b50a9SSilviu Baranga       }
3301b6b50a9SSilviu Baranga 
3311b6b50a9SSilviu Baranga       if (!Merged)
3321b6b50a9SSilviu Baranga         // We couldn't add this pointer to any existing set or the threshold
3331b6b50a9SSilviu Baranga         // for the number of comparisons has been reached. Create a new group
3341b6b50a9SSilviu Baranga         // to hold the current pointer.
3351b6b50a9SSilviu Baranga         Groups.push_back(CheckingPtrGroup(Pointer, *this));
3361b6b50a9SSilviu Baranga     }
3371b6b50a9SSilviu Baranga 
3381b6b50a9SSilviu Baranga     // We've computed the grouped checks for this partition.
3391b6b50a9SSilviu Baranga     // Save the results and continue with the next one.
3401b6b50a9SSilviu Baranga     std::copy(Groups.begin(), Groups.end(), std::back_inserter(CheckingGroups));
3411b6b50a9SSilviu Baranga   }
3420456327cSAdam Nemet }
3430456327cSAdam Nemet 
344041e6debSAdam Nemet bool RuntimePointerChecking::arePointersInSamePartition(
345041e6debSAdam Nemet     const SmallVectorImpl<int> &PtrToPartition, unsigned PtrIdx1,
346041e6debSAdam Nemet     unsigned PtrIdx2) {
347041e6debSAdam Nemet   return (PtrToPartition[PtrIdx1] != -1 &&
348041e6debSAdam Nemet           PtrToPartition[PtrIdx1] == PtrToPartition[PtrIdx2]);
349041e6debSAdam Nemet }
350041e6debSAdam Nemet 
351651a5a24SAdam Nemet bool RuntimePointerChecking::needsChecking(unsigned I, unsigned J) const {
3529f7dedc3SAdam Nemet   const PointerInfo &PointerI = Pointers[I];
3539f7dedc3SAdam Nemet   const PointerInfo &PointerJ = Pointers[J];
3549f7dedc3SAdam Nemet 
355a8945b77SAdam Nemet   // No need to check if two readonly pointers intersect.
3569f7dedc3SAdam Nemet   if (!PointerI.IsWritePtr && !PointerJ.IsWritePtr)
357a8945b77SAdam Nemet     return false;
358a8945b77SAdam Nemet 
359a8945b77SAdam Nemet   // Only need to check pointers between two different dependency sets.
3609f7dedc3SAdam Nemet   if (PointerI.DependencySetId == PointerJ.DependencySetId)
361a8945b77SAdam Nemet     return false;
362a8945b77SAdam Nemet 
363a8945b77SAdam Nemet   // Only need to check pointers in the same alias set.
3649f7dedc3SAdam Nemet   if (PointerI.AliasSetId != PointerJ.AliasSetId)
365a8945b77SAdam Nemet     return false;
366a8945b77SAdam Nemet 
367a8945b77SAdam Nemet   return true;
368a8945b77SAdam Nemet }
369a8945b77SAdam Nemet 
37054f0b83eSAdam Nemet void RuntimePointerChecking::printChecks(
37154f0b83eSAdam Nemet     raw_ostream &OS, const SmallVectorImpl<PointerCheck> &Checks,
37254f0b83eSAdam Nemet     unsigned Depth) const {
37354f0b83eSAdam Nemet   unsigned N = 0;
37454f0b83eSAdam Nemet   for (const auto &Check : Checks) {
37554f0b83eSAdam Nemet     const auto &First = Check.first->Members, &Second = Check.second->Members;
37654f0b83eSAdam Nemet 
37754f0b83eSAdam Nemet     OS.indent(Depth) << "Check " << N++ << ":\n";
37854f0b83eSAdam Nemet 
37954f0b83eSAdam Nemet     OS.indent(Depth + 2) << "Comparing group (" << Check.first << "):\n";
38054f0b83eSAdam Nemet     for (unsigned K = 0; K < First.size(); ++K)
38154f0b83eSAdam Nemet       OS.indent(Depth + 2) << *Pointers[First[K]].PointerValue << "\n";
38254f0b83eSAdam Nemet 
38354f0b83eSAdam Nemet     OS.indent(Depth + 2) << "Against group (" << Check.second << "):\n";
38454f0b83eSAdam Nemet     for (unsigned K = 0; K < Second.size(); ++K)
38554f0b83eSAdam Nemet       OS.indent(Depth + 2) << *Pointers[Second[K]].PointerValue << "\n";
38654f0b83eSAdam Nemet   }
38754f0b83eSAdam Nemet }
38854f0b83eSAdam Nemet 
3893a91e947SAdam Nemet void RuntimePointerChecking::print(raw_ostream &OS, unsigned Depth) const {
390e91cc6efSAdam Nemet 
391e91cc6efSAdam Nemet   OS.indent(Depth) << "Run-time memory checks:\n";
39215840393SAdam Nemet   printChecks(OS, Checks, Depth);
3931b6b50a9SSilviu Baranga 
3941b6b50a9SSilviu Baranga   OS.indent(Depth) << "Grouped accesses:\n";
3951b6b50a9SSilviu Baranga   for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
39654f0b83eSAdam Nemet     const auto &CG = CheckingGroups[I];
39754f0b83eSAdam Nemet 
39854f0b83eSAdam Nemet     OS.indent(Depth + 2) << "Group " << &CG << ":\n";
39954f0b83eSAdam Nemet     OS.indent(Depth + 4) << "(Low: " << *CG.Low << " High: " << *CG.High
40054f0b83eSAdam Nemet                          << ")\n";
40154f0b83eSAdam Nemet     for (unsigned J = 0; J < CG.Members.size(); ++J) {
40254f0b83eSAdam Nemet       OS.indent(Depth + 6) << "Member: " << *Pointers[CG.Members[J]].Expr
4031b6b50a9SSilviu Baranga                            << "\n";
4041b6b50a9SSilviu Baranga     }
405e91cc6efSAdam Nemet   }
406e91cc6efSAdam Nemet }
407e91cc6efSAdam Nemet 
4080456327cSAdam Nemet namespace {
4090456327cSAdam Nemet /// \brief Analyses memory accesses in a loop.
4100456327cSAdam Nemet ///
4110456327cSAdam Nemet /// Checks whether run time pointer checks are needed and builds sets for data
4120456327cSAdam Nemet /// dependence checking.
4130456327cSAdam Nemet class AccessAnalysis {
4140456327cSAdam Nemet public:
4150456327cSAdam Nemet   /// \brief Read or write access location.
4160456327cSAdam Nemet   typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
4170456327cSAdam Nemet   typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
4180456327cSAdam Nemet 
419e2b885c4SAdam Nemet   AccessAnalysis(const DataLayout &Dl, AliasAnalysis *AA, LoopInfo *LI,
420dee666bcSAdam Nemet                  MemoryDepChecker::DepCandidates &DA)
4215dc3b2cfSAdam Nemet       : DL(Dl), AST(*AA), LI(LI), DepCands(DA),
4225dc3b2cfSAdam Nemet         IsRTCheckAnalysisNeeded(false) {}
4230456327cSAdam Nemet 
4240456327cSAdam Nemet   /// \brief Register a load  and whether it is only read from.
425ac80dc75SChandler Carruth   void addLoad(MemoryLocation &Loc, bool IsReadOnly) {
4260456327cSAdam Nemet     Value *Ptr = const_cast<Value*>(Loc.Ptr);
427ecbd1682SChandler Carruth     AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
4280456327cSAdam Nemet     Accesses.insert(MemAccessInfo(Ptr, false));
4290456327cSAdam Nemet     if (IsReadOnly)
4300456327cSAdam Nemet       ReadOnlyPtr.insert(Ptr);
4310456327cSAdam Nemet   }
4320456327cSAdam Nemet 
4330456327cSAdam Nemet   /// \brief Register a store.
434ac80dc75SChandler Carruth   void addStore(MemoryLocation &Loc) {
4350456327cSAdam Nemet     Value *Ptr = const_cast<Value*>(Loc.Ptr);
436ecbd1682SChandler Carruth     AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
4370456327cSAdam Nemet     Accesses.insert(MemAccessInfo(Ptr, true));
4380456327cSAdam Nemet   }
4390456327cSAdam Nemet 
4400456327cSAdam Nemet   /// \brief Check whether we can check the pointers at runtime for
441ee61474aSAdam Nemet   /// non-intersection.
442ee61474aSAdam Nemet   ///
443ee61474aSAdam Nemet   /// Returns true if we need no check or if we do and we can generate them
444ee61474aSAdam Nemet   /// (i.e. the pointers have computable bounds).
4457cdebac0SAdam Nemet   bool canCheckPtrAtRT(RuntimePointerChecking &RtCheck, ScalarEvolution *SE,
4467cdebac0SAdam Nemet                        Loop *TheLoop, const ValueToValueMap &Strides,
4470456327cSAdam Nemet                        bool ShouldCheckStride = false);
4480456327cSAdam Nemet 
4490456327cSAdam Nemet   /// \brief Goes over all memory accesses, checks whether a RT check is needed
4500456327cSAdam Nemet   /// and builds sets of dependent accesses.
4510456327cSAdam Nemet   void buildDependenceSets() {
4520456327cSAdam Nemet     processMemAccesses();
4530456327cSAdam Nemet   }
4540456327cSAdam Nemet 
4555dc3b2cfSAdam Nemet   /// \brief Initial processing of memory accesses determined that we need to
4565dc3b2cfSAdam Nemet   /// perform dependency checking.
4575dc3b2cfSAdam Nemet   ///
4585dc3b2cfSAdam Nemet   /// Note that this can later be cleared if we retry memcheck analysis without
4595dc3b2cfSAdam Nemet   /// dependency checking (i.e. ShouldRetryWithRuntimeCheck).
4600456327cSAdam Nemet   bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
461df3dc5b9SAdam Nemet 
462df3dc5b9SAdam Nemet   /// We decided that no dependence analysis would be used.  Reset the state.
463df3dc5b9SAdam Nemet   void resetDepChecks(MemoryDepChecker &DepChecker) {
464df3dc5b9SAdam Nemet     CheckDeps.clear();
465df3dc5b9SAdam Nemet     DepChecker.clearInterestingDependences();
466df3dc5b9SAdam Nemet   }
4670456327cSAdam Nemet 
4680456327cSAdam Nemet   MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
4690456327cSAdam Nemet 
4700456327cSAdam Nemet private:
4710456327cSAdam Nemet   typedef SetVector<MemAccessInfo> PtrAccessSet;
4720456327cSAdam Nemet 
4730456327cSAdam Nemet   /// \brief Go over all memory access and check whether runtime pointer checks
474b41d2d3fSAdam Nemet   /// are needed and build sets of dependency check candidates.
4750456327cSAdam Nemet   void processMemAccesses();
4760456327cSAdam Nemet 
4770456327cSAdam Nemet   /// Set of all accesses.
4780456327cSAdam Nemet   PtrAccessSet Accesses;
4790456327cSAdam Nemet 
480a28d91d8SMehdi Amini   const DataLayout &DL;
481a28d91d8SMehdi Amini 
4820456327cSAdam Nemet   /// Set of accesses that need a further dependence check.
4830456327cSAdam Nemet   MemAccessInfoSet CheckDeps;
4840456327cSAdam Nemet 
4850456327cSAdam Nemet   /// Set of pointers that are read only.
4860456327cSAdam Nemet   SmallPtrSet<Value*, 16> ReadOnlyPtr;
4870456327cSAdam Nemet 
4880456327cSAdam Nemet   /// An alias set tracker to partition the access set by underlying object and
4890456327cSAdam Nemet   //intrinsic property (such as TBAA metadata).
4900456327cSAdam Nemet   AliasSetTracker AST;
4910456327cSAdam Nemet 
492e2b885c4SAdam Nemet   LoopInfo *LI;
493e2b885c4SAdam Nemet 
4940456327cSAdam Nemet   /// Sets of potentially dependent accesses - members of one set share an
4950456327cSAdam Nemet   /// underlying pointer. The set "CheckDeps" identfies which sets really need a
4960456327cSAdam Nemet   /// dependence check.
497dee666bcSAdam Nemet   MemoryDepChecker::DepCandidates &DepCands;
4980456327cSAdam Nemet 
4995dc3b2cfSAdam Nemet   /// \brief Initial processing of memory accesses determined that we may need
5005dc3b2cfSAdam Nemet   /// to add memchecks.  Perform the analysis to determine the necessary checks.
5015dc3b2cfSAdam Nemet   ///
5025dc3b2cfSAdam Nemet   /// Note that, this is different from isDependencyCheckNeeded.  When we retry
5035dc3b2cfSAdam Nemet   /// memcheck analysis without dependency checking
5045dc3b2cfSAdam Nemet   /// (i.e. ShouldRetryWithRuntimeCheck), isDependencyCheckNeeded is cleared
5055dc3b2cfSAdam Nemet   /// while this remains set if we have potentially dependent accesses.
5065dc3b2cfSAdam Nemet   bool IsRTCheckAnalysisNeeded;
5070456327cSAdam Nemet };
5080456327cSAdam Nemet 
5090456327cSAdam Nemet } // end anonymous namespace
5100456327cSAdam Nemet 
5110456327cSAdam Nemet /// \brief Check whether a pointer can participate in a runtime bounds check.
5128bc61df9SAdam Nemet static bool hasComputableBounds(ScalarEvolution *SE,
5138bc61df9SAdam Nemet                                 const ValueToValueMap &Strides, Value *Ptr) {
5140456327cSAdam Nemet   const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
5150456327cSAdam Nemet   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
5160456327cSAdam Nemet   if (!AR)
5170456327cSAdam Nemet     return false;
5180456327cSAdam Nemet 
5190456327cSAdam Nemet   return AR->isAffine();
5200456327cSAdam Nemet }
5210456327cSAdam Nemet 
5227cdebac0SAdam Nemet bool AccessAnalysis::canCheckPtrAtRT(RuntimePointerChecking &RtCheck,
5237cdebac0SAdam Nemet                                      ScalarEvolution *SE, Loop *TheLoop,
5247cdebac0SAdam Nemet                                      const ValueToValueMap &StridesMap,
5257cdebac0SAdam Nemet                                      bool ShouldCheckStride) {
5260456327cSAdam Nemet   // Find pointers with computable bounds. We are going to use this information
5270456327cSAdam Nemet   // to place a runtime bound check.
5280456327cSAdam Nemet   bool CanDoRT = true;
5290456327cSAdam Nemet 
530ee61474aSAdam Nemet   bool NeedRTCheck = false;
5315dc3b2cfSAdam Nemet   if (!IsRTCheckAnalysisNeeded) return true;
53298a13719SSilviu Baranga 
5330456327cSAdam Nemet   bool IsDepCheckNeeded = isDependencyCheckNeeded();
5340456327cSAdam Nemet 
5350456327cSAdam Nemet   // We assign a consecutive id to access from different alias sets.
5360456327cSAdam Nemet   // Accesses between different groups doesn't need to be checked.
5370456327cSAdam Nemet   unsigned ASId = 1;
5380456327cSAdam Nemet   for (auto &AS : AST) {
539424edc6cSAdam Nemet     int NumReadPtrChecks = 0;
540424edc6cSAdam Nemet     int NumWritePtrChecks = 0;
541424edc6cSAdam Nemet 
5420456327cSAdam Nemet     // We assign consecutive id to access from different dependence sets.
5430456327cSAdam Nemet     // Accesses within the same set don't need a runtime check.
5440456327cSAdam Nemet     unsigned RunningDepId = 1;
5450456327cSAdam Nemet     DenseMap<Value *, unsigned> DepSetId;
5460456327cSAdam Nemet 
5470456327cSAdam Nemet     for (auto A : AS) {
5480456327cSAdam Nemet       Value *Ptr = A.getValue();
5490456327cSAdam Nemet       bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
5500456327cSAdam Nemet       MemAccessInfo Access(Ptr, IsWrite);
5510456327cSAdam Nemet 
552424edc6cSAdam Nemet       if (IsWrite)
553424edc6cSAdam Nemet         ++NumWritePtrChecks;
554424edc6cSAdam Nemet       else
555424edc6cSAdam Nemet         ++NumReadPtrChecks;
556424edc6cSAdam Nemet 
5570456327cSAdam Nemet       if (hasComputableBounds(SE, StridesMap, Ptr) &&
558a28d91d8SMehdi Amini           // When we run after a failing dependency check we have to make sure
559a28d91d8SMehdi Amini           // we don't have wrapping pointers.
5600456327cSAdam Nemet           (!ShouldCheckStride ||
561a28d91d8SMehdi Amini            isStridedPtr(SE, Ptr, TheLoop, StridesMap) == 1)) {
5620456327cSAdam Nemet         // The id of the dependence set.
5630456327cSAdam Nemet         unsigned DepId;
5640456327cSAdam Nemet 
5650456327cSAdam Nemet         if (IsDepCheckNeeded) {
5660456327cSAdam Nemet           Value *Leader = DepCands.getLeaderValue(Access).getPointer();
5670456327cSAdam Nemet           unsigned &LeaderId = DepSetId[Leader];
5680456327cSAdam Nemet           if (!LeaderId)
5690456327cSAdam Nemet             LeaderId = RunningDepId++;
5700456327cSAdam Nemet           DepId = LeaderId;
5710456327cSAdam Nemet         } else
5720456327cSAdam Nemet           // Each access has its own dependence set.
5730456327cSAdam Nemet           DepId = RunningDepId++;
5740456327cSAdam Nemet 
5751b6b50a9SSilviu Baranga         RtCheck.insert(TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap);
5760456327cSAdam Nemet 
577339f42b3SAdam Nemet         DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
5780456327cSAdam Nemet       } else {
579f10ca278SAdam Nemet         DEBUG(dbgs() << "LAA: Can't find bounds for ptr:" << *Ptr << '\n');
5800456327cSAdam Nemet         CanDoRT = false;
5810456327cSAdam Nemet       }
5820456327cSAdam Nemet     }
5830456327cSAdam Nemet 
584424edc6cSAdam Nemet     // If we have at least two writes or one write and a read then we need to
585424edc6cSAdam Nemet     // check them.  But there is no need to checks if there is only one
586424edc6cSAdam Nemet     // dependence set for this alias set.
587424edc6cSAdam Nemet     //
588424edc6cSAdam Nemet     // Note that this function computes CanDoRT and NeedRTCheck independently.
589424edc6cSAdam Nemet     // For example CanDoRT=false, NeedRTCheck=false means that we have a pointer
590424edc6cSAdam Nemet     // for which we couldn't find the bounds but we don't actually need to emit
591424edc6cSAdam Nemet     // any checks so it does not matter.
592424edc6cSAdam Nemet     if (!(IsDepCheckNeeded && CanDoRT && RunningDepId == 2))
593424edc6cSAdam Nemet       NeedRTCheck |= (NumWritePtrChecks >= 2 || (NumReadPtrChecks >= 1 &&
594424edc6cSAdam Nemet                                                  NumWritePtrChecks >= 1));
595424edc6cSAdam Nemet 
5960456327cSAdam Nemet     ++ASId;
5970456327cSAdam Nemet   }
5980456327cSAdam Nemet 
5990456327cSAdam Nemet   // If the pointers that we would use for the bounds comparison have different
6000456327cSAdam Nemet   // address spaces, assume the values aren't directly comparable, so we can't
6010456327cSAdam Nemet   // use them for the runtime check. We also have to assume they could
6020456327cSAdam Nemet   // overlap. In the future there should be metadata for whether address spaces
6030456327cSAdam Nemet   // are disjoint.
6040456327cSAdam Nemet   unsigned NumPointers = RtCheck.Pointers.size();
6050456327cSAdam Nemet   for (unsigned i = 0; i < NumPointers; ++i) {
6060456327cSAdam Nemet     for (unsigned j = i + 1; j < NumPointers; ++j) {
6070456327cSAdam Nemet       // Only need to check pointers between two different dependency sets.
6089f7dedc3SAdam Nemet       if (RtCheck.Pointers[i].DependencySetId ==
6099f7dedc3SAdam Nemet           RtCheck.Pointers[j].DependencySetId)
6100456327cSAdam Nemet        continue;
6110456327cSAdam Nemet       // Only need to check pointers in the same alias set.
6129f7dedc3SAdam Nemet       if (RtCheck.Pointers[i].AliasSetId != RtCheck.Pointers[j].AliasSetId)
6130456327cSAdam Nemet         continue;
6140456327cSAdam Nemet 
6159f7dedc3SAdam Nemet       Value *PtrI = RtCheck.Pointers[i].PointerValue;
6169f7dedc3SAdam Nemet       Value *PtrJ = RtCheck.Pointers[j].PointerValue;
6170456327cSAdam Nemet 
6180456327cSAdam Nemet       unsigned ASi = PtrI->getType()->getPointerAddressSpace();
6190456327cSAdam Nemet       unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
6200456327cSAdam Nemet       if (ASi != ASj) {
621339f42b3SAdam Nemet         DEBUG(dbgs() << "LAA: Runtime check would require comparison between"
6220456327cSAdam Nemet                        " different address spaces\n");
6230456327cSAdam Nemet         return false;
6240456327cSAdam Nemet       }
6250456327cSAdam Nemet     }
6260456327cSAdam Nemet   }
6270456327cSAdam Nemet 
6281b6b50a9SSilviu Baranga   if (NeedRTCheck && CanDoRT)
62915840393SAdam Nemet     RtCheck.generateChecks(DepCands, IsDepCheckNeeded);
6301b6b50a9SSilviu Baranga 
631155e8741SAdam Nemet   DEBUG(dbgs() << "LAA: We need to do " << RtCheck.getNumberOfChecks()
632ee61474aSAdam Nemet                << " pointer comparisons.\n");
633ee61474aSAdam Nemet 
634ee61474aSAdam Nemet   RtCheck.Need = NeedRTCheck;
635ee61474aSAdam Nemet 
636ee61474aSAdam Nemet   bool CanDoRTIfNeeded = !NeedRTCheck || CanDoRT;
637ee61474aSAdam Nemet   if (!CanDoRTIfNeeded)
638ee61474aSAdam Nemet     RtCheck.reset();
639ee61474aSAdam Nemet   return CanDoRTIfNeeded;
6400456327cSAdam Nemet }
6410456327cSAdam Nemet 
6420456327cSAdam Nemet void AccessAnalysis::processMemAccesses() {
6430456327cSAdam Nemet   // We process the set twice: first we process read-write pointers, last we
6440456327cSAdam Nemet   // process read-only pointers. This allows us to skip dependence tests for
6450456327cSAdam Nemet   // read-only pointers.
6460456327cSAdam Nemet 
647339f42b3SAdam Nemet   DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
6480456327cSAdam Nemet   DEBUG(dbgs() << "  AST: "; AST.dump());
6499c926579SAdam Nemet   DEBUG(dbgs() << "LAA:   Accesses(" << Accesses.size() << "):\n");
6500456327cSAdam Nemet   DEBUG({
6510456327cSAdam Nemet     for (auto A : Accesses)
6520456327cSAdam Nemet       dbgs() << "\t" << *A.getPointer() << " (" <<
6530456327cSAdam Nemet                 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
6540456327cSAdam Nemet                                          "read-only" : "read")) << ")\n";
6550456327cSAdam Nemet   });
6560456327cSAdam Nemet 
6570456327cSAdam Nemet   // The AliasSetTracker has nicely partitioned our pointers by metadata
6580456327cSAdam Nemet   // compatibility and potential for underlying-object overlap. As a result, we
6590456327cSAdam Nemet   // only need to check for potential pointer dependencies within each alias
6600456327cSAdam Nemet   // set.
6610456327cSAdam Nemet   for (auto &AS : AST) {
6620456327cSAdam Nemet     // Note that both the alias-set tracker and the alias sets themselves used
6630456327cSAdam Nemet     // linked lists internally and so the iteration order here is deterministic
6640456327cSAdam Nemet     // (matching the original instruction order within each set).
6650456327cSAdam Nemet 
6660456327cSAdam Nemet     bool SetHasWrite = false;
6670456327cSAdam Nemet 
6680456327cSAdam Nemet     // Map of pointers to last access encountered.
6690456327cSAdam Nemet     typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
6700456327cSAdam Nemet     UnderlyingObjToAccessMap ObjToLastAccess;
6710456327cSAdam Nemet 
6720456327cSAdam Nemet     // Set of access to check after all writes have been processed.
6730456327cSAdam Nemet     PtrAccessSet DeferredAccesses;
6740456327cSAdam Nemet 
6750456327cSAdam Nemet     // Iterate over each alias set twice, once to process read/write pointers,
6760456327cSAdam Nemet     // and then to process read-only pointers.
6770456327cSAdam Nemet     for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
6780456327cSAdam Nemet       bool UseDeferred = SetIteration > 0;
6790456327cSAdam Nemet       PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
6800456327cSAdam Nemet 
6810456327cSAdam Nemet       for (auto AV : AS) {
6820456327cSAdam Nemet         Value *Ptr = AV.getValue();
6830456327cSAdam Nemet 
6840456327cSAdam Nemet         // For a single memory access in AliasSetTracker, Accesses may contain
6850456327cSAdam Nemet         // both read and write, and they both need to be handled for CheckDeps.
6860456327cSAdam Nemet         for (auto AC : S) {
6870456327cSAdam Nemet           if (AC.getPointer() != Ptr)
6880456327cSAdam Nemet             continue;
6890456327cSAdam Nemet 
6900456327cSAdam Nemet           bool IsWrite = AC.getInt();
6910456327cSAdam Nemet 
6920456327cSAdam Nemet           // If we're using the deferred access set, then it contains only
6930456327cSAdam Nemet           // reads.
6940456327cSAdam Nemet           bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
6950456327cSAdam Nemet           if (UseDeferred && !IsReadOnlyPtr)
6960456327cSAdam Nemet             continue;
6970456327cSAdam Nemet           // Otherwise, the pointer must be in the PtrAccessSet, either as a
6980456327cSAdam Nemet           // read or a write.
6990456327cSAdam Nemet           assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
7000456327cSAdam Nemet                   S.count(MemAccessInfo(Ptr, false))) &&
7010456327cSAdam Nemet                  "Alias-set pointer not in the access set?");
7020456327cSAdam Nemet 
7030456327cSAdam Nemet           MemAccessInfo Access(Ptr, IsWrite);
7040456327cSAdam Nemet           DepCands.insert(Access);
7050456327cSAdam Nemet 
7060456327cSAdam Nemet           // Memorize read-only pointers for later processing and skip them in
7070456327cSAdam Nemet           // the first round (they need to be checked after we have seen all
7080456327cSAdam Nemet           // write pointers). Note: we also mark pointer that are not
7090456327cSAdam Nemet           // consecutive as "read-only" pointers (so that we check
7100456327cSAdam Nemet           // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
7110456327cSAdam Nemet           if (!UseDeferred && IsReadOnlyPtr) {
7120456327cSAdam Nemet             DeferredAccesses.insert(Access);
7130456327cSAdam Nemet             continue;
7140456327cSAdam Nemet           }
7150456327cSAdam Nemet 
7160456327cSAdam Nemet           // If this is a write - check other reads and writes for conflicts. If
7170456327cSAdam Nemet           // this is a read only check other writes for conflicts (but only if
7180456327cSAdam Nemet           // there is no other write to the ptr - this is an optimization to
7190456327cSAdam Nemet           // catch "a[i] = a[i] + " without having to do a dependence check).
7200456327cSAdam Nemet           if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
7210456327cSAdam Nemet             CheckDeps.insert(Access);
7225dc3b2cfSAdam Nemet             IsRTCheckAnalysisNeeded = true;
7230456327cSAdam Nemet           }
7240456327cSAdam Nemet 
7250456327cSAdam Nemet           if (IsWrite)
7260456327cSAdam Nemet             SetHasWrite = true;
7270456327cSAdam Nemet 
7280456327cSAdam Nemet           // Create sets of pointers connected by a shared alias set and
7290456327cSAdam Nemet           // underlying object.
7300456327cSAdam Nemet           typedef SmallVector<Value *, 16> ValueVector;
7310456327cSAdam Nemet           ValueVector TempObjects;
732e2b885c4SAdam Nemet 
733e2b885c4SAdam Nemet           GetUnderlyingObjects(Ptr, TempObjects, DL, LI);
734e2b885c4SAdam Nemet           DEBUG(dbgs() << "Underlying objects for pointer " << *Ptr << "\n");
7350456327cSAdam Nemet           for (Value *UnderlyingObj : TempObjects) {
7360456327cSAdam Nemet             UnderlyingObjToAccessMap::iterator Prev =
7370456327cSAdam Nemet                 ObjToLastAccess.find(UnderlyingObj);
7380456327cSAdam Nemet             if (Prev != ObjToLastAccess.end())
7390456327cSAdam Nemet               DepCands.unionSets(Access, Prev->second);
7400456327cSAdam Nemet 
7410456327cSAdam Nemet             ObjToLastAccess[UnderlyingObj] = Access;
742e2b885c4SAdam Nemet             DEBUG(dbgs() << "  " << *UnderlyingObj << "\n");
7430456327cSAdam Nemet           }
7440456327cSAdam Nemet         }
7450456327cSAdam Nemet       }
7460456327cSAdam Nemet     }
7470456327cSAdam Nemet   }
7480456327cSAdam Nemet }
7490456327cSAdam Nemet 
7500456327cSAdam Nemet static bool isInBoundsGep(Value *Ptr) {
7510456327cSAdam Nemet   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
7520456327cSAdam Nemet     return GEP->isInBounds();
7530456327cSAdam Nemet   return false;
7540456327cSAdam Nemet }
7550456327cSAdam Nemet 
756c4866d29SAdam Nemet /// \brief Return true if an AddRec pointer \p Ptr is unsigned non-wrapping,
757c4866d29SAdam Nemet /// i.e. monotonically increasing/decreasing.
758c4866d29SAdam Nemet static bool isNoWrapAddRec(Value *Ptr, const SCEVAddRecExpr *AR,
759c4866d29SAdam Nemet                            ScalarEvolution *SE, const Loop *L) {
760c4866d29SAdam Nemet   // FIXME: This should probably only return true for NUW.
761c4866d29SAdam Nemet   if (AR->getNoWrapFlags(SCEV::NoWrapMask))
762c4866d29SAdam Nemet     return true;
763c4866d29SAdam Nemet 
764c4866d29SAdam Nemet   // Scalar evolution does not propagate the non-wrapping flags to values that
765c4866d29SAdam Nemet   // are derived from a non-wrapping induction variable because non-wrapping
766c4866d29SAdam Nemet   // could be flow-sensitive.
767c4866d29SAdam Nemet   //
768c4866d29SAdam Nemet   // Look through the potentially overflowing instruction to try to prove
769c4866d29SAdam Nemet   // non-wrapping for the *specific* value of Ptr.
770c4866d29SAdam Nemet 
771c4866d29SAdam Nemet   // The arithmetic implied by an inbounds GEP can't overflow.
772c4866d29SAdam Nemet   auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
773c4866d29SAdam Nemet   if (!GEP || !GEP->isInBounds())
774c4866d29SAdam Nemet     return false;
775c4866d29SAdam Nemet 
776c4866d29SAdam Nemet   // Make sure there is only one non-const index and analyze that.
777c4866d29SAdam Nemet   Value *NonConstIndex = nullptr;
778c4866d29SAdam Nemet   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
779c4866d29SAdam Nemet     if (!isa<ConstantInt>(*Index)) {
780c4866d29SAdam Nemet       if (NonConstIndex)
781c4866d29SAdam Nemet         return false;
782c4866d29SAdam Nemet       NonConstIndex = *Index;
783c4866d29SAdam Nemet     }
784c4866d29SAdam Nemet   if (!NonConstIndex)
785c4866d29SAdam Nemet     // The recurrence is on the pointer, ignore for now.
786c4866d29SAdam Nemet     return false;
787c4866d29SAdam Nemet 
788c4866d29SAdam Nemet   // The index in GEP is signed.  It is non-wrapping if it's derived from a NSW
789c4866d29SAdam Nemet   // AddRec using a NSW operation.
790c4866d29SAdam Nemet   if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(NonConstIndex))
791c4866d29SAdam Nemet     if (OBO->hasNoSignedWrap() &&
792c4866d29SAdam Nemet         // Assume constant for other the operand so that the AddRec can be
793c4866d29SAdam Nemet         // easily found.
794c4866d29SAdam Nemet         isa<ConstantInt>(OBO->getOperand(1))) {
795c4866d29SAdam Nemet       auto *OpScev = SE->getSCEV(OBO->getOperand(0));
796c4866d29SAdam Nemet 
797c4866d29SAdam Nemet       if (auto *OpAR = dyn_cast<SCEVAddRecExpr>(OpScev))
798c4866d29SAdam Nemet         return OpAR->getLoop() == L && OpAR->getNoWrapFlags(SCEV::FlagNSW);
799c4866d29SAdam Nemet     }
800c4866d29SAdam Nemet 
801c4866d29SAdam Nemet   return false;
802c4866d29SAdam Nemet }
803c4866d29SAdam Nemet 
8040456327cSAdam Nemet /// \brief Check whether the access through \p Ptr has a constant stride.
80532c05396SHao Liu int llvm::isStridedPtr(ScalarEvolution *SE, Value *Ptr, const Loop *Lp,
806a28d91d8SMehdi Amini                        const ValueToValueMap &StridesMap) {
807e3dcce97SCraig Topper   Type *Ty = Ptr->getType();
8080456327cSAdam Nemet   assert(Ty->isPointerTy() && "Unexpected non-ptr");
8090456327cSAdam Nemet 
8100456327cSAdam Nemet   // Make sure that the pointer does not point to aggregate types.
811e3dcce97SCraig Topper   auto *PtrTy = cast<PointerType>(Ty);
8120456327cSAdam Nemet   if (PtrTy->getElementType()->isAggregateType()) {
813339f42b3SAdam Nemet     DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type"
814339f42b3SAdam Nemet           << *Ptr << "\n");
8150456327cSAdam Nemet     return 0;
8160456327cSAdam Nemet   }
8170456327cSAdam Nemet 
8180456327cSAdam Nemet   const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
8190456327cSAdam Nemet 
8200456327cSAdam Nemet   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
8210456327cSAdam Nemet   if (!AR) {
822339f42b3SAdam Nemet     DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer "
82304d4163eSAdam Nemet           << *Ptr << " SCEV: " << *PtrScev << "\n");
8240456327cSAdam Nemet     return 0;
8250456327cSAdam Nemet   }
8260456327cSAdam Nemet 
8270456327cSAdam Nemet   // The accesss function must stride over the innermost loop.
8280456327cSAdam Nemet   if (Lp != AR->getLoop()) {
829339f42b3SAdam Nemet     DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " <<
83004d4163eSAdam Nemet           *Ptr << " SCEV: " << *PtrScev << "\n");
8310456327cSAdam Nemet   }
8320456327cSAdam Nemet 
8330456327cSAdam Nemet   // The address calculation must not wrap. Otherwise, a dependence could be
8340456327cSAdam Nemet   // inverted.
8350456327cSAdam Nemet   // An inbounds getelementptr that is a AddRec with a unit stride
8360456327cSAdam Nemet   // cannot wrap per definition. The unit stride requirement is checked later.
8370456327cSAdam Nemet   // An getelementptr without an inbounds attribute and unit stride would have
8380456327cSAdam Nemet   // to access the pointer value "0" which is undefined behavior in address
8390456327cSAdam Nemet   // space 0, therefore we can also vectorize this case.
8400456327cSAdam Nemet   bool IsInBoundsGEP = isInBoundsGep(Ptr);
841c4866d29SAdam Nemet   bool IsNoWrapAddRec = isNoWrapAddRec(Ptr, AR, SE, Lp);
8420456327cSAdam Nemet   bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
8430456327cSAdam Nemet   if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
844339f42b3SAdam Nemet     DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
8450456327cSAdam Nemet           << *Ptr << " SCEV: " << *PtrScev << "\n");
8460456327cSAdam Nemet     return 0;
8470456327cSAdam Nemet   }
8480456327cSAdam Nemet 
8490456327cSAdam Nemet   // Check the step is constant.
8500456327cSAdam Nemet   const SCEV *Step = AR->getStepRecurrence(*SE);
8510456327cSAdam Nemet 
852943befedSAdam Nemet   // Calculate the pointer stride and check if it is constant.
8530456327cSAdam Nemet   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
8540456327cSAdam Nemet   if (!C) {
855339f42b3SAdam Nemet     DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr <<
85604d4163eSAdam Nemet           " SCEV: " << *PtrScev << "\n");
8570456327cSAdam Nemet     return 0;
8580456327cSAdam Nemet   }
8590456327cSAdam Nemet 
860a28d91d8SMehdi Amini   auto &DL = Lp->getHeader()->getModule()->getDataLayout();
861a28d91d8SMehdi Amini   int64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
8620456327cSAdam Nemet   const APInt &APStepVal = C->getValue()->getValue();
8630456327cSAdam Nemet 
8640456327cSAdam Nemet   // Huge step value - give up.
8650456327cSAdam Nemet   if (APStepVal.getBitWidth() > 64)
8660456327cSAdam Nemet     return 0;
8670456327cSAdam Nemet 
8680456327cSAdam Nemet   int64_t StepVal = APStepVal.getSExtValue();
8690456327cSAdam Nemet 
8700456327cSAdam Nemet   // Strided access.
8710456327cSAdam Nemet   int64_t Stride = StepVal / Size;
8720456327cSAdam Nemet   int64_t Rem = StepVal % Size;
8730456327cSAdam Nemet   if (Rem)
8740456327cSAdam Nemet     return 0;
8750456327cSAdam Nemet 
8760456327cSAdam Nemet   // If the SCEV could wrap but we have an inbounds gep with a unit stride we
8770456327cSAdam Nemet   // know we can't "wrap around the address space". In case of address space
8780456327cSAdam Nemet   // zero we know that this won't happen without triggering undefined behavior.
8790456327cSAdam Nemet   if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
8800456327cSAdam Nemet       Stride != 1 && Stride != -1)
8810456327cSAdam Nemet     return 0;
8820456327cSAdam Nemet 
8830456327cSAdam Nemet   return Stride;
8840456327cSAdam Nemet }
8850456327cSAdam Nemet 
8869c926579SAdam Nemet bool MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
8879c926579SAdam Nemet   switch (Type) {
8889c926579SAdam Nemet   case NoDep:
8899c926579SAdam Nemet   case Forward:
8909c926579SAdam Nemet   case BackwardVectorizable:
8919c926579SAdam Nemet     return true;
8929c926579SAdam Nemet 
8939c926579SAdam Nemet   case Unknown:
8949c926579SAdam Nemet   case ForwardButPreventsForwarding:
8959c926579SAdam Nemet   case Backward:
8969c926579SAdam Nemet   case BackwardVectorizableButPreventsForwarding:
8979c926579SAdam Nemet     return false;
8989c926579SAdam Nemet   }
899d388e930SDavid Majnemer   llvm_unreachable("unexpected DepType!");
9009c926579SAdam Nemet }
9019c926579SAdam Nemet 
9029c926579SAdam Nemet bool MemoryDepChecker::Dependence::isInterestingDependence(DepType Type) {
9039c926579SAdam Nemet   switch (Type) {
9049c926579SAdam Nemet   case NoDep:
9059c926579SAdam Nemet   case Forward:
9069c926579SAdam Nemet     return false;
9079c926579SAdam Nemet 
9089c926579SAdam Nemet   case BackwardVectorizable:
9099c926579SAdam Nemet   case Unknown:
9109c926579SAdam Nemet   case ForwardButPreventsForwarding:
9119c926579SAdam Nemet   case Backward:
9129c926579SAdam Nemet   case BackwardVectorizableButPreventsForwarding:
9139c926579SAdam Nemet     return true;
9149c926579SAdam Nemet   }
915d388e930SDavid Majnemer   llvm_unreachable("unexpected DepType!");
9169c926579SAdam Nemet }
9179c926579SAdam Nemet 
9189c926579SAdam Nemet bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
9199c926579SAdam Nemet   switch (Type) {
9209c926579SAdam Nemet   case NoDep:
9219c926579SAdam Nemet   case Forward:
9229c926579SAdam Nemet   case ForwardButPreventsForwarding:
9239c926579SAdam Nemet     return false;
9249c926579SAdam Nemet 
9259c926579SAdam Nemet   case Unknown:
9269c926579SAdam Nemet   case BackwardVectorizable:
9279c926579SAdam Nemet   case Backward:
9289c926579SAdam Nemet   case BackwardVectorizableButPreventsForwarding:
9299c926579SAdam Nemet     return true;
9309c926579SAdam Nemet   }
931d388e930SDavid Majnemer   llvm_unreachable("unexpected DepType!");
9329c926579SAdam Nemet }
9339c926579SAdam Nemet 
9340456327cSAdam Nemet bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
9350456327cSAdam Nemet                                                     unsigned TypeByteSize) {
9360456327cSAdam Nemet   // If loads occur at a distance that is not a multiple of a feasible vector
9370456327cSAdam Nemet   // factor store-load forwarding does not take place.
9380456327cSAdam Nemet   // Positive dependences might cause troubles because vectorizing them might
9390456327cSAdam Nemet   // prevent store-load forwarding making vectorized code run a lot slower.
9400456327cSAdam Nemet   //   a[i] = a[i-3] ^ a[i-8];
9410456327cSAdam Nemet   //   The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
9420456327cSAdam Nemet   //   hence on your typical architecture store-load forwarding does not take
9430456327cSAdam Nemet   //   place. Vectorizing in such cases does not make sense.
9440456327cSAdam Nemet   // Store-load forwarding distance.
9450456327cSAdam Nemet   const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
9460456327cSAdam Nemet   // Maximum vector factor.
947f219c647SAdam Nemet   unsigned MaxVFWithoutSLForwardIssues =
948f219c647SAdam Nemet     VectorizerParams::MaxVectorWidth * TypeByteSize;
9490456327cSAdam Nemet   if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
9500456327cSAdam Nemet     MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
9510456327cSAdam Nemet 
9520456327cSAdam Nemet   for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
9530456327cSAdam Nemet        vf *= 2) {
9540456327cSAdam Nemet     if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
9550456327cSAdam Nemet       MaxVFWithoutSLForwardIssues = (vf >>=1);
9560456327cSAdam Nemet       break;
9570456327cSAdam Nemet     }
9580456327cSAdam Nemet   }
9590456327cSAdam Nemet 
9600456327cSAdam Nemet   if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
961339f42b3SAdam Nemet     DEBUG(dbgs() << "LAA: Distance " << Distance <<
96204d4163eSAdam Nemet           " that could cause a store-load forwarding conflict\n");
9630456327cSAdam Nemet     return true;
9640456327cSAdam Nemet   }
9650456327cSAdam Nemet 
9660456327cSAdam Nemet   if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
967f219c647SAdam Nemet       MaxVFWithoutSLForwardIssues !=
968f219c647SAdam Nemet       VectorizerParams::MaxVectorWidth * TypeByteSize)
9690456327cSAdam Nemet     MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
9700456327cSAdam Nemet   return false;
9710456327cSAdam Nemet }
9720456327cSAdam Nemet 
973751004a6SHao Liu /// \brief Check the dependence for two accesses with the same stride \p Stride.
974751004a6SHao Liu /// \p Distance is the positive distance and \p TypeByteSize is type size in
975751004a6SHao Liu /// bytes.
976751004a6SHao Liu ///
977751004a6SHao Liu /// \returns true if they are independent.
978751004a6SHao Liu static bool areStridedAccessesIndependent(unsigned Distance, unsigned Stride,
979751004a6SHao Liu                                           unsigned TypeByteSize) {
980751004a6SHao Liu   assert(Stride > 1 && "The stride must be greater than 1");
981751004a6SHao Liu   assert(TypeByteSize > 0 && "The type size in byte must be non-zero");
982751004a6SHao Liu   assert(Distance > 0 && "The distance must be non-zero");
983751004a6SHao Liu 
984751004a6SHao Liu   // Skip if the distance is not multiple of type byte size.
985751004a6SHao Liu   if (Distance % TypeByteSize)
986751004a6SHao Liu     return false;
987751004a6SHao Liu 
988751004a6SHao Liu   unsigned ScaledDist = Distance / TypeByteSize;
989751004a6SHao Liu 
990751004a6SHao Liu   // No dependence if the scaled distance is not multiple of the stride.
991751004a6SHao Liu   // E.g.
992751004a6SHao Liu   //      for (i = 0; i < 1024 ; i += 4)
993751004a6SHao Liu   //        A[i+2] = A[i] + 1;
994751004a6SHao Liu   //
995751004a6SHao Liu   // Two accesses in memory (scaled distance is 2, stride is 4):
996751004a6SHao Liu   //     | A[0] |      |      |      | A[4] |      |      |      |
997751004a6SHao Liu   //     |      |      | A[2] |      |      |      | A[6] |      |
998751004a6SHao Liu   //
999751004a6SHao Liu   // E.g.
1000751004a6SHao Liu   //      for (i = 0; i < 1024 ; i += 3)
1001751004a6SHao Liu   //        A[i+4] = A[i] + 1;
1002751004a6SHao Liu   //
1003751004a6SHao Liu   // Two accesses in memory (scaled distance is 4, stride is 3):
1004751004a6SHao Liu   //     | A[0] |      |      | A[3] |      |      | A[6] |      |      |
1005751004a6SHao Liu   //     |      |      |      |      | A[4] |      |      | A[7] |      |
1006751004a6SHao Liu   return ScaledDist % Stride;
1007751004a6SHao Liu }
1008751004a6SHao Liu 
10099c926579SAdam Nemet MemoryDepChecker::Dependence::DepType
10109c926579SAdam Nemet MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
10110456327cSAdam Nemet                               const MemAccessInfo &B, unsigned BIdx,
10128bc61df9SAdam Nemet                               const ValueToValueMap &Strides) {
10130456327cSAdam Nemet   assert (AIdx < BIdx && "Must pass arguments in program order");
10140456327cSAdam Nemet 
10150456327cSAdam Nemet   Value *APtr = A.getPointer();
10160456327cSAdam Nemet   Value *BPtr = B.getPointer();
10170456327cSAdam Nemet   bool AIsWrite = A.getInt();
10180456327cSAdam Nemet   bool BIsWrite = B.getInt();
10190456327cSAdam Nemet 
10200456327cSAdam Nemet   // Two reads are independent.
10210456327cSAdam Nemet   if (!AIsWrite && !BIsWrite)
10229c926579SAdam Nemet     return Dependence::NoDep;
10230456327cSAdam Nemet 
10240456327cSAdam Nemet   // We cannot check pointers in different address spaces.
10250456327cSAdam Nemet   if (APtr->getType()->getPointerAddressSpace() !=
10260456327cSAdam Nemet       BPtr->getType()->getPointerAddressSpace())
10279c926579SAdam Nemet     return Dependence::Unknown;
10280456327cSAdam Nemet 
10290456327cSAdam Nemet   const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
10300456327cSAdam Nemet   const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
10310456327cSAdam Nemet 
1032a28d91d8SMehdi Amini   int StrideAPtr = isStridedPtr(SE, APtr, InnermostLoop, Strides);
1033a28d91d8SMehdi Amini   int StrideBPtr = isStridedPtr(SE, BPtr, InnermostLoop, Strides);
10340456327cSAdam Nemet 
10350456327cSAdam Nemet   const SCEV *Src = AScev;
10360456327cSAdam Nemet   const SCEV *Sink = BScev;
10370456327cSAdam Nemet 
10380456327cSAdam Nemet   // If the induction step is negative we have to invert source and sink of the
10390456327cSAdam Nemet   // dependence.
10400456327cSAdam Nemet   if (StrideAPtr < 0) {
10410456327cSAdam Nemet     //Src = BScev;
10420456327cSAdam Nemet     //Sink = AScev;
10430456327cSAdam Nemet     std::swap(APtr, BPtr);
10440456327cSAdam Nemet     std::swap(Src, Sink);
10450456327cSAdam Nemet     std::swap(AIsWrite, BIsWrite);
10460456327cSAdam Nemet     std::swap(AIdx, BIdx);
10470456327cSAdam Nemet     std::swap(StrideAPtr, StrideBPtr);
10480456327cSAdam Nemet   }
10490456327cSAdam Nemet 
10500456327cSAdam Nemet   const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
10510456327cSAdam Nemet 
1052339f42b3SAdam Nemet   DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
10530456327cSAdam Nemet         << "(Induction step: " << StrideAPtr <<  ")\n");
1054339f42b3SAdam Nemet   DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
10550456327cSAdam Nemet         << *InstMap[BIdx] << ": " << *Dist << "\n");
10560456327cSAdam Nemet 
1057943befedSAdam Nemet   // Need accesses with constant stride. We don't want to vectorize
10580456327cSAdam Nemet   // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
10590456327cSAdam Nemet   // the address space.
10600456327cSAdam Nemet   if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
1061943befedSAdam Nemet     DEBUG(dbgs() << "Pointer access with non-constant stride\n");
10629c926579SAdam Nemet     return Dependence::Unknown;
10630456327cSAdam Nemet   }
10640456327cSAdam Nemet 
10650456327cSAdam Nemet   const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
10660456327cSAdam Nemet   if (!C) {
1067339f42b3SAdam Nemet     DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
10680456327cSAdam Nemet     ShouldRetryWithRuntimeCheck = true;
10699c926579SAdam Nemet     return Dependence::Unknown;
10700456327cSAdam Nemet   }
10710456327cSAdam Nemet 
10720456327cSAdam Nemet   Type *ATy = APtr->getType()->getPointerElementType();
10730456327cSAdam Nemet   Type *BTy = BPtr->getType()->getPointerElementType();
1074a28d91d8SMehdi Amini   auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
1075a28d91d8SMehdi Amini   unsigned TypeByteSize = DL.getTypeAllocSize(ATy);
10760456327cSAdam Nemet 
10770456327cSAdam Nemet   // Negative distances are not plausible dependencies.
10780456327cSAdam Nemet   const APInt &Val = C->getValue()->getValue();
10790456327cSAdam Nemet   if (Val.isNegative()) {
10800456327cSAdam Nemet     bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
10810456327cSAdam Nemet     if (IsTrueDataDependence &&
10820456327cSAdam Nemet         (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
10830456327cSAdam Nemet          ATy != BTy))
10849c926579SAdam Nemet       return Dependence::ForwardButPreventsForwarding;
10850456327cSAdam Nemet 
1086339f42b3SAdam Nemet     DEBUG(dbgs() << "LAA: Dependence is negative: NoDep\n");
10879c926579SAdam Nemet     return Dependence::Forward;
10880456327cSAdam Nemet   }
10890456327cSAdam Nemet 
10900456327cSAdam Nemet   // Write to the same location with the same size.
10910456327cSAdam Nemet   // Could be improved to assert type sizes are the same (i32 == float, etc).
10920456327cSAdam Nemet   if (Val == 0) {
10930456327cSAdam Nemet     if (ATy == BTy)
10949c926579SAdam Nemet       return Dependence::NoDep;
1095339f42b3SAdam Nemet     DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n");
10969c926579SAdam Nemet     return Dependence::Unknown;
10970456327cSAdam Nemet   }
10980456327cSAdam Nemet 
10990456327cSAdam Nemet   assert(Val.isStrictlyPositive() && "Expect a positive value");
11000456327cSAdam Nemet 
11010456327cSAdam Nemet   if (ATy != BTy) {
110204d4163eSAdam Nemet     DEBUG(dbgs() <<
1103339f42b3SAdam Nemet           "LAA: ReadWrite-Write positive dependency with different types\n");
11049c926579SAdam Nemet     return Dependence::Unknown;
11050456327cSAdam Nemet   }
11060456327cSAdam Nemet 
11070456327cSAdam Nemet   unsigned Distance = (unsigned) Val.getZExtValue();
11080456327cSAdam Nemet 
1109751004a6SHao Liu   unsigned Stride = std::abs(StrideAPtr);
1110751004a6SHao Liu   if (Stride > 1 &&
11110131a569SAdam Nemet       areStridedAccessesIndependent(Distance, Stride, TypeByteSize)) {
11120131a569SAdam Nemet     DEBUG(dbgs() << "LAA: Strided accesses are independent\n");
1113751004a6SHao Liu     return Dependence::NoDep;
11140131a569SAdam Nemet   }
1115751004a6SHao Liu 
11160456327cSAdam Nemet   // Bail out early if passed-in parameters make vectorization not feasible.
1117f219c647SAdam Nemet   unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
1118f219c647SAdam Nemet                            VectorizerParams::VectorizationFactor : 1);
1119f219c647SAdam Nemet   unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
1120f219c647SAdam Nemet                            VectorizerParams::VectorizationInterleave : 1);
1121751004a6SHao Liu   // The minimum number of iterations for a vectorized/unrolled version.
1122751004a6SHao Liu   unsigned MinNumIter = std::max(ForcedFactor * ForcedUnroll, 2U);
11230456327cSAdam Nemet 
1124751004a6SHao Liu   // It's not vectorizable if the distance is smaller than the minimum distance
1125751004a6SHao Liu   // needed for a vectroized/unrolled version. Vectorizing one iteration in
1126751004a6SHao Liu   // front needs TypeByteSize * Stride. Vectorizing the last iteration needs
1127751004a6SHao Liu   // TypeByteSize (No need to plus the last gap distance).
1128751004a6SHao Liu   //
1129751004a6SHao Liu   // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1130751004a6SHao Liu   //      foo(int *A) {
1131751004a6SHao Liu   //        int *B = (int *)((char *)A + 14);
1132751004a6SHao Liu   //        for (i = 0 ; i < 1024 ; i += 2)
1133751004a6SHao Liu   //          B[i] = A[i] + 1;
1134751004a6SHao Liu   //      }
1135751004a6SHao Liu   //
1136751004a6SHao Liu   // Two accesses in memory (stride is 2):
1137751004a6SHao Liu   //     | A[0] |      | A[2] |      | A[4] |      | A[6] |      |
1138751004a6SHao Liu   //                              | B[0] |      | B[2] |      | B[4] |
1139751004a6SHao Liu   //
1140751004a6SHao Liu   // Distance needs for vectorizing iterations except the last iteration:
1141751004a6SHao Liu   // 4 * 2 * (MinNumIter - 1). Distance needs for the last iteration: 4.
1142751004a6SHao Liu   // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4.
1143751004a6SHao Liu   //
1144751004a6SHao Liu   // If MinNumIter is 2, it is vectorizable as the minimum distance needed is
1145751004a6SHao Liu   // 12, which is less than distance.
1146751004a6SHao Liu   //
1147751004a6SHao Liu   // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4),
1148751004a6SHao Liu   // the minimum distance needed is 28, which is greater than distance. It is
1149751004a6SHao Liu   // not safe to do vectorization.
1150751004a6SHao Liu   unsigned MinDistanceNeeded =
1151751004a6SHao Liu       TypeByteSize * Stride * (MinNumIter - 1) + TypeByteSize;
1152751004a6SHao Liu   if (MinDistanceNeeded > Distance) {
1153751004a6SHao Liu     DEBUG(dbgs() << "LAA: Failure because of positive distance " << Distance
1154751004a6SHao Liu                  << '\n');
1155751004a6SHao Liu     return Dependence::Backward;
1156751004a6SHao Liu   }
1157751004a6SHao Liu 
1158751004a6SHao Liu   // Unsafe if the minimum distance needed is greater than max safe distance.
1159751004a6SHao Liu   if (MinDistanceNeeded > MaxSafeDepDistBytes) {
1160751004a6SHao Liu     DEBUG(dbgs() << "LAA: Failure because it needs at least "
1161751004a6SHao Liu                  << MinDistanceNeeded << " size in bytes");
11629c926579SAdam Nemet     return Dependence::Backward;
11630456327cSAdam Nemet   }
11640456327cSAdam Nemet 
11659cc0c399SAdam Nemet   // Positive distance bigger than max vectorization factor.
1166751004a6SHao Liu   // FIXME: Should use max factor instead of max distance in bytes, which could
1167751004a6SHao Liu   // not handle different types.
1168751004a6SHao Liu   // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1169751004a6SHao Liu   //      void foo (int *A, char *B) {
1170751004a6SHao Liu   //        for (unsigned i = 0; i < 1024; i++) {
1171751004a6SHao Liu   //          A[i+2] = A[i] + 1;
1172751004a6SHao Liu   //          B[i+2] = B[i] + 1;
1173751004a6SHao Liu   //        }
1174751004a6SHao Liu   //      }
1175751004a6SHao Liu   //
1176751004a6SHao Liu   // This case is currently unsafe according to the max safe distance. If we
1177751004a6SHao Liu   // analyze the two accesses on array B, the max safe dependence distance
1178751004a6SHao Liu   // is 2. Then we analyze the accesses on array A, the minimum distance needed
1179751004a6SHao Liu   // is 8, which is less than 2 and forbidden vectorization, But actually
1180751004a6SHao Liu   // both A and B could be vectorized by 2 iterations.
1181751004a6SHao Liu   MaxSafeDepDistBytes =
1182751004a6SHao Liu       Distance < MaxSafeDepDistBytes ? Distance : MaxSafeDepDistBytes;
11830456327cSAdam Nemet 
11840456327cSAdam Nemet   bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
11850456327cSAdam Nemet   if (IsTrueDataDependence &&
11860456327cSAdam Nemet       couldPreventStoreLoadForward(Distance, TypeByteSize))
11879c926579SAdam Nemet     return Dependence::BackwardVectorizableButPreventsForwarding;
11880456327cSAdam Nemet 
1189751004a6SHao Liu   DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue()
1190751004a6SHao Liu                << " with max VF = "
1191751004a6SHao Liu                << MaxSafeDepDistBytes / (TypeByteSize * Stride) << '\n');
11920456327cSAdam Nemet 
11939c926579SAdam Nemet   return Dependence::BackwardVectorizable;
11940456327cSAdam Nemet }
11950456327cSAdam Nemet 
1196dee666bcSAdam Nemet bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets,
11970456327cSAdam Nemet                                    MemAccessInfoSet &CheckDeps,
11988bc61df9SAdam Nemet                                    const ValueToValueMap &Strides) {
11990456327cSAdam Nemet 
12000456327cSAdam Nemet   MaxSafeDepDistBytes = -1U;
12010456327cSAdam Nemet   while (!CheckDeps.empty()) {
12020456327cSAdam Nemet     MemAccessInfo CurAccess = *CheckDeps.begin();
12030456327cSAdam Nemet 
12040456327cSAdam Nemet     // Get the relevant memory access set.
12050456327cSAdam Nemet     EquivalenceClasses<MemAccessInfo>::iterator I =
12060456327cSAdam Nemet       AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
12070456327cSAdam Nemet 
12080456327cSAdam Nemet     // Check accesses within this set.
12090456327cSAdam Nemet     EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
12100456327cSAdam Nemet     AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
12110456327cSAdam Nemet 
12120456327cSAdam Nemet     // Check every access pair.
12130456327cSAdam Nemet     while (AI != AE) {
12140456327cSAdam Nemet       CheckDeps.erase(*AI);
12150456327cSAdam Nemet       EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
12160456327cSAdam Nemet       while (OI != AE) {
12170456327cSAdam Nemet         // Check every accessing instruction pair in program order.
12180456327cSAdam Nemet         for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
12190456327cSAdam Nemet              I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
12200456327cSAdam Nemet           for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
12210456327cSAdam Nemet                I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
12229c926579SAdam Nemet             auto A = std::make_pair(&*AI, *I1);
12239c926579SAdam Nemet             auto B = std::make_pair(&*OI, *I2);
12249c926579SAdam Nemet 
12259c926579SAdam Nemet             assert(*I1 != *I2);
12269c926579SAdam Nemet             if (*I1 > *I2)
12279c926579SAdam Nemet               std::swap(A, B);
12289c926579SAdam Nemet 
12299c926579SAdam Nemet             Dependence::DepType Type =
12309c926579SAdam Nemet                 isDependent(*A.first, A.second, *B.first, B.second, Strides);
12319c926579SAdam Nemet             SafeForVectorization &= Dependence::isSafeForVectorization(Type);
12329c926579SAdam Nemet 
12339c926579SAdam Nemet             // Gather dependences unless we accumulated MaxInterestingDependence
12349c926579SAdam Nemet             // dependences.  In that case return as soon as we find the first
12359c926579SAdam Nemet             // unsafe dependence.  This puts a limit on this quadratic
12369c926579SAdam Nemet             // algorithm.
12379c926579SAdam Nemet             if (RecordInterestingDependences) {
12389c926579SAdam Nemet               if (Dependence::isInterestingDependence(Type))
12399c926579SAdam Nemet                 InterestingDependences.push_back(
12409c926579SAdam Nemet                     Dependence(A.second, B.second, Type));
12419c926579SAdam Nemet 
12429c926579SAdam Nemet               if (InterestingDependences.size() >= MaxInterestingDependence) {
12439c926579SAdam Nemet                 RecordInterestingDependences = false;
12449c926579SAdam Nemet                 InterestingDependences.clear();
12459c926579SAdam Nemet                 DEBUG(dbgs() << "Too many dependences, stopped recording\n");
12469c926579SAdam Nemet               }
12479c926579SAdam Nemet             }
12489c926579SAdam Nemet             if (!RecordInterestingDependences && !SafeForVectorization)
12490456327cSAdam Nemet               return false;
12500456327cSAdam Nemet           }
12510456327cSAdam Nemet         ++OI;
12520456327cSAdam Nemet       }
12530456327cSAdam Nemet       AI++;
12540456327cSAdam Nemet     }
12550456327cSAdam Nemet   }
12569c926579SAdam Nemet 
12579c926579SAdam Nemet   DEBUG(dbgs() << "Total Interesting Dependences: "
12589c926579SAdam Nemet                << InterestingDependences.size() << "\n");
12599c926579SAdam Nemet   return SafeForVectorization;
12600456327cSAdam Nemet }
12610456327cSAdam Nemet 
1262ec1e2bb6SAdam Nemet SmallVector<Instruction *, 4>
1263ec1e2bb6SAdam Nemet MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const {
1264ec1e2bb6SAdam Nemet   MemAccessInfo Access(Ptr, isWrite);
1265ec1e2bb6SAdam Nemet   auto &IndexVector = Accesses.find(Access)->second;
1266ec1e2bb6SAdam Nemet 
1267ec1e2bb6SAdam Nemet   SmallVector<Instruction *, 4> Insts;
1268ec1e2bb6SAdam Nemet   std::transform(IndexVector.begin(), IndexVector.end(),
1269ec1e2bb6SAdam Nemet                  std::back_inserter(Insts),
1270ec1e2bb6SAdam Nemet                  [&](unsigned Idx) { return this->InstMap[Idx]; });
1271ec1e2bb6SAdam Nemet   return Insts;
1272ec1e2bb6SAdam Nemet }
1273ec1e2bb6SAdam Nemet 
127458913d65SAdam Nemet const char *MemoryDepChecker::Dependence::DepName[] = {
127558913d65SAdam Nemet     "NoDep", "Unknown", "Forward", "ForwardButPreventsForwarding", "Backward",
127658913d65SAdam Nemet     "BackwardVectorizable", "BackwardVectorizableButPreventsForwarding"};
127758913d65SAdam Nemet 
127858913d65SAdam Nemet void MemoryDepChecker::Dependence::print(
127958913d65SAdam Nemet     raw_ostream &OS, unsigned Depth,
128058913d65SAdam Nemet     const SmallVectorImpl<Instruction *> &Instrs) const {
128158913d65SAdam Nemet   OS.indent(Depth) << DepName[Type] << ":\n";
128258913d65SAdam Nemet   OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
128358913d65SAdam Nemet   OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
128458913d65SAdam Nemet }
128558913d65SAdam Nemet 
1286929c38e8SAdam Nemet bool LoopAccessInfo::canAnalyzeLoop() {
12878dcb3b6aSAdam Nemet   // We need to have a loop header.
12888dcb3b6aSAdam Nemet   DEBUG(dbgs() << "LAA: Found a loop: " <<
12898dcb3b6aSAdam Nemet         TheLoop->getHeader()->getName() << '\n');
12908dcb3b6aSAdam Nemet 
1291929c38e8SAdam Nemet     // We can only analyze innermost loops.
1292929c38e8SAdam Nemet   if (!TheLoop->empty()) {
12938dcb3b6aSAdam Nemet     DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
12942bd6e984SAdam Nemet     emitAnalysis(LoopAccessReport() << "loop is not the innermost loop");
1295929c38e8SAdam Nemet     return false;
1296929c38e8SAdam Nemet   }
1297929c38e8SAdam Nemet 
1298929c38e8SAdam Nemet   // We must have a single backedge.
1299929c38e8SAdam Nemet   if (TheLoop->getNumBackEdges() != 1) {
13008dcb3b6aSAdam Nemet     DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
1301929c38e8SAdam Nemet     emitAnalysis(
13022bd6e984SAdam Nemet         LoopAccessReport() <<
1303929c38e8SAdam Nemet         "loop control flow is not understood by analyzer");
1304929c38e8SAdam Nemet     return false;
1305929c38e8SAdam Nemet   }
1306929c38e8SAdam Nemet 
1307929c38e8SAdam Nemet   // We must have a single exiting block.
1308929c38e8SAdam Nemet   if (!TheLoop->getExitingBlock()) {
13098dcb3b6aSAdam Nemet     DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
1310929c38e8SAdam Nemet     emitAnalysis(
13112bd6e984SAdam Nemet         LoopAccessReport() <<
1312929c38e8SAdam Nemet         "loop control flow is not understood by analyzer");
1313929c38e8SAdam Nemet     return false;
1314929c38e8SAdam Nemet   }
1315929c38e8SAdam Nemet 
1316929c38e8SAdam Nemet   // We only handle bottom-tested loops, i.e. loop in which the condition is
1317929c38e8SAdam Nemet   // checked at the end of each iteration. With that we can assume that all
1318929c38e8SAdam Nemet   // instructions in the loop are executed the same number of times.
1319929c38e8SAdam Nemet   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
13208dcb3b6aSAdam Nemet     DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
1321929c38e8SAdam Nemet     emitAnalysis(
13222bd6e984SAdam Nemet         LoopAccessReport() <<
1323929c38e8SAdam Nemet         "loop control flow is not understood by analyzer");
1324929c38e8SAdam Nemet     return false;
1325929c38e8SAdam Nemet   }
1326929c38e8SAdam Nemet 
1327929c38e8SAdam Nemet   // ScalarEvolution needs to be able to find the exit count.
1328929c38e8SAdam Nemet   const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
1329929c38e8SAdam Nemet   if (ExitCount == SE->getCouldNotCompute()) {
13302bd6e984SAdam Nemet     emitAnalysis(LoopAccessReport() <<
1331929c38e8SAdam Nemet                  "could not determine number of loop iterations");
1332929c38e8SAdam Nemet     DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
1333929c38e8SAdam Nemet     return false;
1334929c38e8SAdam Nemet   }
1335929c38e8SAdam Nemet 
1336929c38e8SAdam Nemet   return true;
1337929c38e8SAdam Nemet }
1338929c38e8SAdam Nemet 
13398bc61df9SAdam Nemet void LoopAccessInfo::analyzeLoop(const ValueToValueMap &Strides) {
13400456327cSAdam Nemet 
13410456327cSAdam Nemet   typedef SmallVector<Value*, 16> ValueVector;
13420456327cSAdam Nemet   typedef SmallPtrSet<Value*, 16> ValueSet;
13430456327cSAdam Nemet 
13440456327cSAdam Nemet   // Holds the Load and Store *instructions*.
13450456327cSAdam Nemet   ValueVector Loads;
13460456327cSAdam Nemet   ValueVector Stores;
13470456327cSAdam Nemet 
13480456327cSAdam Nemet   // Holds all the different accesses in the loop.
13490456327cSAdam Nemet   unsigned NumReads = 0;
13500456327cSAdam Nemet   unsigned NumReadWrites = 0;
13510456327cSAdam Nemet 
13527cdebac0SAdam Nemet   PtrRtChecking.Pointers.clear();
13537cdebac0SAdam Nemet   PtrRtChecking.Need = false;
13540456327cSAdam Nemet 
13550456327cSAdam Nemet   const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
13560456327cSAdam Nemet 
13570456327cSAdam Nemet   // For each block.
13580456327cSAdam Nemet   for (Loop::block_iterator bb = TheLoop->block_begin(),
13590456327cSAdam Nemet        be = TheLoop->block_end(); bb != be; ++bb) {
13600456327cSAdam Nemet 
13610456327cSAdam Nemet     // Scan the BB and collect legal loads and stores.
13620456327cSAdam Nemet     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
13630456327cSAdam Nemet          ++it) {
13640456327cSAdam Nemet 
13650456327cSAdam Nemet       // If this is a load, save it. If this instruction can read from memory
13660456327cSAdam Nemet       // but is not a load, then we quit. Notice that we don't handle function
13670456327cSAdam Nemet       // calls that read or write.
13680456327cSAdam Nemet       if (it->mayReadFromMemory()) {
13690456327cSAdam Nemet         // Many math library functions read the rounding mode. We will only
13700456327cSAdam Nemet         // vectorize a loop if it contains known function calls that don't set
13710456327cSAdam Nemet         // the flag. Therefore, it is safe to ignore this read from memory.
13720456327cSAdam Nemet         CallInst *Call = dyn_cast<CallInst>(it);
13730456327cSAdam Nemet         if (Call && getIntrinsicIDForCall(Call, TLI))
13740456327cSAdam Nemet           continue;
13750456327cSAdam Nemet 
13769b3cf604SMichael Zolotukhin         // If the function has an explicit vectorized counterpart, we can safely
13779b3cf604SMichael Zolotukhin         // assume that it can be vectorized.
13789b3cf604SMichael Zolotukhin         if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
13799b3cf604SMichael Zolotukhin             TLI->isFunctionVectorizable(Call->getCalledFunction()->getName()))
13809b3cf604SMichael Zolotukhin           continue;
13819b3cf604SMichael Zolotukhin 
13820456327cSAdam Nemet         LoadInst *Ld = dyn_cast<LoadInst>(it);
13830456327cSAdam Nemet         if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
13842bd6e984SAdam Nemet           emitAnalysis(LoopAccessReport(Ld)
13850456327cSAdam Nemet                        << "read with atomic ordering or volatile read");
1386339f42b3SAdam Nemet           DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
1387436018c3SAdam Nemet           CanVecMem = false;
1388436018c3SAdam Nemet           return;
13890456327cSAdam Nemet         }
13900456327cSAdam Nemet         NumLoads++;
13910456327cSAdam Nemet         Loads.push_back(Ld);
13920456327cSAdam Nemet         DepChecker.addAccess(Ld);
13930456327cSAdam Nemet         continue;
13940456327cSAdam Nemet       }
13950456327cSAdam Nemet 
13960456327cSAdam Nemet       // Save 'store' instructions. Abort if other instructions write to memory.
13970456327cSAdam Nemet       if (it->mayWriteToMemory()) {
13980456327cSAdam Nemet         StoreInst *St = dyn_cast<StoreInst>(it);
13990456327cSAdam Nemet         if (!St) {
14002bd6e984SAdam Nemet           emitAnalysis(LoopAccessReport(it) <<
140104d4163eSAdam Nemet                        "instruction cannot be vectorized");
1402436018c3SAdam Nemet           CanVecMem = false;
1403436018c3SAdam Nemet           return;
14040456327cSAdam Nemet         }
14050456327cSAdam Nemet         if (!St->isSimple() && !IsAnnotatedParallel) {
14062bd6e984SAdam Nemet           emitAnalysis(LoopAccessReport(St)
14070456327cSAdam Nemet                        << "write with atomic ordering or volatile write");
1408339f42b3SAdam Nemet           DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
1409436018c3SAdam Nemet           CanVecMem = false;
1410436018c3SAdam Nemet           return;
14110456327cSAdam Nemet         }
14120456327cSAdam Nemet         NumStores++;
14130456327cSAdam Nemet         Stores.push_back(St);
14140456327cSAdam Nemet         DepChecker.addAccess(St);
14150456327cSAdam Nemet       }
14160456327cSAdam Nemet     } // Next instr.
14170456327cSAdam Nemet   } // Next block.
14180456327cSAdam Nemet 
14190456327cSAdam Nemet   // Now we have two lists that hold the loads and the stores.
14200456327cSAdam Nemet   // Next, we find the pointers that they use.
14210456327cSAdam Nemet 
14220456327cSAdam Nemet   // Check if we see any stores. If there are no stores, then we don't
14230456327cSAdam Nemet   // care if the pointers are *restrict*.
14240456327cSAdam Nemet   if (!Stores.size()) {
1425339f42b3SAdam Nemet     DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
1426436018c3SAdam Nemet     CanVecMem = true;
1427436018c3SAdam Nemet     return;
14280456327cSAdam Nemet   }
14290456327cSAdam Nemet 
1430dee666bcSAdam Nemet   MemoryDepChecker::DepCandidates DependentAccesses;
1431a28d91d8SMehdi Amini   AccessAnalysis Accesses(TheLoop->getHeader()->getModule()->getDataLayout(),
1432e2b885c4SAdam Nemet                           AA, LI, DependentAccesses);
14330456327cSAdam Nemet 
14340456327cSAdam Nemet   // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
14350456327cSAdam Nemet   // multiple times on the same object. If the ptr is accessed twice, once
14360456327cSAdam Nemet   // for read and once for write, it will only appear once (on the write
14370456327cSAdam Nemet   // list). This is okay, since we are going to check for conflicts between
14380456327cSAdam Nemet   // writes and between reads and writes, but not between reads and reads.
14390456327cSAdam Nemet   ValueSet Seen;
14400456327cSAdam Nemet 
14410456327cSAdam Nemet   ValueVector::iterator I, IE;
14420456327cSAdam Nemet   for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
14430456327cSAdam Nemet     StoreInst *ST = cast<StoreInst>(*I);
14440456327cSAdam Nemet     Value* Ptr = ST->getPointerOperand();
1445ce48250fSAdam Nemet     // Check for store to loop invariant address.
1446ce48250fSAdam Nemet     StoreToLoopInvariantAddress |= isUniform(Ptr);
14470456327cSAdam Nemet     // If we did *not* see this pointer before, insert it to  the read-write
14480456327cSAdam Nemet     // list. At this phase it is only a 'write' list.
14490456327cSAdam Nemet     if (Seen.insert(Ptr).second) {
14500456327cSAdam Nemet       ++NumReadWrites;
14510456327cSAdam Nemet 
1452ac80dc75SChandler Carruth       MemoryLocation Loc = MemoryLocation::get(ST);
14530456327cSAdam Nemet       // The TBAA metadata could have a control dependency on the predication
14540456327cSAdam Nemet       // condition, so we cannot rely on it when determining whether or not we
14550456327cSAdam Nemet       // need runtime pointer checks.
145601abb2c3SAdam Nemet       if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
14570456327cSAdam Nemet         Loc.AATags.TBAA = nullptr;
14580456327cSAdam Nemet 
14590456327cSAdam Nemet       Accesses.addStore(Loc);
14600456327cSAdam Nemet     }
14610456327cSAdam Nemet   }
14620456327cSAdam Nemet 
14630456327cSAdam Nemet   if (IsAnnotatedParallel) {
146404d4163eSAdam Nemet     DEBUG(dbgs()
1465339f42b3SAdam Nemet           << "LAA: A loop annotated parallel, ignore memory dependency "
14660456327cSAdam Nemet           << "checks.\n");
1467436018c3SAdam Nemet     CanVecMem = true;
1468436018c3SAdam Nemet     return;
14690456327cSAdam Nemet   }
14700456327cSAdam Nemet 
14710456327cSAdam Nemet   for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
14720456327cSAdam Nemet     LoadInst *LD = cast<LoadInst>(*I);
14730456327cSAdam Nemet     Value* Ptr = LD->getPointerOperand();
14740456327cSAdam Nemet     // If we did *not* see this pointer before, insert it to the
14750456327cSAdam Nemet     // read list. If we *did* see it before, then it is already in
14760456327cSAdam Nemet     // the read-write list. This allows us to vectorize expressions
14770456327cSAdam Nemet     // such as A[i] += x;  Because the address of A[i] is a read-write
14780456327cSAdam Nemet     // pointer. This only works if the index of A[i] is consecutive.
14790456327cSAdam Nemet     // If the address of i is unknown (for example A[B[i]]) then we may
14800456327cSAdam Nemet     // read a few words, modify, and write a few words, and some of the
14810456327cSAdam Nemet     // words may be written to the same address.
14820456327cSAdam Nemet     bool IsReadOnlyPtr = false;
1483a28d91d8SMehdi Amini     if (Seen.insert(Ptr).second || !isStridedPtr(SE, Ptr, TheLoop, Strides)) {
14840456327cSAdam Nemet       ++NumReads;
14850456327cSAdam Nemet       IsReadOnlyPtr = true;
14860456327cSAdam Nemet     }
14870456327cSAdam Nemet 
1488ac80dc75SChandler Carruth     MemoryLocation Loc = MemoryLocation::get(LD);
14890456327cSAdam Nemet     // The TBAA metadata could have a control dependency on the predication
14900456327cSAdam Nemet     // condition, so we cannot rely on it when determining whether or not we
14910456327cSAdam Nemet     // need runtime pointer checks.
149201abb2c3SAdam Nemet     if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
14930456327cSAdam Nemet       Loc.AATags.TBAA = nullptr;
14940456327cSAdam Nemet 
14950456327cSAdam Nemet     Accesses.addLoad(Loc, IsReadOnlyPtr);
14960456327cSAdam Nemet   }
14970456327cSAdam Nemet 
14980456327cSAdam Nemet   // If we write (or read-write) to a single destination and there are no
14990456327cSAdam Nemet   // other reads in this loop then is it safe to vectorize.
15000456327cSAdam Nemet   if (NumReadWrites == 1 && NumReads == 0) {
1501339f42b3SAdam Nemet     DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
1502436018c3SAdam Nemet     CanVecMem = true;
1503436018c3SAdam Nemet     return;
15040456327cSAdam Nemet   }
15050456327cSAdam Nemet 
15060456327cSAdam Nemet   // Build dependence sets and check whether we need a runtime pointer bounds
15070456327cSAdam Nemet   // check.
15080456327cSAdam Nemet   Accesses.buildDependenceSets();
15090456327cSAdam Nemet 
15100456327cSAdam Nemet   // Find pointers with computable bounds. We are going to use this information
15110456327cSAdam Nemet   // to place a runtime bound check.
1512ee61474aSAdam Nemet   bool CanDoRTIfNeeded =
15137cdebac0SAdam Nemet       Accesses.canCheckPtrAtRT(PtrRtChecking, SE, TheLoop, Strides);
1514ee61474aSAdam Nemet   if (!CanDoRTIfNeeded) {
15152bd6e984SAdam Nemet     emitAnalysis(LoopAccessReport() << "cannot identify array bounds");
1516ee61474aSAdam Nemet     DEBUG(dbgs() << "LAA: We can't vectorize because we can't find "
1517ee61474aSAdam Nemet                  << "the array bounds.\n");
1518436018c3SAdam Nemet     CanVecMem = false;
1519436018c3SAdam Nemet     return;
15200456327cSAdam Nemet   }
15210456327cSAdam Nemet 
1522ee61474aSAdam Nemet   DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
15230456327cSAdam Nemet 
1524436018c3SAdam Nemet   CanVecMem = true;
15250456327cSAdam Nemet   if (Accesses.isDependencyCheckNeeded()) {
1526339f42b3SAdam Nemet     DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
15270456327cSAdam Nemet     CanVecMem = DepChecker.areDepsSafe(
15280456327cSAdam Nemet         DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
15290456327cSAdam Nemet     MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
15300456327cSAdam Nemet 
15310456327cSAdam Nemet     if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
1532339f42b3SAdam Nemet       DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
15330456327cSAdam Nemet 
15340456327cSAdam Nemet       // Clear the dependency checks. We assume they are not needed.
1535df3dc5b9SAdam Nemet       Accesses.resetDepChecks(DepChecker);
15360456327cSAdam Nemet 
15377cdebac0SAdam Nemet       PtrRtChecking.reset();
15387cdebac0SAdam Nemet       PtrRtChecking.Need = true;
15390456327cSAdam Nemet 
1540ee61474aSAdam Nemet       CanDoRTIfNeeded =
15417cdebac0SAdam Nemet           Accesses.canCheckPtrAtRT(PtrRtChecking, SE, TheLoop, Strides, true);
154298a13719SSilviu Baranga 
1543949e91a6SAdam Nemet       // Check that we found the bounds for the pointer.
1544ee61474aSAdam Nemet       if (!CanDoRTIfNeeded) {
15452bd6e984SAdam Nemet         emitAnalysis(LoopAccessReport()
15460456327cSAdam Nemet                      << "cannot check memory dependencies at runtime");
1547b6dc76ffSAdam Nemet         DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
1548b6dc76ffSAdam Nemet         CanVecMem = false;
1549b6dc76ffSAdam Nemet         return;
1550b6dc76ffSAdam Nemet       }
1551b6dc76ffSAdam Nemet 
15520456327cSAdam Nemet       CanVecMem = true;
15530456327cSAdam Nemet     }
15540456327cSAdam Nemet   }
15550456327cSAdam Nemet 
15564bb90a71SAdam Nemet   if (CanVecMem)
15574bb90a71SAdam Nemet     DEBUG(dbgs() << "LAA: No unsafe dependent memory operations in loop.  We"
15587cdebac0SAdam Nemet                  << (PtrRtChecking.Need ? "" : " don't")
15590f67c6c1SAdam Nemet                  << " need runtime memory checks.\n");
15604bb90a71SAdam Nemet   else {
15612bd6e984SAdam Nemet     emitAnalysis(LoopAccessReport() <<
156204d4163eSAdam Nemet                  "unsafe dependent memory operations in loop");
15634bb90a71SAdam Nemet     DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
15644bb90a71SAdam Nemet   }
15650456327cSAdam Nemet }
15660456327cSAdam Nemet 
156701abb2c3SAdam Nemet bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
156801abb2c3SAdam Nemet                                            DominatorTree *DT)  {
15690456327cSAdam Nemet   assert(TheLoop->contains(BB) && "Unknown block used");
15700456327cSAdam Nemet 
15710456327cSAdam Nemet   // Blocks that do not dominate the latch need predication.
15720456327cSAdam Nemet   BasicBlock* Latch = TheLoop->getLoopLatch();
15730456327cSAdam Nemet   return !DT->dominates(BB, Latch);
15740456327cSAdam Nemet }
15750456327cSAdam Nemet 
15762bd6e984SAdam Nemet void LoopAccessInfo::emitAnalysis(LoopAccessReport &Message) {
1577c922853bSAdam Nemet   assert(!Report && "Multiple reports generated");
1578c922853bSAdam Nemet   Report = Message;
15790456327cSAdam Nemet }
15800456327cSAdam Nemet 
158157ac766eSAdam Nemet bool LoopAccessInfo::isUniform(Value *V) const {
15820456327cSAdam Nemet   return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
15830456327cSAdam Nemet }
15847206d7a5SAdam Nemet 
15857206d7a5SAdam Nemet // FIXME: this function is currently a duplicate of the one in
15867206d7a5SAdam Nemet // LoopVectorize.cpp.
15877206d7a5SAdam Nemet static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
15887206d7a5SAdam Nemet                                  Instruction *Loc) {
15897206d7a5SAdam Nemet   if (FirstInst)
15907206d7a5SAdam Nemet     return FirstInst;
15917206d7a5SAdam Nemet   if (Instruction *I = dyn_cast<Instruction>(V))
15927206d7a5SAdam Nemet     return I->getParent() == Loc->getParent() ? I : nullptr;
15937206d7a5SAdam Nemet   return nullptr;
15947206d7a5SAdam Nemet }
15957206d7a5SAdam Nemet 
1596*4e533ef7SAdam Nemet /// \brief IR Values for the lower and upper bounds of a pointer evolution.  We
1597*4e533ef7SAdam Nemet /// need to use value-handles because SCEV expansion can invalidate previously
1598*4e533ef7SAdam Nemet /// expanded values.  Thus expansion of a pointer can invalidate the bounds for
1599*4e533ef7SAdam Nemet /// a previous one.
16001da7df37SAdam Nemet struct PointerBounds {
1601*4e533ef7SAdam Nemet   TrackingVH<Value> Start;
1602*4e533ef7SAdam Nemet   TrackingVH<Value> End;
16031da7df37SAdam Nemet };
16047206d7a5SAdam Nemet 
16051da7df37SAdam Nemet /// \brief Expand code for the lower and upper bound of the pointer group \p CG
16061da7df37SAdam Nemet /// in \p TheLoop.  \return the values for the bounds.
16071da7df37SAdam Nemet static PointerBounds
16081da7df37SAdam Nemet expandBounds(const RuntimePointerChecking::CheckingPtrGroup *CG, Loop *TheLoop,
16091da7df37SAdam Nemet              Instruction *Loc, SCEVExpander &Exp, ScalarEvolution *SE,
16101da7df37SAdam Nemet              const RuntimePointerChecking &PtrRtChecking) {
16111da7df37SAdam Nemet   Value *Ptr = PtrRtChecking.Pointers[CG->Members[0]].PointerValue;
16127206d7a5SAdam Nemet   const SCEV *Sc = SE->getSCEV(Ptr);
16137206d7a5SAdam Nemet 
16147206d7a5SAdam Nemet   if (SE->isLoopInvariant(Sc, TheLoop)) {
16151b6b50a9SSilviu Baranga     DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" << *Ptr
16161b6b50a9SSilviu Baranga                  << "\n");
16171da7df37SAdam Nemet     return {Ptr, Ptr};
16187206d7a5SAdam Nemet   } else {
16197206d7a5SAdam Nemet     unsigned AS = Ptr->getType()->getPointerAddressSpace();
16201da7df37SAdam Nemet     LLVMContext &Ctx = Loc->getContext();
16217206d7a5SAdam Nemet 
16227206d7a5SAdam Nemet     // Use this type for pointer arithmetic.
16237206d7a5SAdam Nemet     Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
16241b6b50a9SSilviu Baranga     Value *Start = nullptr, *End = nullptr;
16257206d7a5SAdam Nemet 
16261b6b50a9SSilviu Baranga     DEBUG(dbgs() << "LAA: Adding RT check for range:\n");
16271da7df37SAdam Nemet     Start = Exp.expandCodeFor(CG->Low, PtrArithTy, Loc);
16281da7df37SAdam Nemet     End = Exp.expandCodeFor(CG->High, PtrArithTy, Loc);
16291da7df37SAdam Nemet     DEBUG(dbgs() << "Start: " << *CG->Low << " End: " << *CG->High << "\n");
16301da7df37SAdam Nemet     return {Start, End};
16317206d7a5SAdam Nemet   }
16327206d7a5SAdam Nemet }
16337206d7a5SAdam Nemet 
16341da7df37SAdam Nemet /// \brief Turns a collection of checks into a collection of expanded upper and
16351da7df37SAdam Nemet /// lower bounds for both pointers in the check.
16361da7df37SAdam Nemet static SmallVector<std::pair<PointerBounds, PointerBounds>, 4> expandBounds(
16371da7df37SAdam Nemet     const SmallVectorImpl<RuntimePointerChecking::PointerCheck> &PointerChecks,
16381da7df37SAdam Nemet     Loop *L, Instruction *Loc, ScalarEvolution *SE, SCEVExpander &Exp,
16391da7df37SAdam Nemet     const RuntimePointerChecking &PtrRtChecking) {
16401da7df37SAdam Nemet   SmallVector<std::pair<PointerBounds, PointerBounds>, 4> ChecksWithBounds;
16411da7df37SAdam Nemet 
16421da7df37SAdam Nemet   // Here we're relying on the SCEV Expander's cache to only emit code for the
16431da7df37SAdam Nemet   // same bounds once.
16441da7df37SAdam Nemet   std::transform(
16451da7df37SAdam Nemet       PointerChecks.begin(), PointerChecks.end(),
16461da7df37SAdam Nemet       std::back_inserter(ChecksWithBounds),
16471da7df37SAdam Nemet       [&](const RuntimePointerChecking::PointerCheck &Check) {
164894abbbd6SNAKAMURA Takumi         PointerBounds
164994abbbd6SNAKAMURA Takumi           First = expandBounds(Check.first, L, Loc, Exp, SE, PtrRtChecking),
165094abbbd6SNAKAMURA Takumi           Second = expandBounds(Check.second, L, Loc, Exp, SE, PtrRtChecking);
165194abbbd6SNAKAMURA Takumi         return std::make_pair(First, Second);
16521da7df37SAdam Nemet       });
16531da7df37SAdam Nemet 
16541da7df37SAdam Nemet   return ChecksWithBounds;
16551da7df37SAdam Nemet }
16561da7df37SAdam Nemet 
16575b0a4795SAdam Nemet std::pair<Instruction *, Instruction *> LoopAccessInfo::addRuntimeChecks(
16581da7df37SAdam Nemet     Instruction *Loc,
16591da7df37SAdam Nemet     const SmallVectorImpl<RuntimePointerChecking::PointerCheck> &PointerChecks)
16601da7df37SAdam Nemet     const {
16611da7df37SAdam Nemet 
16621da7df37SAdam Nemet   SCEVExpander Exp(*SE, DL, "induction");
16631da7df37SAdam Nemet   auto ExpandedChecks =
16641da7df37SAdam Nemet       expandBounds(PointerChecks, TheLoop, Loc, SE, Exp, PtrRtChecking);
16651da7df37SAdam Nemet 
16661da7df37SAdam Nemet   LLVMContext &Ctx = Loc->getContext();
16671da7df37SAdam Nemet   Instruction *FirstInst = nullptr;
16687206d7a5SAdam Nemet   IRBuilder<> ChkBuilder(Loc);
16697206d7a5SAdam Nemet   // Our instructions might fold to a constant.
16707206d7a5SAdam Nemet   Value *MemoryRuntimeCheck = nullptr;
16711b6b50a9SSilviu Baranga 
16721da7df37SAdam Nemet   for (const auto &Check : ExpandedChecks) {
16731da7df37SAdam Nemet     const PointerBounds &A = Check.first, &B = Check.second;
1674cdb791cdSAdam Nemet     // Check if two pointers (A and B) conflict where conflict is computed as:
1675cdb791cdSAdam Nemet     // start(A) <= end(B) && start(B) <= end(A)
16761da7df37SAdam Nemet     unsigned AS0 = A.Start->getType()->getPointerAddressSpace();
16771da7df37SAdam Nemet     unsigned AS1 = B.Start->getType()->getPointerAddressSpace();
16787206d7a5SAdam Nemet 
16791da7df37SAdam Nemet     assert((AS0 == B.End->getType()->getPointerAddressSpace()) &&
16801da7df37SAdam Nemet            (AS1 == A.End->getType()->getPointerAddressSpace()) &&
16817206d7a5SAdam Nemet            "Trying to bounds check pointers with different address spaces");
16827206d7a5SAdam Nemet 
16837206d7a5SAdam Nemet     Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
16847206d7a5SAdam Nemet     Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
16857206d7a5SAdam Nemet 
16861da7df37SAdam Nemet     Value *Start0 = ChkBuilder.CreateBitCast(A.Start, PtrArithTy0, "bc");
16871da7df37SAdam Nemet     Value *Start1 = ChkBuilder.CreateBitCast(B.Start, PtrArithTy1, "bc");
16881da7df37SAdam Nemet     Value *End0 =   ChkBuilder.CreateBitCast(A.End,   PtrArithTy1, "bc");
16891da7df37SAdam Nemet     Value *End1 =   ChkBuilder.CreateBitCast(B.End,   PtrArithTy0, "bc");
16907206d7a5SAdam Nemet 
16917206d7a5SAdam Nemet     Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
16927206d7a5SAdam Nemet     FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
16937206d7a5SAdam Nemet     Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
16947206d7a5SAdam Nemet     FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
16957206d7a5SAdam Nemet     Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
16967206d7a5SAdam Nemet     FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
16977206d7a5SAdam Nemet     if (MemoryRuntimeCheck) {
16981da7df37SAdam Nemet       IsConflict =
16991da7df37SAdam Nemet           ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx");
17007206d7a5SAdam Nemet       FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
17017206d7a5SAdam Nemet     }
17027206d7a5SAdam Nemet     MemoryRuntimeCheck = IsConflict;
17037206d7a5SAdam Nemet   }
17047206d7a5SAdam Nemet 
170590fec840SAdam Nemet   if (!MemoryRuntimeCheck)
170690fec840SAdam Nemet     return std::make_pair(nullptr, nullptr);
170790fec840SAdam Nemet 
17087206d7a5SAdam Nemet   // We have to do this trickery because the IRBuilder might fold the check to a
17097206d7a5SAdam Nemet   // constant expression in which case there is no Instruction anchored in a
17107206d7a5SAdam Nemet   // the block.
17117206d7a5SAdam Nemet   Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
17127206d7a5SAdam Nemet                                                  ConstantInt::getTrue(Ctx));
17137206d7a5SAdam Nemet   ChkBuilder.Insert(Check, "memcheck.conflict");
17147206d7a5SAdam Nemet   FirstInst = getFirstInst(FirstInst, Check, Loc);
17157206d7a5SAdam Nemet   return std::make_pair(FirstInst, Check);
17167206d7a5SAdam Nemet }
17173bfd93d7SAdam Nemet 
17185b0a4795SAdam Nemet std::pair<Instruction *, Instruction *>
17195b0a4795SAdam Nemet LoopAccessInfo::addRuntimeChecks(Instruction *Loc) const {
17201da7df37SAdam Nemet   if (!PtrRtChecking.Need)
17211da7df37SAdam Nemet     return std::make_pair(nullptr, nullptr);
17221da7df37SAdam Nemet 
17235b0a4795SAdam Nemet   return addRuntimeChecks(Loc, PtrRtChecking.getChecks());
17241da7df37SAdam Nemet }
17251da7df37SAdam Nemet 
17263bfd93d7SAdam Nemet LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
1727a28d91d8SMehdi Amini                                const DataLayout &DL,
17283bfd93d7SAdam Nemet                                const TargetLibraryInfo *TLI, AliasAnalysis *AA,
1729e2b885c4SAdam Nemet                                DominatorTree *DT, LoopInfo *LI,
17308bc61df9SAdam Nemet                                const ValueToValueMap &Strides)
17317cdebac0SAdam Nemet     : PtrRtChecking(SE), DepChecker(SE, L), TheLoop(L), SE(SE), DL(DL),
17327cdebac0SAdam Nemet       TLI(TLI), AA(AA), DT(DT), LI(LI), NumLoads(0), NumStores(0),
1733ce48250fSAdam Nemet       MaxSafeDepDistBytes(-1U), CanVecMem(false),
1734ce48250fSAdam Nemet       StoreToLoopInvariantAddress(false) {
1735929c38e8SAdam Nemet   if (canAnalyzeLoop())
17363bfd93d7SAdam Nemet     analyzeLoop(Strides);
17373bfd93d7SAdam Nemet }
17383bfd93d7SAdam Nemet 
1739e91cc6efSAdam Nemet void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
1740e91cc6efSAdam Nemet   if (CanVecMem) {
17417cdebac0SAdam Nemet     if (PtrRtChecking.Need)
1742e91cc6efSAdam Nemet       OS.indent(Depth) << "Memory dependences are safe with run-time checks\n";
174326da8e98SAdam Nemet     else
174426da8e98SAdam Nemet       OS.indent(Depth) << "Memory dependences are safe\n";
1745e91cc6efSAdam Nemet   }
1746e91cc6efSAdam Nemet 
1747e91cc6efSAdam Nemet   if (Report)
1748e91cc6efSAdam Nemet     OS.indent(Depth) << "Report: " << Report->str() << "\n";
1749e91cc6efSAdam Nemet 
175058913d65SAdam Nemet   if (auto *InterestingDependences = DepChecker.getInterestingDependences()) {
175158913d65SAdam Nemet     OS.indent(Depth) << "Interesting Dependences:\n";
175258913d65SAdam Nemet     for (auto &Dep : *InterestingDependences) {
175358913d65SAdam Nemet       Dep.print(OS, Depth + 2, DepChecker.getMemoryInstructions());
175458913d65SAdam Nemet       OS << "\n";
175558913d65SAdam Nemet     }
175658913d65SAdam Nemet   } else
175758913d65SAdam Nemet     OS.indent(Depth) << "Too many interesting dependences, not recorded\n";
1758e91cc6efSAdam Nemet 
1759e91cc6efSAdam Nemet   // List the pair of accesses need run-time checks to prove independence.
17607cdebac0SAdam Nemet   PtrRtChecking.print(OS, Depth);
1761e91cc6efSAdam Nemet   OS << "\n";
1762c3384320SAdam Nemet 
1763c3384320SAdam Nemet   OS.indent(Depth) << "Store to invariant address was "
1764c3384320SAdam Nemet                    << (StoreToLoopInvariantAddress ? "" : "not ")
1765c3384320SAdam Nemet                    << "found in loop.\n";
1766e91cc6efSAdam Nemet }
1767e91cc6efSAdam Nemet 
17688bc61df9SAdam Nemet const LoopAccessInfo &
17698bc61df9SAdam Nemet LoopAccessAnalysis::getInfo(Loop *L, const ValueToValueMap &Strides) {
17703bfd93d7SAdam Nemet   auto &LAI = LoopAccessInfoMap[L];
17713bfd93d7SAdam Nemet 
17723bfd93d7SAdam Nemet #ifndef NDEBUG
17733bfd93d7SAdam Nemet   assert((!LAI || LAI->NumSymbolicStrides == Strides.size()) &&
17743bfd93d7SAdam Nemet          "Symbolic strides changed for loop");
17753bfd93d7SAdam Nemet #endif
17763bfd93d7SAdam Nemet 
17773bfd93d7SAdam Nemet   if (!LAI) {
1778a28d91d8SMehdi Amini     const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
1779e2b885c4SAdam Nemet     LAI = llvm::make_unique<LoopAccessInfo>(L, SE, DL, TLI, AA, DT, LI,
1780e2b885c4SAdam Nemet                                             Strides);
17813bfd93d7SAdam Nemet #ifndef NDEBUG
17823bfd93d7SAdam Nemet     LAI->NumSymbolicStrides = Strides.size();
17833bfd93d7SAdam Nemet #endif
17843bfd93d7SAdam Nemet   }
17853bfd93d7SAdam Nemet   return *LAI.get();
17863bfd93d7SAdam Nemet }
17873bfd93d7SAdam Nemet 
1788e91cc6efSAdam Nemet void LoopAccessAnalysis::print(raw_ostream &OS, const Module *M) const {
1789e91cc6efSAdam Nemet   LoopAccessAnalysis &LAA = *const_cast<LoopAccessAnalysis *>(this);
1790e91cc6efSAdam Nemet 
1791e91cc6efSAdam Nemet   ValueToValueMap NoSymbolicStrides;
1792e91cc6efSAdam Nemet 
1793e91cc6efSAdam Nemet   for (Loop *TopLevelLoop : *LI)
1794e91cc6efSAdam Nemet     for (Loop *L : depth_first(TopLevelLoop)) {
1795e91cc6efSAdam Nemet       OS.indent(2) << L->getHeader()->getName() << ":\n";
1796e91cc6efSAdam Nemet       auto &LAI = LAA.getInfo(L, NoSymbolicStrides);
1797e91cc6efSAdam Nemet       LAI.print(OS, 4);
1798e91cc6efSAdam Nemet     }
1799e91cc6efSAdam Nemet }
1800e91cc6efSAdam Nemet 
18013bfd93d7SAdam Nemet bool LoopAccessAnalysis::runOnFunction(Function &F) {
18022f1fd165SChandler Carruth   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
18033bfd93d7SAdam Nemet   auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
18043bfd93d7SAdam Nemet   TLI = TLIP ? &TLIP->getTLI() : nullptr;
18053bfd93d7SAdam Nemet   AA = &getAnalysis<AliasAnalysis>();
18063bfd93d7SAdam Nemet   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1807e2b885c4SAdam Nemet   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
18083bfd93d7SAdam Nemet 
18093bfd93d7SAdam Nemet   return false;
18103bfd93d7SAdam Nemet }
18113bfd93d7SAdam Nemet 
18123bfd93d7SAdam Nemet void LoopAccessAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
18132f1fd165SChandler Carruth     AU.addRequired<ScalarEvolutionWrapperPass>();
18143bfd93d7SAdam Nemet     AU.addRequired<AliasAnalysis>();
18153bfd93d7SAdam Nemet     AU.addRequired<DominatorTreeWrapperPass>();
1816e91cc6efSAdam Nemet     AU.addRequired<LoopInfoWrapperPass>();
18173bfd93d7SAdam Nemet 
18183bfd93d7SAdam Nemet     AU.setPreservesAll();
18193bfd93d7SAdam Nemet }
18203bfd93d7SAdam Nemet 
18213bfd93d7SAdam Nemet char LoopAccessAnalysis::ID = 0;
18223bfd93d7SAdam Nemet static const char laa_name[] = "Loop Access Analysis";
18233bfd93d7SAdam Nemet #define LAA_NAME "loop-accesses"
18243bfd93d7SAdam Nemet 
18253bfd93d7SAdam Nemet INITIALIZE_PASS_BEGIN(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
18263bfd93d7SAdam Nemet INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
18272f1fd165SChandler Carruth INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
18283bfd93d7SAdam Nemet INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1829e91cc6efSAdam Nemet INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
18303bfd93d7SAdam Nemet INITIALIZE_PASS_END(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
18313bfd93d7SAdam Nemet 
18323bfd93d7SAdam Nemet namespace llvm {
18333bfd93d7SAdam Nemet   Pass *createLAAPass() {
18343bfd93d7SAdam Nemet     return new LoopAccessAnalysis();
18353bfd93d7SAdam Nemet   }
18363bfd93d7SAdam Nemet }
1837