10456327cSAdam Nemet //===- LoopAccessAnalysis.cpp - Loop Access Analysis Implementation --------==//
20456327cSAdam Nemet //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60456327cSAdam Nemet //
70456327cSAdam Nemet //===----------------------------------------------------------------------===//
80456327cSAdam Nemet //
90456327cSAdam Nemet // The implementation for the loop memory dependence that was originally
100456327cSAdam Nemet // developed for the loop vectorizer.
110456327cSAdam Nemet //
120456327cSAdam Nemet //===----------------------------------------------------------------------===//
130456327cSAdam Nemet 
143bab7e1aSChandler Carruth #include "llvm/Analysis/LoopAccessAnalysis.h"
15a3fe70d2SEugene Zelenko #include "llvm/ADT/APInt.h"
16a3fe70d2SEugene Zelenko #include "llvm/ADT/DenseMap.h"
17a3fe70d2SEugene Zelenko #include "llvm/ADT/DepthFirstIterator.h"
18a3fe70d2SEugene Zelenko #include "llvm/ADT/EquivalenceClasses.h"
19a3fe70d2SEugene Zelenko #include "llvm/ADT/PointerIntPair.h"
203bab7e1aSChandler Carruth #include "llvm/ADT/STLExtras.h"
21a3fe70d2SEugene Zelenko #include "llvm/ADT/SetVector.h"
22a3fe70d2SEugene Zelenko #include "llvm/ADT/SmallPtrSet.h"
23a3fe70d2SEugene Zelenko #include "llvm/ADT/SmallSet.h"
24a3fe70d2SEugene Zelenko #include "llvm/ADT/SmallVector.h"
253bab7e1aSChandler Carruth #include "llvm/ADT/iterator_range.h"
26a3fe70d2SEugene Zelenko #include "llvm/Analysis/AliasAnalysis.h"
27a3fe70d2SEugene Zelenko #include "llvm/Analysis/AliasSetTracker.h"
283bab7e1aSChandler Carruth #include "llvm/Analysis/LoopAnalysisManager.h"
290456327cSAdam Nemet #include "llvm/Analysis/LoopInfo.h"
30a3fe70d2SEugene Zelenko #include "llvm/Analysis/MemoryLocation.h"
310965da20SAdam Nemet #include "llvm/Analysis/OptimizationRemarkEmitter.h"
32a3fe70d2SEugene Zelenko #include "llvm/Analysis/ScalarEvolution.h"
337206d7a5SAdam Nemet #include "llvm/Analysis/ScalarEvolutionExpander.h"
34a3fe70d2SEugene Zelenko #include "llvm/Analysis/ScalarEvolutionExpressions.h"
35799003bfSBenjamin Kramer #include "llvm/Analysis/TargetLibraryInfo.h"
360456327cSAdam Nemet #include "llvm/Analysis/ValueTracking.h"
37f45594c9SAdam Nemet #include "llvm/Analysis/VectorUtils.h"
38a3fe70d2SEugene Zelenko #include "llvm/IR/BasicBlock.h"
39a3fe70d2SEugene Zelenko #include "llvm/IR/Constants.h"
40a3fe70d2SEugene Zelenko #include "llvm/IR/DataLayout.h"
41a3fe70d2SEugene Zelenko #include "llvm/IR/DebugLoc.h"
42a3fe70d2SEugene Zelenko #include "llvm/IR/DerivedTypes.h"
43a3fe70d2SEugene Zelenko #include "llvm/IR/DiagnosticInfo.h"
440456327cSAdam Nemet #include "llvm/IR/Dominators.h"
45a3fe70d2SEugene Zelenko #include "llvm/IR/Function.h"
463bab7e1aSChandler Carruth #include "llvm/IR/IRBuilder.h"
47a3fe70d2SEugene Zelenko #include "llvm/IR/InstrTypes.h"
48a3fe70d2SEugene Zelenko #include "llvm/IR/Instruction.h"
49a3fe70d2SEugene Zelenko #include "llvm/IR/Instructions.h"
50a3fe70d2SEugene Zelenko #include "llvm/IR/Operator.h"
518a021317SXinliang David Li #include "llvm/IR/PassManager.h"
52a3fe70d2SEugene Zelenko #include "llvm/IR/Type.h"
53a3fe70d2SEugene Zelenko #include "llvm/IR/Value.h"
54a3fe70d2SEugene Zelenko #include "llvm/IR/ValueHandle.h"
55a3fe70d2SEugene Zelenko #include "llvm/Pass.h"
56a3fe70d2SEugene Zelenko #include "llvm/Support/Casting.h"
57a3fe70d2SEugene Zelenko #include "llvm/Support/CommandLine.h"
580456327cSAdam Nemet #include "llvm/Support/Debug.h"
59a3fe70d2SEugene Zelenko #include "llvm/Support/ErrorHandling.h"
60799003bfSBenjamin Kramer #include "llvm/Support/raw_ostream.h"
61a3fe70d2SEugene Zelenko #include <algorithm>
62a3fe70d2SEugene Zelenko #include <cassert>
63a3fe70d2SEugene Zelenko #include <cstdint>
64a3fe70d2SEugene Zelenko #include <cstdlib>
65a3fe70d2SEugene Zelenko #include <iterator>
66a3fe70d2SEugene Zelenko #include <utility>
67a3fe70d2SEugene Zelenko #include <vector>
68a3fe70d2SEugene Zelenko 
690456327cSAdam Nemet using namespace llvm;
700456327cSAdam Nemet 
71339f42b3SAdam Nemet #define DEBUG_TYPE "loop-accesses"
720456327cSAdam Nemet 
73f219c647SAdam Nemet static cl::opt<unsigned, true>
74f219c647SAdam Nemet VectorizationFactor("force-vector-width", cl::Hidden,
75f219c647SAdam Nemet                     cl::desc("Sets the SIMD width. Zero is autoselect."),
76f219c647SAdam Nemet                     cl::location(VectorizerParams::VectorizationFactor));
771d862af7SAdam Nemet unsigned VectorizerParams::VectorizationFactor;
78f219c647SAdam Nemet 
79f219c647SAdam Nemet static cl::opt<unsigned, true>
80f219c647SAdam Nemet VectorizationInterleave("force-vector-interleave", cl::Hidden,
81f219c647SAdam Nemet                         cl::desc("Sets the vectorization interleave count. "
82f219c647SAdam Nemet                                  "Zero is autoselect."),
83f219c647SAdam Nemet                         cl::location(
84f219c647SAdam Nemet                             VectorizerParams::VectorizationInterleave));
851d862af7SAdam Nemet unsigned VectorizerParams::VectorizationInterleave;
86f219c647SAdam Nemet 
871d862af7SAdam Nemet static cl::opt<unsigned, true> RuntimeMemoryCheckThreshold(
881d862af7SAdam Nemet     "runtime-memory-check-threshold", cl::Hidden,
891d862af7SAdam Nemet     cl::desc("When performing memory disambiguation checks at runtime do not "
901d862af7SAdam Nemet              "generate more than this number of comparisons (default = 8)."),
911d862af7SAdam Nemet     cl::location(VectorizerParams::RuntimeMemoryCheckThreshold), cl::init(8));
921d862af7SAdam Nemet unsigned VectorizerParams::RuntimeMemoryCheckThreshold;
93f219c647SAdam Nemet 
945f8f34e4SAdrian Prantl /// The maximum iterations used to merge memory checks
951b6b50a9SSilviu Baranga static cl::opt<unsigned> MemoryCheckMergeThreshold(
961b6b50a9SSilviu Baranga     "memory-check-merge-threshold", cl::Hidden,
971b6b50a9SSilviu Baranga     cl::desc("Maximum number of comparisons done when trying to merge "
981b6b50a9SSilviu Baranga              "runtime memory checks. (default = 100)"),
991b6b50a9SSilviu Baranga     cl::init(100));
1001b6b50a9SSilviu Baranga 
101f219c647SAdam Nemet /// Maximum SIMD width.
102f219c647SAdam Nemet const unsigned VectorizerParams::MaxVectorWidth = 64;
103f219c647SAdam Nemet 
1045f8f34e4SAdrian Prantl /// We collect dependences up to this threshold.
105a2df750fSAdam Nemet static cl::opt<unsigned>
106a2df750fSAdam Nemet     MaxDependences("max-dependences", cl::Hidden,
107a2df750fSAdam Nemet                    cl::desc("Maximum number of dependences collected by "
1089c926579SAdam Nemet                             "loop-access analysis (default = 100)"),
1099c926579SAdam Nemet                    cl::init(100));
1109c926579SAdam Nemet 
111a9f09c62SAdam Nemet /// This enables versioning on the strides of symbolically striding memory
112a9f09c62SAdam Nemet /// accesses in code like the following.
113a9f09c62SAdam Nemet ///   for (i = 0; i < N; ++i)
114a9f09c62SAdam Nemet ///     A[i * Stride1] += B[i * Stride2] ...
115a9f09c62SAdam Nemet ///
116a9f09c62SAdam Nemet /// Will be roughly translated to
117a9f09c62SAdam Nemet ///    if (Stride1 == 1 && Stride2 == 1) {
118a9f09c62SAdam Nemet ///      for (i = 0; i < N; i+=4)
119a9f09c62SAdam Nemet ///       A[i:i+3] += ...
120a9f09c62SAdam Nemet ///    } else
121a9f09c62SAdam Nemet ///      ...
122a9f09c62SAdam Nemet static cl::opt<bool> EnableMemAccessVersioning(
123a9f09c62SAdam Nemet     "enable-mem-access-versioning", cl::init(true), cl::Hidden,
124a9f09c62SAdam Nemet     cl::desc("Enable symbolic stride memory access versioning"));
125a9f09c62SAdam Nemet 
1265f8f34e4SAdrian Prantl /// Enable store-to-load forwarding conflict detection. This option can
12737ec5f91SMatthew Simpson /// be disabled for correctness testing.
12837ec5f91SMatthew Simpson static cl::opt<bool> EnableForwardingConflictDetection(
12937ec5f91SMatthew Simpson     "store-to-load-forwarding-conflict-detection", cl::Hidden,
130a250dc9fSMatthew Simpson     cl::desc("Enable conflict detection in loop-access analysis"),
131a250dc9fSMatthew Simpson     cl::init(true));
132a250dc9fSMatthew Simpson 
133f219c647SAdam Nemet bool VectorizerParams::isInterleaveForced() {
134f219c647SAdam Nemet   return ::VectorizationInterleave.getNumOccurrences() > 0;
135f219c647SAdam Nemet }
136f219c647SAdam Nemet 
1370456327cSAdam Nemet Value *llvm::stripIntegerCast(Value *V) {
1388b401013SDavid Majnemer   if (auto *CI = dyn_cast<CastInst>(V))
1390456327cSAdam Nemet     if (CI->getOperand(0)->getType()->isIntegerTy())
1400456327cSAdam Nemet       return CI->getOperand(0);
1410456327cSAdam Nemet   return V;
1420456327cSAdam Nemet }
1430456327cSAdam Nemet 
1449cd9a7e3SSilviu Baranga const SCEV *llvm::replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE,
1458bc61df9SAdam Nemet                                             const ValueToValueMap &PtrToStride,
1460456327cSAdam Nemet                                             Value *Ptr, Value *OrigPtr) {
1479cd9a7e3SSilviu Baranga   const SCEV *OrigSCEV = PSE.getSCEV(Ptr);
1480456327cSAdam Nemet 
1490456327cSAdam Nemet   // If there is an entry in the map return the SCEV of the pointer with the
1500456327cSAdam Nemet   // symbolic stride replaced by one.
1518bc61df9SAdam Nemet   ValueToValueMap::const_iterator SI =
1528bc61df9SAdam Nemet       PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
1530456327cSAdam Nemet   if (SI != PtrToStride.end()) {
1540456327cSAdam Nemet     Value *StrideVal = SI->second;
1550456327cSAdam Nemet 
1560456327cSAdam Nemet     // Strip casts.
1570456327cSAdam Nemet     StrideVal = stripIntegerCast(StrideVal);
1580456327cSAdam Nemet 
1599cd9a7e3SSilviu Baranga     ScalarEvolution *SE = PSE.getSE();
160e3c0534bSSilviu Baranga     const auto *U = cast<SCEVUnknown>(SE->getSCEV(StrideVal));
161e3c0534bSSilviu Baranga     const auto *CT =
162e3c0534bSSilviu Baranga         static_cast<const SCEVConstant *>(SE->getOne(StrideVal->getType()));
163e3c0534bSSilviu Baranga 
1649cd9a7e3SSilviu Baranga     PSE.addPredicate(*SE->getEqualPredicate(U, CT));
1659cd9a7e3SSilviu Baranga     auto *Expr = PSE.getSCEV(Ptr);
166e3c0534bSSilviu Baranga 
167d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV
168d34e60caSNicola Zaghen                       << " by: " << *Expr << "\n");
1699cd9a7e3SSilviu Baranga     return Expr;
1700456327cSAdam Nemet   }
1710456327cSAdam Nemet 
1720456327cSAdam Nemet   // Otherwise, just return the SCEV of the original pointer.
173e3c0534bSSilviu Baranga   return OrigSCEV;
1740456327cSAdam Nemet }
1750456327cSAdam Nemet 
1763622fbfcSElena Demikhovsky /// Calculate Start and End points of memory access.
1773622fbfcSElena Demikhovsky /// Let's assume A is the first access and B is a memory access on N-th loop
1783622fbfcSElena Demikhovsky /// iteration. Then B is calculated as:
1793622fbfcSElena Demikhovsky ///   B = A + Step*N .
1803622fbfcSElena Demikhovsky /// Step value may be positive or negative.
1813622fbfcSElena Demikhovsky /// N is a calculated back-edge taken count:
1823622fbfcSElena Demikhovsky ///     N = (TripCount > 0) ? RoundDown(TripCount -1 , VF) : 0
1833622fbfcSElena Demikhovsky /// Start and End points are calculated in the following way:
1843622fbfcSElena Demikhovsky /// Start = UMIN(A, B) ; End = UMAX(A, B) + SizeOfElt,
1853622fbfcSElena Demikhovsky /// where SizeOfElt is the size of single memory access in bytes.
1863622fbfcSElena Demikhovsky ///
1873622fbfcSElena Demikhovsky /// There is no conflict when the intervals are disjoint:
1883622fbfcSElena Demikhovsky /// NoConflict = (P2.Start >= P1.End) || (P1.Start >= P2.End)
1897cdebac0SAdam Nemet void RuntimePointerChecking::insert(Loop *Lp, Value *Ptr, bool WritePtr,
1907cdebac0SAdam Nemet                                     unsigned DepSetId, unsigned ASId,
191e3c0534bSSilviu Baranga                                     const ValueToValueMap &Strides,
1929cd9a7e3SSilviu Baranga                                     PredicatedScalarEvolution &PSE) {
1930456327cSAdam Nemet   // Get the stride replaced scev.
1949cd9a7e3SSilviu Baranga   const SCEV *Sc = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
195279784ffSAdam Nemet   ScalarEvolution *SE = PSE.getSE();
196279784ffSAdam Nemet 
197279784ffSAdam Nemet   const SCEV *ScStart;
198279784ffSAdam Nemet   const SCEV *ScEnd;
199279784ffSAdam Nemet 
20059a65504SAdam Nemet   if (SE->isLoopInvariant(Sc, Lp))
201279784ffSAdam Nemet     ScStart = ScEnd = Sc;
202279784ffSAdam Nemet   else {
2030456327cSAdam Nemet     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
2040456327cSAdam Nemet     assert(AR && "Invalid addrec expression");
2056f444dfdSSilviu Baranga     const SCEV *Ex = PSE.getBackedgeTakenCount();
2060e5804a6SSilviu Baranga 
207279784ffSAdam Nemet     ScStart = AR->getStart();
208279784ffSAdam Nemet     ScEnd = AR->evaluateAtIteration(Ex, *SE);
2090e5804a6SSilviu Baranga     const SCEV *Step = AR->getStepRecurrence(*SE);
2100e5804a6SSilviu Baranga 
2110e5804a6SSilviu Baranga     // For expressions with negative step, the upper bound is ScStart and the
2120e5804a6SSilviu Baranga     // lower bound is ScEnd.
2138b401013SDavid Majnemer     if (const auto *CStep = dyn_cast<SCEVConstant>(Step)) {
2140e5804a6SSilviu Baranga       if (CStep->getValue()->isNegative())
2150e5804a6SSilviu Baranga         std::swap(ScStart, ScEnd);
2160e5804a6SSilviu Baranga     } else {
2173622fbfcSElena Demikhovsky       // Fallback case: the step is not constant, but we can still
2180e5804a6SSilviu Baranga       // get the upper and lower bounds of the interval by using min/max
2190e5804a6SSilviu Baranga       // expressions.
2200e5804a6SSilviu Baranga       ScStart = SE->getUMinExpr(ScStart, ScEnd);
2210e5804a6SSilviu Baranga       ScEnd = SE->getUMaxExpr(AR->getStart(), ScEnd);
2220e5804a6SSilviu Baranga     }
2233622fbfcSElena Demikhovsky     // Add the size of the pointed element to ScEnd.
2243622fbfcSElena Demikhovsky     unsigned EltSize =
2253622fbfcSElena Demikhovsky       Ptr->getType()->getPointerElementType()->getScalarSizeInBits() / 8;
2263622fbfcSElena Demikhovsky     const SCEV *EltSizeSCEV = SE->getConstant(ScEnd->getType(), EltSize);
2273622fbfcSElena Demikhovsky     ScEnd = SE->getAddExpr(ScEnd, EltSizeSCEV);
228279784ffSAdam Nemet   }
2290e5804a6SSilviu Baranga 
2300e5804a6SSilviu Baranga   Pointers.emplace_back(Ptr, ScStart, ScEnd, WritePtr, DepSetId, ASId, Sc);
2311b6b50a9SSilviu Baranga }
2321b6b50a9SSilviu Baranga 
233bbe1f1deSAdam Nemet SmallVector<RuntimePointerChecking::PointerCheck, 4>
23438530887SAdam Nemet RuntimePointerChecking::generateChecks() const {
235bbe1f1deSAdam Nemet   SmallVector<PointerCheck, 4> Checks;
236bbe1f1deSAdam Nemet 
2377c52e052SAdam Nemet   for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
2387c52e052SAdam Nemet     for (unsigned J = I + 1; J < CheckingGroups.size(); ++J) {
2397c52e052SAdam Nemet       const RuntimePointerChecking::CheckingPtrGroup &CGI = CheckingGroups[I];
2407c52e052SAdam Nemet       const RuntimePointerChecking::CheckingPtrGroup &CGJ = CheckingGroups[J];
241bbe1f1deSAdam Nemet 
24238530887SAdam Nemet       if (needsChecking(CGI, CGJ))
243bbe1f1deSAdam Nemet         Checks.push_back(std::make_pair(&CGI, &CGJ));
244bbe1f1deSAdam Nemet     }
245bbe1f1deSAdam Nemet   }
246bbe1f1deSAdam Nemet   return Checks;
247bbe1f1deSAdam Nemet }
248bbe1f1deSAdam Nemet 
24915840393SAdam Nemet void RuntimePointerChecking::generateChecks(
25015840393SAdam Nemet     MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
25115840393SAdam Nemet   assert(Checks.empty() && "Checks is not empty");
25215840393SAdam Nemet   groupChecks(DepCands, UseDependencies);
25315840393SAdam Nemet   Checks = generateChecks();
25415840393SAdam Nemet }
25515840393SAdam Nemet 
256651a5a24SAdam Nemet bool RuntimePointerChecking::needsChecking(const CheckingPtrGroup &M,
257651a5a24SAdam Nemet                                            const CheckingPtrGroup &N) const {
2581b6b50a9SSilviu Baranga   for (unsigned I = 0, EI = M.Members.size(); EI != I; ++I)
2591b6b50a9SSilviu Baranga     for (unsigned J = 0, EJ = N.Members.size(); EJ != J; ++J)
260651a5a24SAdam Nemet       if (needsChecking(M.Members[I], N.Members[J]))
2611b6b50a9SSilviu Baranga         return true;
2621b6b50a9SSilviu Baranga   return false;
2631b6b50a9SSilviu Baranga }
2641b6b50a9SSilviu Baranga 
2651b6b50a9SSilviu Baranga /// Compare \p I and \p J and return the minimum.
2661b6b50a9SSilviu Baranga /// Return nullptr in case we couldn't find an answer.
2671b6b50a9SSilviu Baranga static const SCEV *getMinFromExprs(const SCEV *I, const SCEV *J,
2681b6b50a9SSilviu Baranga                                    ScalarEvolution *SE) {
2691b6b50a9SSilviu Baranga   const SCEV *Diff = SE->getMinusSCEV(J, I);
2701b6b50a9SSilviu Baranga   const SCEVConstant *C = dyn_cast<const SCEVConstant>(Diff);
2711b6b50a9SSilviu Baranga 
2721b6b50a9SSilviu Baranga   if (!C)
2731b6b50a9SSilviu Baranga     return nullptr;
2741b6b50a9SSilviu Baranga   if (C->getValue()->isNegative())
2751b6b50a9SSilviu Baranga     return J;
2761b6b50a9SSilviu Baranga   return I;
2771b6b50a9SSilviu Baranga }
2781b6b50a9SSilviu Baranga 
2797cdebac0SAdam Nemet bool RuntimePointerChecking::CheckingPtrGroup::addPointer(unsigned Index) {
2809f7dedc3SAdam Nemet   const SCEV *Start = RtCheck.Pointers[Index].Start;
2819f7dedc3SAdam Nemet   const SCEV *End = RtCheck.Pointers[Index].End;
2829f7dedc3SAdam Nemet 
2831b6b50a9SSilviu Baranga   // Compare the starts and ends with the known minimum and maximum
2841b6b50a9SSilviu Baranga   // of this set. We need to know how we compare against the min/max
2851b6b50a9SSilviu Baranga   // of the set in order to be able to emit memchecks.
2869f7dedc3SAdam Nemet   const SCEV *Min0 = getMinFromExprs(Start, Low, RtCheck.SE);
2871b6b50a9SSilviu Baranga   if (!Min0)
2881b6b50a9SSilviu Baranga     return false;
2891b6b50a9SSilviu Baranga 
2909f7dedc3SAdam Nemet   const SCEV *Min1 = getMinFromExprs(End, High, RtCheck.SE);
2911b6b50a9SSilviu Baranga   if (!Min1)
2921b6b50a9SSilviu Baranga     return false;
2931b6b50a9SSilviu Baranga 
2941b6b50a9SSilviu Baranga   // Update the low bound  expression if we've found a new min value.
2959f7dedc3SAdam Nemet   if (Min0 == Start)
2969f7dedc3SAdam Nemet     Low = Start;
2971b6b50a9SSilviu Baranga 
2981b6b50a9SSilviu Baranga   // Update the high bound expression if we've found a new max value.
2999f7dedc3SAdam Nemet   if (Min1 != End)
3009f7dedc3SAdam Nemet     High = End;
3011b6b50a9SSilviu Baranga 
3021b6b50a9SSilviu Baranga   Members.push_back(Index);
3031b6b50a9SSilviu Baranga   return true;
3041b6b50a9SSilviu Baranga }
3051b6b50a9SSilviu Baranga 
3067cdebac0SAdam Nemet void RuntimePointerChecking::groupChecks(
3077cdebac0SAdam Nemet     MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
3081b6b50a9SSilviu Baranga   // We build the groups from dependency candidates equivalence classes
3091b6b50a9SSilviu Baranga   // because:
3101b6b50a9SSilviu Baranga   //    - We know that pointers in the same equivalence class share
3111b6b50a9SSilviu Baranga   //      the same underlying object and therefore there is a chance
3121b6b50a9SSilviu Baranga   //      that we can compare pointers
3131b6b50a9SSilviu Baranga   //    - We wouldn't be able to merge two pointers for which we need
3141b6b50a9SSilviu Baranga   //      to emit a memcheck. The classes in DepCands are already
3151b6b50a9SSilviu Baranga   //      conveniently built such that no two pointers in the same
3161b6b50a9SSilviu Baranga   //      class need checking against each other.
3171b6b50a9SSilviu Baranga 
3181b6b50a9SSilviu Baranga   // We use the following (greedy) algorithm to construct the groups
3191b6b50a9SSilviu Baranga   // For every pointer in the equivalence class:
3201b6b50a9SSilviu Baranga   //   For each existing group:
3211b6b50a9SSilviu Baranga   //   - if the difference between this pointer and the min/max bounds
3221b6b50a9SSilviu Baranga   //     of the group is a constant, then make the pointer part of the
3231b6b50a9SSilviu Baranga   //     group and update the min/max bounds of that group as required.
3241b6b50a9SSilviu Baranga 
3251b6b50a9SSilviu Baranga   CheckingGroups.clear();
3261b6b50a9SSilviu Baranga 
32748250600SSilviu Baranga   // If we need to check two pointers to the same underlying object
32848250600SSilviu Baranga   // with a non-constant difference, we shouldn't perform any pointer
32948250600SSilviu Baranga   // grouping with those pointers. This is because we can easily get
33048250600SSilviu Baranga   // into cases where the resulting check would return false, even when
33148250600SSilviu Baranga   // the accesses are safe.
33248250600SSilviu Baranga   //
33348250600SSilviu Baranga   // The following example shows this:
33448250600SSilviu Baranga   // for (i = 0; i < 1000; ++i)
33548250600SSilviu Baranga   //   a[5000 + i * m] = a[i] + a[i + 9000]
33648250600SSilviu Baranga   //
33748250600SSilviu Baranga   // Here grouping gives a check of (5000, 5000 + 1000 * m) against
33848250600SSilviu Baranga   // (0, 10000) which is always false. However, if m is 1, there is no
33948250600SSilviu Baranga   // dependence. Not grouping the checks for a[i] and a[i + 9000] allows
34048250600SSilviu Baranga   // us to perform an accurate check in this case.
34148250600SSilviu Baranga   //
34248250600SSilviu Baranga   // The above case requires that we have an UnknownDependence between
34348250600SSilviu Baranga   // accesses to the same underlying object. This cannot happen unless
344ef307b8cSFlorian Hahn   // FoundNonConstantDistanceDependence is set, and therefore UseDependencies
34548250600SSilviu Baranga   // is also false. In this case we will use the fallback path and create
34648250600SSilviu Baranga   // separate checking groups for all pointers.
34748250600SSilviu Baranga 
3481b6b50a9SSilviu Baranga   // If we don't have the dependency partitions, construct a new
34948250600SSilviu Baranga   // checking pointer group for each pointer. This is also required
35048250600SSilviu Baranga   // for correctness, because in this case we can have checking between
35148250600SSilviu Baranga   // pointers to the same underlying object.
3521b6b50a9SSilviu Baranga   if (!UseDependencies) {
3531b6b50a9SSilviu Baranga     for (unsigned I = 0; I < Pointers.size(); ++I)
3541b6b50a9SSilviu Baranga       CheckingGroups.push_back(CheckingPtrGroup(I, *this));
3551b6b50a9SSilviu Baranga     return;
3561b6b50a9SSilviu Baranga   }
3571b6b50a9SSilviu Baranga 
3581b6b50a9SSilviu Baranga   unsigned TotalComparisons = 0;
3591b6b50a9SSilviu Baranga 
3601b6b50a9SSilviu Baranga   DenseMap<Value *, unsigned> PositionMap;
3619f7dedc3SAdam Nemet   for (unsigned Index = 0; Index < Pointers.size(); ++Index)
3629f7dedc3SAdam Nemet     PositionMap[Pointers[Index].PointerValue] = Index;
3631b6b50a9SSilviu Baranga 
364ce3877fcSSilviu Baranga   // We need to keep track of what pointers we've already seen so we
365ce3877fcSSilviu Baranga   // don't process them twice.
366ce3877fcSSilviu Baranga   SmallSet<unsigned, 2> Seen;
367ce3877fcSSilviu Baranga 
368e4b9f507SSanjay Patel   // Go through all equivalence classes, get the "pointer check groups"
369ce3877fcSSilviu Baranga   // and add them to the overall solution. We use the order in which accesses
370ce3877fcSSilviu Baranga   // appear in 'Pointers' to enforce determinism.
371ce3877fcSSilviu Baranga   for (unsigned I = 0; I < Pointers.size(); ++I) {
372ce3877fcSSilviu Baranga     // We've seen this pointer before, and therefore already processed
373ce3877fcSSilviu Baranga     // its equivalence class.
374ce3877fcSSilviu Baranga     if (Seen.count(I))
3751b6b50a9SSilviu Baranga       continue;
3761b6b50a9SSilviu Baranga 
3779f7dedc3SAdam Nemet     MemoryDepChecker::MemAccessInfo Access(Pointers[I].PointerValue,
3789f7dedc3SAdam Nemet                                            Pointers[I].IsWritePtr);
3791b6b50a9SSilviu Baranga 
380ce3877fcSSilviu Baranga     SmallVector<CheckingPtrGroup, 2> Groups;
381ce3877fcSSilviu Baranga     auto LeaderI = DepCands.findValue(DepCands.getLeaderValue(Access));
382ce3877fcSSilviu Baranga 
383a647c30fSSilviu Baranga     // Because DepCands is constructed by visiting accesses in the order in
384a647c30fSSilviu Baranga     // which they appear in alias sets (which is deterministic) and the
385a647c30fSSilviu Baranga     // iteration order within an equivalence class member is only dependent on
386a647c30fSSilviu Baranga     // the order in which unions and insertions are performed on the
387a647c30fSSilviu Baranga     // equivalence class, the iteration order is deterministic.
388ce3877fcSSilviu Baranga     for (auto MI = DepCands.member_begin(LeaderI), ME = DepCands.member_end();
3891b6b50a9SSilviu Baranga          MI != ME; ++MI) {
3901b6b50a9SSilviu Baranga       unsigned Pointer = PositionMap[MI->getPointer()];
3911b6b50a9SSilviu Baranga       bool Merged = false;
392ce3877fcSSilviu Baranga       // Mark this pointer as seen.
393ce3877fcSSilviu Baranga       Seen.insert(Pointer);
3941b6b50a9SSilviu Baranga 
3951b6b50a9SSilviu Baranga       // Go through all the existing sets and see if we can find one
3961b6b50a9SSilviu Baranga       // which can include this pointer.
3971b6b50a9SSilviu Baranga       for (CheckingPtrGroup &Group : Groups) {
3981b6b50a9SSilviu Baranga         // Don't perform more than a certain amount of comparisons.
3991b6b50a9SSilviu Baranga         // This should limit the cost of grouping the pointers to something
4001b6b50a9SSilviu Baranga         // reasonable.  If we do end up hitting this threshold, the algorithm
4011b6b50a9SSilviu Baranga         // will create separate groups for all remaining pointers.
4021b6b50a9SSilviu Baranga         if (TotalComparisons > MemoryCheckMergeThreshold)
4031b6b50a9SSilviu Baranga           break;
4041b6b50a9SSilviu Baranga 
4051b6b50a9SSilviu Baranga         TotalComparisons++;
4061b6b50a9SSilviu Baranga 
4071b6b50a9SSilviu Baranga         if (Group.addPointer(Pointer)) {
4081b6b50a9SSilviu Baranga           Merged = true;
4091b6b50a9SSilviu Baranga           break;
4101b6b50a9SSilviu Baranga         }
4111b6b50a9SSilviu Baranga       }
4121b6b50a9SSilviu Baranga 
4131b6b50a9SSilviu Baranga       if (!Merged)
4141b6b50a9SSilviu Baranga         // We couldn't add this pointer to any existing set or the threshold
4151b6b50a9SSilviu Baranga         // for the number of comparisons has been reached. Create a new group
4161b6b50a9SSilviu Baranga         // to hold the current pointer.
4171b6b50a9SSilviu Baranga         Groups.push_back(CheckingPtrGroup(Pointer, *this));
4181b6b50a9SSilviu Baranga     }
4191b6b50a9SSilviu Baranga 
4201b6b50a9SSilviu Baranga     // We've computed the grouped checks for this partition.
4211b6b50a9SSilviu Baranga     // Save the results and continue with the next one.
42275709329SFangrui Song     llvm::copy(Groups, std::back_inserter(CheckingGroups));
4231b6b50a9SSilviu Baranga   }
4240456327cSAdam Nemet }
4250456327cSAdam Nemet 
426041e6debSAdam Nemet bool RuntimePointerChecking::arePointersInSamePartition(
427041e6debSAdam Nemet     const SmallVectorImpl<int> &PtrToPartition, unsigned PtrIdx1,
428041e6debSAdam Nemet     unsigned PtrIdx2) {
429041e6debSAdam Nemet   return (PtrToPartition[PtrIdx1] != -1 &&
430041e6debSAdam Nemet           PtrToPartition[PtrIdx1] == PtrToPartition[PtrIdx2]);
431041e6debSAdam Nemet }
432041e6debSAdam Nemet 
433651a5a24SAdam Nemet bool RuntimePointerChecking::needsChecking(unsigned I, unsigned J) const {
4349f7dedc3SAdam Nemet   const PointerInfo &PointerI = Pointers[I];
4359f7dedc3SAdam Nemet   const PointerInfo &PointerJ = Pointers[J];
4369f7dedc3SAdam Nemet 
437a8945b77SAdam Nemet   // No need to check if two readonly pointers intersect.
4389f7dedc3SAdam Nemet   if (!PointerI.IsWritePtr && !PointerJ.IsWritePtr)
439a8945b77SAdam Nemet     return false;
440a8945b77SAdam Nemet 
441a8945b77SAdam Nemet   // Only need to check pointers between two different dependency sets.
4429f7dedc3SAdam Nemet   if (PointerI.DependencySetId == PointerJ.DependencySetId)
443a8945b77SAdam Nemet     return false;
444a8945b77SAdam Nemet 
445a8945b77SAdam Nemet   // Only need to check pointers in the same alias set.
4469f7dedc3SAdam Nemet   if (PointerI.AliasSetId != PointerJ.AliasSetId)
447a8945b77SAdam Nemet     return false;
448a8945b77SAdam Nemet 
449a8945b77SAdam Nemet   return true;
450a8945b77SAdam Nemet }
451a8945b77SAdam Nemet 
45254f0b83eSAdam Nemet void RuntimePointerChecking::printChecks(
45354f0b83eSAdam Nemet     raw_ostream &OS, const SmallVectorImpl<PointerCheck> &Checks,
45454f0b83eSAdam Nemet     unsigned Depth) const {
45554f0b83eSAdam Nemet   unsigned N = 0;
45654f0b83eSAdam Nemet   for (const auto &Check : Checks) {
45754f0b83eSAdam Nemet     const auto &First = Check.first->Members, &Second = Check.second->Members;
45854f0b83eSAdam Nemet 
45954f0b83eSAdam Nemet     OS.indent(Depth) << "Check " << N++ << ":\n";
46054f0b83eSAdam Nemet 
46154f0b83eSAdam Nemet     OS.indent(Depth + 2) << "Comparing group (" << Check.first << "):\n";
46254f0b83eSAdam Nemet     for (unsigned K = 0; K < First.size(); ++K)
46354f0b83eSAdam Nemet       OS.indent(Depth + 2) << *Pointers[First[K]].PointerValue << "\n";
46454f0b83eSAdam Nemet 
46554f0b83eSAdam Nemet     OS.indent(Depth + 2) << "Against group (" << Check.second << "):\n";
46654f0b83eSAdam Nemet     for (unsigned K = 0; K < Second.size(); ++K)
46754f0b83eSAdam Nemet       OS.indent(Depth + 2) << *Pointers[Second[K]].PointerValue << "\n";
46854f0b83eSAdam Nemet   }
46954f0b83eSAdam Nemet }
47054f0b83eSAdam Nemet 
4713a91e947SAdam Nemet void RuntimePointerChecking::print(raw_ostream &OS, unsigned Depth) const {
472e91cc6efSAdam Nemet 
473e91cc6efSAdam Nemet   OS.indent(Depth) << "Run-time memory checks:\n";
47415840393SAdam Nemet   printChecks(OS, Checks, Depth);
4751b6b50a9SSilviu Baranga 
4761b6b50a9SSilviu Baranga   OS.indent(Depth) << "Grouped accesses:\n";
4771b6b50a9SSilviu Baranga   for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
47854f0b83eSAdam Nemet     const auto &CG = CheckingGroups[I];
47954f0b83eSAdam Nemet 
48054f0b83eSAdam Nemet     OS.indent(Depth + 2) << "Group " << &CG << ":\n";
48154f0b83eSAdam Nemet     OS.indent(Depth + 4) << "(Low: " << *CG.Low << " High: " << *CG.High
48254f0b83eSAdam Nemet                          << ")\n";
48354f0b83eSAdam Nemet     for (unsigned J = 0; J < CG.Members.size(); ++J) {
48454f0b83eSAdam Nemet       OS.indent(Depth + 6) << "Member: " << *Pointers[CG.Members[J]].Expr
4851b6b50a9SSilviu Baranga                            << "\n";
4861b6b50a9SSilviu Baranga     }
487e91cc6efSAdam Nemet   }
488e91cc6efSAdam Nemet }
489e91cc6efSAdam Nemet 
4900456327cSAdam Nemet namespace {
491a3fe70d2SEugene Zelenko 
4925f8f34e4SAdrian Prantl /// Analyses memory accesses in a loop.
4930456327cSAdam Nemet ///
4940456327cSAdam Nemet /// Checks whether run time pointer checks are needed and builds sets for data
4950456327cSAdam Nemet /// dependence checking.
4960456327cSAdam Nemet class AccessAnalysis {
4970456327cSAdam Nemet public:
4985f8f34e4SAdrian Prantl   /// Read or write access location.
4990456327cSAdam Nemet   typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
5005448e989SAmjad Aboud   typedef SmallVector<MemAccessInfo, 8> MemAccessInfoList;
5010456327cSAdam Nemet 
50277eeac3dSManoj Gupta   AccessAnalysis(const DataLayout &Dl, Loop *TheLoop, AliasAnalysis *AA,
50377eeac3dSManoj Gupta                  LoopInfo *LI, MemoryDepChecker::DepCandidates &DA,
5049cd9a7e3SSilviu Baranga                  PredicatedScalarEvolution &PSE)
50577eeac3dSManoj Gupta       : DL(Dl), TheLoop(TheLoop), AST(*AA), LI(LI), DepCands(DA),
50677eeac3dSManoj Gupta         IsRTCheckAnalysisNeeded(false), PSE(PSE) {}
5070456327cSAdam Nemet 
5085f8f34e4SAdrian Prantl   /// Register a load  and whether it is only read from.
509ac80dc75SChandler Carruth   void addLoad(MemoryLocation &Loc, bool IsReadOnly) {
5100456327cSAdam Nemet     Value *Ptr = const_cast<Value*>(Loc.Ptr);
5116ef8002cSGeorge Burgess IV     AST.add(Ptr, LocationSize::unknown(), Loc.AATags);
5120456327cSAdam Nemet     Accesses.insert(MemAccessInfo(Ptr, false));
5130456327cSAdam Nemet     if (IsReadOnly)
5140456327cSAdam Nemet       ReadOnlyPtr.insert(Ptr);
5150456327cSAdam Nemet   }
5160456327cSAdam Nemet 
5175f8f34e4SAdrian Prantl   /// Register a store.
518ac80dc75SChandler Carruth   void addStore(MemoryLocation &Loc) {
5190456327cSAdam Nemet     Value *Ptr = const_cast<Value*>(Loc.Ptr);
5206ef8002cSGeorge Burgess IV     AST.add(Ptr, LocationSize::unknown(), Loc.AATags);
5210456327cSAdam Nemet     Accesses.insert(MemAccessInfo(Ptr, true));
5220456327cSAdam Nemet   }
5230456327cSAdam Nemet 
5245f8f34e4SAdrian Prantl   /// Check if we can emit a run-time no-alias check for \p Access.
525ac920f77SSilviu Baranga   ///
526ac920f77SSilviu Baranga   /// Returns true if we can emit a run-time no alias check for \p Access.
527ac920f77SSilviu Baranga   /// If we can check this access, this also adds it to a dependence set and
528ac920f77SSilviu Baranga   /// adds a run-time to check for it to \p RtCheck. If \p Assume is true,
529ac920f77SSilviu Baranga   /// we will attempt to use additional run-time checks in order to get
530ac920f77SSilviu Baranga   /// the bounds of the pointer.
531ac920f77SSilviu Baranga   bool createCheckForAccess(RuntimePointerChecking &RtCheck,
532ac920f77SSilviu Baranga                             MemAccessInfo Access,
533ac920f77SSilviu Baranga                             const ValueToValueMap &Strides,
534ac920f77SSilviu Baranga                             DenseMap<Value *, unsigned> &DepSetId,
535ac920f77SSilviu Baranga                             Loop *TheLoop, unsigned &RunningDepId,
536ac920f77SSilviu Baranga                             unsigned ASId, bool ShouldCheckStride,
537ac920f77SSilviu Baranga                             bool Assume);
538ac920f77SSilviu Baranga 
5395f8f34e4SAdrian Prantl   /// Check whether we can check the pointers at runtime for
540ee61474aSAdam Nemet   /// non-intersection.
541ee61474aSAdam Nemet   ///
542ee61474aSAdam Nemet   /// Returns true if we need no check or if we do and we can generate them
543ee61474aSAdam Nemet   /// (i.e. the pointers have computable bounds).
5447cdebac0SAdam Nemet   bool canCheckPtrAtRT(RuntimePointerChecking &RtCheck, ScalarEvolution *SE,
5457cdebac0SAdam Nemet                        Loop *TheLoop, const ValueToValueMap &Strides,
5469f02c586SAndrey Turetskiy                        bool ShouldCheckWrap = false);
5470456327cSAdam Nemet 
5485f8f34e4SAdrian Prantl   /// Goes over all memory accesses, checks whether a RT check is needed
5490456327cSAdam Nemet   /// and builds sets of dependent accesses.
5500456327cSAdam Nemet   void buildDependenceSets() {
5510456327cSAdam Nemet     processMemAccesses();
5520456327cSAdam Nemet   }
5530456327cSAdam Nemet 
5545f8f34e4SAdrian Prantl   /// Initial processing of memory accesses determined that we need to
5555dc3b2cfSAdam Nemet   /// perform dependency checking.
5565dc3b2cfSAdam Nemet   ///
5575dc3b2cfSAdam Nemet   /// Note that this can later be cleared if we retry memcheck analysis without
558ef307b8cSFlorian Hahn   /// dependency checking (i.e. FoundNonConstantDistanceDependence).
5590456327cSAdam Nemet   bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
560df3dc5b9SAdam Nemet 
561df3dc5b9SAdam Nemet   /// We decided that no dependence analysis would be used.  Reset the state.
562df3dc5b9SAdam Nemet   void resetDepChecks(MemoryDepChecker &DepChecker) {
563df3dc5b9SAdam Nemet     CheckDeps.clear();
564a2df750fSAdam Nemet     DepChecker.clearDependences();
565df3dc5b9SAdam Nemet   }
5660456327cSAdam Nemet 
5675448e989SAmjad Aboud   MemAccessInfoList &getDependenciesToCheck() { return CheckDeps; }
5680456327cSAdam Nemet 
5690456327cSAdam Nemet private:
5700456327cSAdam Nemet   typedef SetVector<MemAccessInfo> PtrAccessSet;
5710456327cSAdam Nemet 
5725f8f34e4SAdrian Prantl   /// Go over all memory access and check whether runtime pointer checks
573b41d2d3fSAdam Nemet   /// are needed and build sets of dependency check candidates.
5740456327cSAdam Nemet   void processMemAccesses();
5750456327cSAdam Nemet 
5760456327cSAdam Nemet   /// Set of all accesses.
5770456327cSAdam Nemet   PtrAccessSet Accesses;
5780456327cSAdam Nemet 
579a28d91d8SMehdi Amini   const DataLayout &DL;
580a28d91d8SMehdi Amini 
58177eeac3dSManoj Gupta   /// The loop being checked.
58277eeac3dSManoj Gupta   const Loop *TheLoop;
58377eeac3dSManoj Gupta 
5845448e989SAmjad Aboud   /// List of accesses that need a further dependence check.
5855448e989SAmjad Aboud   MemAccessInfoList CheckDeps;
5860456327cSAdam Nemet 
5870456327cSAdam Nemet   /// Set of pointers that are read only.
5880456327cSAdam Nemet   SmallPtrSet<Value*, 16> ReadOnlyPtr;
5890456327cSAdam Nemet 
5900456327cSAdam Nemet   /// An alias set tracker to partition the access set by underlying object and
5910456327cSAdam Nemet   //intrinsic property (such as TBAA metadata).
5920456327cSAdam Nemet   AliasSetTracker AST;
5930456327cSAdam Nemet 
594e2b885c4SAdam Nemet   LoopInfo *LI;
595e2b885c4SAdam Nemet 
5960456327cSAdam Nemet   /// Sets of potentially dependent accesses - members of one set share an
5970456327cSAdam Nemet   /// underlying pointer. The set "CheckDeps" identfies which sets really need a
5980456327cSAdam Nemet   /// dependence check.
599dee666bcSAdam Nemet   MemoryDepChecker::DepCandidates &DepCands;
6000456327cSAdam Nemet 
6015f8f34e4SAdrian Prantl   /// Initial processing of memory accesses determined that we may need
6025dc3b2cfSAdam Nemet   /// to add memchecks.  Perform the analysis to determine the necessary checks.
6035dc3b2cfSAdam Nemet   ///
6045dc3b2cfSAdam Nemet   /// Note that, this is different from isDependencyCheckNeeded.  When we retry
6055dc3b2cfSAdam Nemet   /// memcheck analysis without dependency checking
606ef307b8cSFlorian Hahn   /// (i.e. FoundNonConstantDistanceDependence), isDependencyCheckNeeded is
607ef307b8cSFlorian Hahn   /// cleared while this remains set if we have potentially dependent accesses.
6085dc3b2cfSAdam Nemet   bool IsRTCheckAnalysisNeeded;
609e3c0534bSSilviu Baranga 
610e3c0534bSSilviu Baranga   /// The SCEV predicate containing all the SCEV-related assumptions.
6119cd9a7e3SSilviu Baranga   PredicatedScalarEvolution &PSE;
6120456327cSAdam Nemet };
6130456327cSAdam Nemet 
6140456327cSAdam Nemet } // end anonymous namespace
6150456327cSAdam Nemet 
6165f8f34e4SAdrian Prantl /// Check whether a pointer can participate in a runtime bounds check.
617ac920f77SSilviu Baranga /// If \p Assume, try harder to prove that we can compute the bounds of \p Ptr
618ac920f77SSilviu Baranga /// by adding run-time checks (overflow checks) if necessary.
6199cd9a7e3SSilviu Baranga static bool hasComputableBounds(PredicatedScalarEvolution &PSE,
620e3c0534bSSilviu Baranga                                 const ValueToValueMap &Strides, Value *Ptr,
621ac920f77SSilviu Baranga                                 Loop *L, bool Assume) {
6229cd9a7e3SSilviu Baranga   const SCEV *PtrScev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
623279784ffSAdam Nemet 
624279784ffSAdam Nemet   // The bounds for loop-invariant pointer is trivial.
625279784ffSAdam Nemet   if (PSE.getSE()->isLoopInvariant(PtrScev, L))
626279784ffSAdam Nemet     return true;
627279784ffSAdam Nemet 
6280456327cSAdam Nemet   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
629ac920f77SSilviu Baranga 
630ac920f77SSilviu Baranga   if (!AR && Assume)
631ac920f77SSilviu Baranga     AR = PSE.getAsAddRec(Ptr);
632ac920f77SSilviu Baranga 
6330456327cSAdam Nemet   if (!AR)
6340456327cSAdam Nemet     return false;
6350456327cSAdam Nemet 
6360456327cSAdam Nemet   return AR->isAffine();
6370456327cSAdam Nemet }
6380456327cSAdam Nemet 
6395f8f34e4SAdrian Prantl /// Check whether a pointer address cannot wrap.
6409f02c586SAndrey Turetskiy static bool isNoWrap(PredicatedScalarEvolution &PSE,
6419f02c586SAndrey Turetskiy                      const ValueToValueMap &Strides, Value *Ptr, Loop *L) {
6429f02c586SAndrey Turetskiy   const SCEV *PtrScev = PSE.getSCEV(Ptr);
6439f02c586SAndrey Turetskiy   if (PSE.getSE()->isLoopInvariant(PtrScev, L))
6449f02c586SAndrey Turetskiy     return true;
6459f02c586SAndrey Turetskiy 
6467afb46d3SDavid Majnemer   int64_t Stride = getPtrStride(PSE, Ptr, L, Strides);
647ac920f77SSilviu Baranga   if (Stride == 1 || PSE.hasNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW))
648ac920f77SSilviu Baranga     return true;
649ac920f77SSilviu Baranga 
650ac920f77SSilviu Baranga   return false;
651ac920f77SSilviu Baranga }
652ac920f77SSilviu Baranga 
653ac920f77SSilviu Baranga bool AccessAnalysis::createCheckForAccess(RuntimePointerChecking &RtCheck,
654ac920f77SSilviu Baranga                                           MemAccessInfo Access,
655ac920f77SSilviu Baranga                                           const ValueToValueMap &StridesMap,
656ac920f77SSilviu Baranga                                           DenseMap<Value *, unsigned> &DepSetId,
657ac920f77SSilviu Baranga                                           Loop *TheLoop, unsigned &RunningDepId,
658ac920f77SSilviu Baranga                                           unsigned ASId, bool ShouldCheckWrap,
659ac920f77SSilviu Baranga                                           bool Assume) {
660ac920f77SSilviu Baranga   Value *Ptr = Access.getPointer();
661ac920f77SSilviu Baranga 
662ac920f77SSilviu Baranga   if (!hasComputableBounds(PSE, StridesMap, Ptr, TheLoop, Assume))
663ac920f77SSilviu Baranga     return false;
664ac920f77SSilviu Baranga 
665ac920f77SSilviu Baranga   // When we run after a failing dependency check we have to make sure
666ac920f77SSilviu Baranga   // we don't have wrapping pointers.
667ac920f77SSilviu Baranga   if (ShouldCheckWrap && !isNoWrap(PSE, StridesMap, Ptr, TheLoop)) {
668ac920f77SSilviu Baranga     auto *Expr = PSE.getSCEV(Ptr);
669ac920f77SSilviu Baranga     if (!Assume || !isa<SCEVAddRecExpr>(Expr))
670ac920f77SSilviu Baranga       return false;
671ac920f77SSilviu Baranga     PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
672ac920f77SSilviu Baranga   }
673ac920f77SSilviu Baranga 
674ac920f77SSilviu Baranga   // The id of the dependence set.
675ac920f77SSilviu Baranga   unsigned DepId;
676ac920f77SSilviu Baranga 
677ac920f77SSilviu Baranga   if (isDependencyCheckNeeded()) {
678ac920f77SSilviu Baranga     Value *Leader = DepCands.getLeaderValue(Access).getPointer();
679ac920f77SSilviu Baranga     unsigned &LeaderId = DepSetId[Leader];
680ac920f77SSilviu Baranga     if (!LeaderId)
681ac920f77SSilviu Baranga       LeaderId = RunningDepId++;
682ac920f77SSilviu Baranga     DepId = LeaderId;
683ac920f77SSilviu Baranga   } else
684ac920f77SSilviu Baranga     // Each access has its own dependence set.
685ac920f77SSilviu Baranga     DepId = RunningDepId++;
686ac920f77SSilviu Baranga 
687ac920f77SSilviu Baranga   bool IsWrite = Access.getInt();
688ac920f77SSilviu Baranga   RtCheck.insert(TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap, PSE);
689d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
690ac920f77SSilviu Baranga 
691ac920f77SSilviu Baranga   return true;
6929f02c586SAndrey Turetskiy  }
6939f02c586SAndrey Turetskiy 
6947cdebac0SAdam Nemet bool AccessAnalysis::canCheckPtrAtRT(RuntimePointerChecking &RtCheck,
6957cdebac0SAdam Nemet                                      ScalarEvolution *SE, Loop *TheLoop,
6967cdebac0SAdam Nemet                                      const ValueToValueMap &StridesMap,
6979f02c586SAndrey Turetskiy                                      bool ShouldCheckWrap) {
6980456327cSAdam Nemet   // Find pointers with computable bounds. We are going to use this information
6990456327cSAdam Nemet   // to place a runtime bound check.
7000456327cSAdam Nemet   bool CanDoRT = true;
7010456327cSAdam Nemet 
702ee61474aSAdam Nemet   bool NeedRTCheck = false;
7035dc3b2cfSAdam Nemet   if (!IsRTCheckAnalysisNeeded) return true;
70498a13719SSilviu Baranga 
7050456327cSAdam Nemet   bool IsDepCheckNeeded = isDependencyCheckNeeded();
7060456327cSAdam Nemet 
7070456327cSAdam Nemet   // We assign a consecutive id to access from different alias sets.
7080456327cSAdam Nemet   // Accesses between different groups doesn't need to be checked.
7090456327cSAdam Nemet   unsigned ASId = 1;
7100456327cSAdam Nemet   for (auto &AS : AST) {
711424edc6cSAdam Nemet     int NumReadPtrChecks = 0;
712424edc6cSAdam Nemet     int NumWritePtrChecks = 0;
713ac920f77SSilviu Baranga     bool CanDoAliasSetRT = true;
714424edc6cSAdam Nemet 
7150456327cSAdam Nemet     // We assign consecutive id to access from different dependence sets.
7160456327cSAdam Nemet     // Accesses within the same set don't need a runtime check.
7170456327cSAdam Nemet     unsigned RunningDepId = 1;
7180456327cSAdam Nemet     DenseMap<Value *, unsigned> DepSetId;
7190456327cSAdam Nemet 
720ac920f77SSilviu Baranga     SmallVector<MemAccessInfo, 4> Retries;
721ac920f77SSilviu Baranga 
7220456327cSAdam Nemet     for (auto A : AS) {
7230456327cSAdam Nemet       Value *Ptr = A.getValue();
7240456327cSAdam Nemet       bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
7250456327cSAdam Nemet       MemAccessInfo Access(Ptr, IsWrite);
7260456327cSAdam Nemet 
727424edc6cSAdam Nemet       if (IsWrite)
728424edc6cSAdam Nemet         ++NumWritePtrChecks;
729424edc6cSAdam Nemet       else
730424edc6cSAdam Nemet         ++NumReadPtrChecks;
731424edc6cSAdam Nemet 
732ac920f77SSilviu Baranga       if (!createCheckForAccess(RtCheck, Access, StridesMap, DepSetId, TheLoop,
733ac920f77SSilviu Baranga                                 RunningDepId, ASId, ShouldCheckWrap, false)) {
734d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "LAA: Can't find bounds for ptr:" << *Ptr << '\n');
735ac920f77SSilviu Baranga         Retries.push_back(Access);
736ac920f77SSilviu Baranga         CanDoAliasSetRT = false;
7370456327cSAdam Nemet       }
7380456327cSAdam Nemet     }
7390456327cSAdam Nemet 
740424edc6cSAdam Nemet     // If we have at least two writes or one write and a read then we need to
741424edc6cSAdam Nemet     // check them.  But there is no need to checks if there is only one
742424edc6cSAdam Nemet     // dependence set for this alias set.
743424edc6cSAdam Nemet     //
744424edc6cSAdam Nemet     // Note that this function computes CanDoRT and NeedRTCheck independently.
745424edc6cSAdam Nemet     // For example CanDoRT=false, NeedRTCheck=false means that we have a pointer
746424edc6cSAdam Nemet     // for which we couldn't find the bounds but we don't actually need to emit
747424edc6cSAdam Nemet     // any checks so it does not matter.
748ac920f77SSilviu Baranga     bool NeedsAliasSetRTCheck = false;
749ac920f77SSilviu Baranga     if (!(IsDepCheckNeeded && CanDoAliasSetRT && RunningDepId == 2))
750ac920f77SSilviu Baranga       NeedsAliasSetRTCheck = (NumWritePtrChecks >= 2 ||
751ac920f77SSilviu Baranga                              (NumReadPtrChecks >= 1 && NumWritePtrChecks >= 1));
752424edc6cSAdam Nemet 
753ac920f77SSilviu Baranga     // We need to perform run-time alias checks, but some pointers had bounds
754ac920f77SSilviu Baranga     // that couldn't be checked.
755ac920f77SSilviu Baranga     if (NeedsAliasSetRTCheck && !CanDoAliasSetRT) {
756ac920f77SSilviu Baranga       // Reset the CanDoSetRt flag and retry all accesses that have failed.
757ac920f77SSilviu Baranga       // We know that we need these checks, so we can now be more aggressive
758ac920f77SSilviu Baranga       // and add further checks if required (overflow checks).
759ac920f77SSilviu Baranga       CanDoAliasSetRT = true;
760ac920f77SSilviu Baranga       for (auto Access : Retries)
761ac920f77SSilviu Baranga         if (!createCheckForAccess(RtCheck, Access, StridesMap, DepSetId,
762ac920f77SSilviu Baranga                                   TheLoop, RunningDepId, ASId,
763ac920f77SSilviu Baranga                                   ShouldCheckWrap, /*Assume=*/true)) {
764ac920f77SSilviu Baranga           CanDoAliasSetRT = false;
765ac920f77SSilviu Baranga           break;
766ac920f77SSilviu Baranga         }
767ac920f77SSilviu Baranga     }
768ac920f77SSilviu Baranga 
769ac920f77SSilviu Baranga     CanDoRT &= CanDoAliasSetRT;
770ac920f77SSilviu Baranga     NeedRTCheck |= NeedsAliasSetRTCheck;
7710456327cSAdam Nemet     ++ASId;
7720456327cSAdam Nemet   }
7730456327cSAdam Nemet 
7740456327cSAdam Nemet   // If the pointers that we would use for the bounds comparison have different
7750456327cSAdam Nemet   // address spaces, assume the values aren't directly comparable, so we can't
7760456327cSAdam Nemet   // use them for the runtime check. We also have to assume they could
7770456327cSAdam Nemet   // overlap. In the future there should be metadata for whether address spaces
7780456327cSAdam Nemet   // are disjoint.
7790456327cSAdam Nemet   unsigned NumPointers = RtCheck.Pointers.size();
7800456327cSAdam Nemet   for (unsigned i = 0; i < NumPointers; ++i) {
7810456327cSAdam Nemet     for (unsigned j = i + 1; j < NumPointers; ++j) {
7820456327cSAdam Nemet       // Only need to check pointers between two different dependency sets.
7839f7dedc3SAdam Nemet       if (RtCheck.Pointers[i].DependencySetId ==
7849f7dedc3SAdam Nemet           RtCheck.Pointers[j].DependencySetId)
7850456327cSAdam Nemet        continue;
7860456327cSAdam Nemet       // Only need to check pointers in the same alias set.
7879f7dedc3SAdam Nemet       if (RtCheck.Pointers[i].AliasSetId != RtCheck.Pointers[j].AliasSetId)
7880456327cSAdam Nemet         continue;
7890456327cSAdam Nemet 
7909f7dedc3SAdam Nemet       Value *PtrI = RtCheck.Pointers[i].PointerValue;
7919f7dedc3SAdam Nemet       Value *PtrJ = RtCheck.Pointers[j].PointerValue;
7920456327cSAdam Nemet 
7930456327cSAdam Nemet       unsigned ASi = PtrI->getType()->getPointerAddressSpace();
7940456327cSAdam Nemet       unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
7950456327cSAdam Nemet       if (ASi != ASj) {
796d34e60caSNicola Zaghen         LLVM_DEBUG(
797d34e60caSNicola Zaghen             dbgs() << "LAA: Runtime check would require comparison between"
7980456327cSAdam Nemet                       " different address spaces\n");
7990456327cSAdam Nemet         return false;
8000456327cSAdam Nemet       }
8010456327cSAdam Nemet     }
8020456327cSAdam Nemet   }
8030456327cSAdam Nemet 
8041b6b50a9SSilviu Baranga   if (NeedRTCheck && CanDoRT)
80515840393SAdam Nemet     RtCheck.generateChecks(DepCands, IsDepCheckNeeded);
8061b6b50a9SSilviu Baranga 
807d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "LAA: We need to do " << RtCheck.getNumberOfChecks()
808ee61474aSAdam Nemet                     << " pointer comparisons.\n");
809ee61474aSAdam Nemet 
810ee61474aSAdam Nemet   RtCheck.Need = NeedRTCheck;
811ee61474aSAdam Nemet 
812ee61474aSAdam Nemet   bool CanDoRTIfNeeded = !NeedRTCheck || CanDoRT;
813ee61474aSAdam Nemet   if (!CanDoRTIfNeeded)
814ee61474aSAdam Nemet     RtCheck.reset();
815ee61474aSAdam Nemet   return CanDoRTIfNeeded;
8160456327cSAdam Nemet }
8170456327cSAdam Nemet 
8180456327cSAdam Nemet void AccessAnalysis::processMemAccesses() {
8190456327cSAdam Nemet   // We process the set twice: first we process read-write pointers, last we
8200456327cSAdam Nemet   // process read-only pointers. This allows us to skip dependence tests for
8210456327cSAdam Nemet   // read-only pointers.
8220456327cSAdam Nemet 
823d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
824d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  AST: "; AST.dump());
825d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "LAA:   Accesses(" << Accesses.size() << "):\n");
826d34e60caSNicola Zaghen   LLVM_DEBUG({
8270456327cSAdam Nemet     for (auto A : Accesses)
8280456327cSAdam Nemet       dbgs() << "\t" << *A.getPointer() << " (" <<
8290456327cSAdam Nemet                 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
8300456327cSAdam Nemet                                          "read-only" : "read")) << ")\n";
8310456327cSAdam Nemet   });
8320456327cSAdam Nemet 
8330456327cSAdam Nemet   // The AliasSetTracker has nicely partitioned our pointers by metadata
8340456327cSAdam Nemet   // compatibility and potential for underlying-object overlap. As a result, we
8350456327cSAdam Nemet   // only need to check for potential pointer dependencies within each alias
8360456327cSAdam Nemet   // set.
8370456327cSAdam Nemet   for (auto &AS : AST) {
8380456327cSAdam Nemet     // Note that both the alias-set tracker and the alias sets themselves used
8390456327cSAdam Nemet     // linked lists internally and so the iteration order here is deterministic
8400456327cSAdam Nemet     // (matching the original instruction order within each set).
8410456327cSAdam Nemet 
8420456327cSAdam Nemet     bool SetHasWrite = false;
8430456327cSAdam Nemet 
8440456327cSAdam Nemet     // Map of pointers to last access encountered.
8450456327cSAdam Nemet     typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
8460456327cSAdam Nemet     UnderlyingObjToAccessMap ObjToLastAccess;
8470456327cSAdam Nemet 
8480456327cSAdam Nemet     // Set of access to check after all writes have been processed.
8490456327cSAdam Nemet     PtrAccessSet DeferredAccesses;
8500456327cSAdam Nemet 
8510456327cSAdam Nemet     // Iterate over each alias set twice, once to process read/write pointers,
8520456327cSAdam Nemet     // and then to process read-only pointers.
8530456327cSAdam Nemet     for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
8540456327cSAdam Nemet       bool UseDeferred = SetIteration > 0;
8550456327cSAdam Nemet       PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
8560456327cSAdam Nemet 
8570456327cSAdam Nemet       for (auto AV : AS) {
8580456327cSAdam Nemet         Value *Ptr = AV.getValue();
8590456327cSAdam Nemet 
8600456327cSAdam Nemet         // For a single memory access in AliasSetTracker, Accesses may contain
8610456327cSAdam Nemet         // both read and write, and they both need to be handled for CheckDeps.
8620456327cSAdam Nemet         for (auto AC : S) {
8630456327cSAdam Nemet           if (AC.getPointer() != Ptr)
8640456327cSAdam Nemet             continue;
8650456327cSAdam Nemet 
8660456327cSAdam Nemet           bool IsWrite = AC.getInt();
8670456327cSAdam Nemet 
8680456327cSAdam Nemet           // If we're using the deferred access set, then it contains only
8690456327cSAdam Nemet           // reads.
8700456327cSAdam Nemet           bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
8710456327cSAdam Nemet           if (UseDeferred && !IsReadOnlyPtr)
8720456327cSAdam Nemet             continue;
8730456327cSAdam Nemet           // Otherwise, the pointer must be in the PtrAccessSet, either as a
8740456327cSAdam Nemet           // read or a write.
8750456327cSAdam Nemet           assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
8760456327cSAdam Nemet                   S.count(MemAccessInfo(Ptr, false))) &&
8770456327cSAdam Nemet                  "Alias-set pointer not in the access set?");
8780456327cSAdam Nemet 
8790456327cSAdam Nemet           MemAccessInfo Access(Ptr, IsWrite);
8800456327cSAdam Nemet           DepCands.insert(Access);
8810456327cSAdam Nemet 
8820456327cSAdam Nemet           // Memorize read-only pointers for later processing and skip them in
8830456327cSAdam Nemet           // the first round (they need to be checked after we have seen all
8840456327cSAdam Nemet           // write pointers). Note: we also mark pointer that are not
8850456327cSAdam Nemet           // consecutive as "read-only" pointers (so that we check
8860456327cSAdam Nemet           // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
8870456327cSAdam Nemet           if (!UseDeferred && IsReadOnlyPtr) {
8880456327cSAdam Nemet             DeferredAccesses.insert(Access);
8890456327cSAdam Nemet             continue;
8900456327cSAdam Nemet           }
8910456327cSAdam Nemet 
8920456327cSAdam Nemet           // If this is a write - check other reads and writes for conflicts. If
8930456327cSAdam Nemet           // this is a read only check other writes for conflicts (but only if
8940456327cSAdam Nemet           // there is no other write to the ptr - this is an optimization to
8950456327cSAdam Nemet           // catch "a[i] = a[i] + " without having to do a dependence check).
8960456327cSAdam Nemet           if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
8975448e989SAmjad Aboud             CheckDeps.push_back(Access);
8985dc3b2cfSAdam Nemet             IsRTCheckAnalysisNeeded = true;
8990456327cSAdam Nemet           }
9000456327cSAdam Nemet 
9010456327cSAdam Nemet           if (IsWrite)
9020456327cSAdam Nemet             SetHasWrite = true;
9030456327cSAdam Nemet 
9040456327cSAdam Nemet           // Create sets of pointers connected by a shared alias set and
9050456327cSAdam Nemet           // underlying object.
9060456327cSAdam Nemet           typedef SmallVector<Value *, 16> ValueVector;
9070456327cSAdam Nemet           ValueVector TempObjects;
908e2b885c4SAdam Nemet 
909e2b885c4SAdam Nemet           GetUnderlyingObjects(Ptr, TempObjects, DL, LI);
910d34e60caSNicola Zaghen           LLVM_DEBUG(dbgs()
911d34e60caSNicola Zaghen                      << "Underlying objects for pointer " << *Ptr << "\n");
9120456327cSAdam Nemet           for (Value *UnderlyingObj : TempObjects) {
913afd13519SMehdi Amini             // nullptr never alias, don't join sets for pointer that have "null"
914afd13519SMehdi Amini             // in their UnderlyingObjects list.
91577eeac3dSManoj Gupta             if (isa<ConstantPointerNull>(UnderlyingObj) &&
91677eeac3dSManoj Gupta                 !NullPointerIsDefined(
91777eeac3dSManoj Gupta                     TheLoop->getHeader()->getParent(),
91877eeac3dSManoj Gupta                     UnderlyingObj->getType()->getPointerAddressSpace()))
919afd13519SMehdi Amini               continue;
920afd13519SMehdi Amini 
9210456327cSAdam Nemet             UnderlyingObjToAccessMap::iterator Prev =
9220456327cSAdam Nemet                 ObjToLastAccess.find(UnderlyingObj);
9230456327cSAdam Nemet             if (Prev != ObjToLastAccess.end())
9240456327cSAdam Nemet               DepCands.unionSets(Access, Prev->second);
9250456327cSAdam Nemet 
9260456327cSAdam Nemet             ObjToLastAccess[UnderlyingObj] = Access;
927d34e60caSNicola Zaghen             LLVM_DEBUG(dbgs() << "  " << *UnderlyingObj << "\n");
9280456327cSAdam Nemet           }
9290456327cSAdam Nemet         }
9300456327cSAdam Nemet       }
9310456327cSAdam Nemet     }
9320456327cSAdam Nemet   }
9330456327cSAdam Nemet }
9340456327cSAdam Nemet 
9350456327cSAdam Nemet static bool isInBoundsGep(Value *Ptr) {
9360456327cSAdam Nemet   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9370456327cSAdam Nemet     return GEP->isInBounds();
9380456327cSAdam Nemet   return false;
9390456327cSAdam Nemet }
9400456327cSAdam Nemet 
9415f8f34e4SAdrian Prantl /// Return true if an AddRec pointer \p Ptr is unsigned non-wrapping,
942c4866d29SAdam Nemet /// i.e. monotonically increasing/decreasing.
943c4866d29SAdam Nemet static bool isNoWrapAddRec(Value *Ptr, const SCEVAddRecExpr *AR,
944ea63a7f5SSilviu Baranga                            PredicatedScalarEvolution &PSE, const Loop *L) {
945c4866d29SAdam Nemet   // FIXME: This should probably only return true for NUW.
946c4866d29SAdam Nemet   if (AR->getNoWrapFlags(SCEV::NoWrapMask))
947c4866d29SAdam Nemet     return true;
948c4866d29SAdam Nemet 
949c4866d29SAdam Nemet   // Scalar evolution does not propagate the non-wrapping flags to values that
950c4866d29SAdam Nemet   // are derived from a non-wrapping induction variable because non-wrapping
951c4866d29SAdam Nemet   // could be flow-sensitive.
952c4866d29SAdam Nemet   //
953c4866d29SAdam Nemet   // Look through the potentially overflowing instruction to try to prove
954c4866d29SAdam Nemet   // non-wrapping for the *specific* value of Ptr.
955c4866d29SAdam Nemet 
956c4866d29SAdam Nemet   // The arithmetic implied by an inbounds GEP can't overflow.
957c4866d29SAdam Nemet   auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
958c4866d29SAdam Nemet   if (!GEP || !GEP->isInBounds())
959c4866d29SAdam Nemet     return false;
960c4866d29SAdam Nemet 
961c4866d29SAdam Nemet   // Make sure there is only one non-const index and analyze that.
962c4866d29SAdam Nemet   Value *NonConstIndex = nullptr;
9638b401013SDavid Majnemer   for (Value *Index : make_range(GEP->idx_begin(), GEP->idx_end()))
9648b401013SDavid Majnemer     if (!isa<ConstantInt>(Index)) {
965c4866d29SAdam Nemet       if (NonConstIndex)
966c4866d29SAdam Nemet         return false;
9678b401013SDavid Majnemer       NonConstIndex = Index;
968c4866d29SAdam Nemet     }
969c4866d29SAdam Nemet   if (!NonConstIndex)
970c4866d29SAdam Nemet     // The recurrence is on the pointer, ignore for now.
971c4866d29SAdam Nemet     return false;
972c4866d29SAdam Nemet 
973c4866d29SAdam Nemet   // The index in GEP is signed.  It is non-wrapping if it's derived from a NSW
974c4866d29SAdam Nemet   // AddRec using a NSW operation.
975c4866d29SAdam Nemet   if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(NonConstIndex))
976c4866d29SAdam Nemet     if (OBO->hasNoSignedWrap() &&
977c4866d29SAdam Nemet         // Assume constant for other the operand so that the AddRec can be
978c4866d29SAdam Nemet         // easily found.
979c4866d29SAdam Nemet         isa<ConstantInt>(OBO->getOperand(1))) {
980ea63a7f5SSilviu Baranga       auto *OpScev = PSE.getSCEV(OBO->getOperand(0));
981c4866d29SAdam Nemet 
982c4866d29SAdam Nemet       if (auto *OpAR = dyn_cast<SCEVAddRecExpr>(OpScev))
983c4866d29SAdam Nemet         return OpAR->getLoop() == L && OpAR->getNoWrapFlags(SCEV::FlagNSW);
984c4866d29SAdam Nemet     }
985c4866d29SAdam Nemet 
986c4866d29SAdam Nemet   return false;
987c4866d29SAdam Nemet }
988c4866d29SAdam Nemet 
9895f8f34e4SAdrian Prantl /// Check whether the access through \p Ptr has a constant stride.
9907afb46d3SDavid Majnemer int64_t llvm::getPtrStride(PredicatedScalarEvolution &PSE, Value *Ptr,
991ea63a7f5SSilviu Baranga                            const Loop *Lp, const ValueToValueMap &StridesMap,
9925f8cc0c3SElena Demikhovsky                            bool Assume, bool ShouldCheckWrap) {
993e3dcce97SCraig Topper   Type *Ty = Ptr->getType();
9940456327cSAdam Nemet   assert(Ty->isPointerTy() && "Unexpected non-ptr");
9950456327cSAdam Nemet 
9960456327cSAdam Nemet   // Make sure that the pointer does not point to aggregate types.
997e3dcce97SCraig Topper   auto *PtrTy = cast<PointerType>(Ty);
9980456327cSAdam Nemet   if (PtrTy->getElementType()->isAggregateType()) {
999d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type"
1000d34e60caSNicola Zaghen                       << *Ptr << "\n");
10010456327cSAdam Nemet     return 0;
10020456327cSAdam Nemet   }
10030456327cSAdam Nemet 
10049cd9a7e3SSilviu Baranga   const SCEV *PtrScev = replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr);
10050456327cSAdam Nemet 
10060456327cSAdam Nemet   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
1007ea63a7f5SSilviu Baranga   if (Assume && !AR)
1008d68ed854SSilviu Baranga     AR = PSE.getAsAddRec(Ptr);
1009ea63a7f5SSilviu Baranga 
10100456327cSAdam Nemet   if (!AR) {
1011d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer " << *Ptr
1012ea63a7f5SSilviu Baranga                       << " SCEV: " << *PtrScev << "\n");
10130456327cSAdam Nemet     return 0;
10140456327cSAdam Nemet   }
10150456327cSAdam Nemet 
1016c437f310SHiroshi Inoue   // The access function must stride over the innermost loop.
10170456327cSAdam Nemet   if (Lp != AR->getLoop()) {
1018d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop "
1019d34e60caSNicola Zaghen                       << *Ptr << " SCEV: " << *AR << "\n");
1020a02ce98bSKyle Butt     return 0;
10210456327cSAdam Nemet   }
10220456327cSAdam Nemet 
10230456327cSAdam Nemet   // The address calculation must not wrap. Otherwise, a dependence could be
10240456327cSAdam Nemet   // inverted.
10250456327cSAdam Nemet   // An inbounds getelementptr that is a AddRec with a unit stride
10260456327cSAdam Nemet   // cannot wrap per definition. The unit stride requirement is checked later.
10270456327cSAdam Nemet   // An getelementptr without an inbounds attribute and unit stride would have
10280456327cSAdam Nemet   // to access the pointer value "0" which is undefined behavior in address
10290456327cSAdam Nemet   // space 0, therefore we can also vectorize this case.
10300456327cSAdam Nemet   bool IsInBoundsGEP = isInBoundsGep(Ptr);
10315f8cc0c3SElena Demikhovsky   bool IsNoWrapAddRec = !ShouldCheckWrap ||
1032ea63a7f5SSilviu Baranga     PSE.hasNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW) ||
1033ea63a7f5SSilviu Baranga     isNoWrapAddRec(Ptr, AR, PSE, Lp);
103477eeac3dSManoj Gupta   if (!IsNoWrapAddRec && !IsInBoundsGEP &&
103577eeac3dSManoj Gupta       NullPointerIsDefined(Lp->getHeader()->getParent(),
103677eeac3dSManoj Gupta                            PtrTy->getAddressSpace())) {
1037ea63a7f5SSilviu Baranga     if (Assume) {
1038ea63a7f5SSilviu Baranga       PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
1039ea63a7f5SSilviu Baranga       IsNoWrapAddRec = true;
1040d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "LAA: Pointer may wrap in the address space:\n"
1041ea63a7f5SSilviu Baranga                         << "LAA:   Pointer: " << *Ptr << "\n"
1042ea63a7f5SSilviu Baranga                         << "LAA:   SCEV: " << *AR << "\n"
1043ea63a7f5SSilviu Baranga                         << "LAA:   Added an overflow assumption\n");
1044ea63a7f5SSilviu Baranga     } else {
1045d34e60caSNicola Zaghen       LLVM_DEBUG(
1046d34e60caSNicola Zaghen           dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
1047ea63a7f5SSilviu Baranga                  << *Ptr << " SCEV: " << *AR << "\n");
10480456327cSAdam Nemet       return 0;
10490456327cSAdam Nemet     }
1050ea63a7f5SSilviu Baranga   }
10510456327cSAdam Nemet 
10520456327cSAdam Nemet   // Check the step is constant.
10539cd9a7e3SSilviu Baranga   const SCEV *Step = AR->getStepRecurrence(*PSE.getSE());
10540456327cSAdam Nemet 
1055943befedSAdam Nemet   // Calculate the pointer stride and check if it is constant.
10560456327cSAdam Nemet   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
10570456327cSAdam Nemet   if (!C) {
1058d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr
1059d34e60caSNicola Zaghen                       << " SCEV: " << *AR << "\n");
10600456327cSAdam Nemet     return 0;
10610456327cSAdam Nemet   }
10620456327cSAdam Nemet 
1063a28d91d8SMehdi Amini   auto &DL = Lp->getHeader()->getModule()->getDataLayout();
1064a28d91d8SMehdi Amini   int64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
10650de2feceSSanjoy Das   const APInt &APStepVal = C->getAPInt();
10660456327cSAdam Nemet 
10670456327cSAdam Nemet   // Huge step value - give up.
10680456327cSAdam Nemet   if (APStepVal.getBitWidth() > 64)
10690456327cSAdam Nemet     return 0;
10700456327cSAdam Nemet 
10710456327cSAdam Nemet   int64_t StepVal = APStepVal.getSExtValue();
10720456327cSAdam Nemet 
10730456327cSAdam Nemet   // Strided access.
10740456327cSAdam Nemet   int64_t Stride = StepVal / Size;
10750456327cSAdam Nemet   int64_t Rem = StepVal % Size;
10760456327cSAdam Nemet   if (Rem)
10770456327cSAdam Nemet     return 0;
10780456327cSAdam Nemet 
10790456327cSAdam Nemet   // If the SCEV could wrap but we have an inbounds gep with a unit stride we
10800456327cSAdam Nemet   // know we can't "wrap around the address space". In case of address space
10810456327cSAdam Nemet   // zero we know that this won't happen without triggering undefined behavior.
108277eeac3dSManoj Gupta   if (!IsNoWrapAddRec && Stride != 1 && Stride != -1 &&
108377eeac3dSManoj Gupta       (IsInBoundsGEP || !NullPointerIsDefined(Lp->getHeader()->getParent(),
108477eeac3dSManoj Gupta                                               PtrTy->getAddressSpace()))) {
1085ea63a7f5SSilviu Baranga     if (Assume) {
1086ea63a7f5SSilviu Baranga       // We can avoid this case by adding a run-time check.
1087d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "LAA: Non unit strided pointer which is not either "
1088c437f310SHiroshi Inoue                         << "inbounds or in address space 0 may wrap:\n"
1089ea63a7f5SSilviu Baranga                         << "LAA:   Pointer: " << *Ptr << "\n"
1090ea63a7f5SSilviu Baranga                         << "LAA:   SCEV: " << *AR << "\n"
1091ea63a7f5SSilviu Baranga                         << "LAA:   Added an overflow assumption\n");
1092ea63a7f5SSilviu Baranga       PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
1093ea63a7f5SSilviu Baranga     } else
10940456327cSAdam Nemet       return 0;
1095ea63a7f5SSilviu Baranga   }
10960456327cSAdam Nemet 
10970456327cSAdam Nemet   return Stride;
10980456327cSAdam Nemet }
10990456327cSAdam Nemet 
1100428e9d9dSAlexey Bataev bool llvm::sortPtrAccesses(ArrayRef<Value *> VL, const DataLayout &DL,
1101428e9d9dSAlexey Bataev                            ScalarEvolution &SE,
1102428e9d9dSAlexey Bataev                            SmallVectorImpl<unsigned> &SortedIndices) {
1103428e9d9dSAlexey Bataev   assert(llvm::all_of(
1104428e9d9dSAlexey Bataev              VL, [](const Value *V) { return V->getType()->isPointerTy(); }) &&
1105428e9d9dSAlexey Bataev          "Expected list of pointer operands.");
1106428e9d9dSAlexey Bataev   SmallVector<std::pair<int64_t, Value *>, 4> OffValPairs;
1107428e9d9dSAlexey Bataev   OffValPairs.reserve(VL.size());
1108428e9d9dSAlexey Bataev 
1109428e9d9dSAlexey Bataev   // Walk over the pointers, and map each of them to an offset relative to
1110428e9d9dSAlexey Bataev   // first pointer in the array.
1111428e9d9dSAlexey Bataev   Value *Ptr0 = VL[0];
1112428e9d9dSAlexey Bataev   const SCEV *Scev0 = SE.getSCEV(Ptr0);
1113428e9d9dSAlexey Bataev   Value *Obj0 = GetUnderlyingObject(Ptr0, DL);
1114428e9d9dSAlexey Bataev 
1115428e9d9dSAlexey Bataev   llvm::SmallSet<int64_t, 4> Offsets;
1116428e9d9dSAlexey Bataev   for (auto *Ptr : VL) {
1117428e9d9dSAlexey Bataev     // TODO: Outline this code as a special, more time consuming, version of
1118428e9d9dSAlexey Bataev     // computeConstantDifference() function.
1119428e9d9dSAlexey Bataev     if (Ptr->getType()->getPointerAddressSpace() !=
1120428e9d9dSAlexey Bataev         Ptr0->getType()->getPointerAddressSpace())
1121428e9d9dSAlexey Bataev       return false;
1122428e9d9dSAlexey Bataev     // If a pointer refers to a different underlying object, bail - the
1123428e9d9dSAlexey Bataev     // pointers are by definition incomparable.
1124428e9d9dSAlexey Bataev     Value *CurrObj = GetUnderlyingObject(Ptr, DL);
1125428e9d9dSAlexey Bataev     if (CurrObj != Obj0)
1126428e9d9dSAlexey Bataev       return false;
1127428e9d9dSAlexey Bataev 
1128428e9d9dSAlexey Bataev     const SCEV *Scev = SE.getSCEV(Ptr);
1129428e9d9dSAlexey Bataev     const auto *Diff = dyn_cast<SCEVConstant>(SE.getMinusSCEV(Scev, Scev0));
1130428e9d9dSAlexey Bataev     // The pointers may not have a constant offset from each other, or SCEV
1131428e9d9dSAlexey Bataev     // may just not be smart enough to figure out they do. Regardless,
1132428e9d9dSAlexey Bataev     // there's nothing we can do.
1133428e9d9dSAlexey Bataev     if (!Diff)
1134428e9d9dSAlexey Bataev       return false;
1135428e9d9dSAlexey Bataev 
1136428e9d9dSAlexey Bataev     // Check if the pointer with the same offset is found.
1137428e9d9dSAlexey Bataev     int64_t Offset = Diff->getAPInt().getSExtValue();
1138428e9d9dSAlexey Bataev     if (!Offsets.insert(Offset).second)
1139428e9d9dSAlexey Bataev       return false;
1140428e9d9dSAlexey Bataev     OffValPairs.emplace_back(Offset, Ptr);
1141428e9d9dSAlexey Bataev   }
1142428e9d9dSAlexey Bataev   SortedIndices.clear();
1143428e9d9dSAlexey Bataev   SortedIndices.resize(VL.size());
1144428e9d9dSAlexey Bataev   std::iota(SortedIndices.begin(), SortedIndices.end(), 0);
1145428e9d9dSAlexey Bataev 
1146428e9d9dSAlexey Bataev   // Sort the memory accesses and keep the order of their uses in UseOrder.
1147428e9d9dSAlexey Bataev   std::stable_sort(SortedIndices.begin(), SortedIndices.end(),
1148428e9d9dSAlexey Bataev                    [&OffValPairs](unsigned Left, unsigned Right) {
1149428e9d9dSAlexey Bataev                      return OffValPairs[Left].first < OffValPairs[Right].first;
1150428e9d9dSAlexey Bataev                    });
1151428e9d9dSAlexey Bataev 
1152428e9d9dSAlexey Bataev   // Check if the order is consecutive already.
1153428e9d9dSAlexey Bataev   if (llvm::all_of(SortedIndices, [&SortedIndices](const unsigned I) {
1154428e9d9dSAlexey Bataev         return I == SortedIndices[I];
1155428e9d9dSAlexey Bataev       }))
1156428e9d9dSAlexey Bataev     SortedIndices.clear();
1157428e9d9dSAlexey Bataev 
1158428e9d9dSAlexey Bataev   return true;
1159428e9d9dSAlexey Bataev }
1160428e9d9dSAlexey Bataev 
1161f1c00a22SHaicheng Wu /// Take the address space operand from the Load/Store instruction.
1162f1c00a22SHaicheng Wu /// Returns -1 if this is not a valid Load/Store instruction.
1163f1c00a22SHaicheng Wu static unsigned getAddressSpaceOperand(Value *I) {
1164f1c00a22SHaicheng Wu   if (LoadInst *L = dyn_cast<LoadInst>(I))
1165f1c00a22SHaicheng Wu     return L->getPointerAddressSpace();
1166f1c00a22SHaicheng Wu   if (StoreInst *S = dyn_cast<StoreInst>(I))
1167f1c00a22SHaicheng Wu     return S->getPointerAddressSpace();
1168f1c00a22SHaicheng Wu   return -1;
1169f1c00a22SHaicheng Wu }
1170f1c00a22SHaicheng Wu 
1171f1c00a22SHaicheng Wu /// Returns true if the memory operations \p A and \p B are consecutive.
1172f1c00a22SHaicheng Wu bool llvm::isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL,
1173f1c00a22SHaicheng Wu                                ScalarEvolution &SE, bool CheckType) {
1174038ede2aSRenato Golin   Value *PtrA = getLoadStorePointerOperand(A);
1175038ede2aSRenato Golin   Value *PtrB = getLoadStorePointerOperand(B);
1176f1c00a22SHaicheng Wu   unsigned ASA = getAddressSpaceOperand(A);
1177f1c00a22SHaicheng Wu   unsigned ASB = getAddressSpaceOperand(B);
1178f1c00a22SHaicheng Wu 
1179f1c00a22SHaicheng Wu   // Check that the address spaces match and that the pointers are valid.
1180f1c00a22SHaicheng Wu   if (!PtrA || !PtrB || (ASA != ASB))
1181f1c00a22SHaicheng Wu     return false;
1182f1c00a22SHaicheng Wu 
1183f1c00a22SHaicheng Wu   // Make sure that A and B are different pointers.
1184f1c00a22SHaicheng Wu   if (PtrA == PtrB)
1185f1c00a22SHaicheng Wu     return false;
1186f1c00a22SHaicheng Wu 
1187f1c00a22SHaicheng Wu   // Make sure that A and B have the same type if required.
1188f1c00a22SHaicheng Wu   if (CheckType && PtrA->getType() != PtrB->getType())
1189f1c00a22SHaicheng Wu     return false;
1190f1c00a22SHaicheng Wu 
1191945b7e5aSElena Demikhovsky   unsigned IdxWidth = DL.getIndexSizeInBits(ASA);
1192f1c00a22SHaicheng Wu   Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1193945b7e5aSElena Demikhovsky   APInt Size(IdxWidth, DL.getTypeStoreSize(Ty));
1194f1c00a22SHaicheng Wu 
1195945b7e5aSElena Demikhovsky   APInt OffsetA(IdxWidth, 0), OffsetB(IdxWidth, 0);
1196f1c00a22SHaicheng Wu   PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetA);
1197f1c00a22SHaicheng Wu   PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetB);
1198f1c00a22SHaicheng Wu 
1199f1c00a22SHaicheng Wu   //  OffsetDelta = OffsetB - OffsetA;
1200f1c00a22SHaicheng Wu   const SCEV *OffsetSCEVA = SE.getConstant(OffsetA);
1201f1c00a22SHaicheng Wu   const SCEV *OffsetSCEVB = SE.getConstant(OffsetB);
1202f1c00a22SHaicheng Wu   const SCEV *OffsetDeltaSCEV = SE.getMinusSCEV(OffsetSCEVB, OffsetSCEVA);
1203f1c00a22SHaicheng Wu   const SCEVConstant *OffsetDeltaC = dyn_cast<SCEVConstant>(OffsetDeltaSCEV);
1204f1c00a22SHaicheng Wu   const APInt &OffsetDelta = OffsetDeltaC->getAPInt();
1205f1c00a22SHaicheng Wu   // Check if they are based on the same pointer. That makes the offsets
1206f1c00a22SHaicheng Wu   // sufficient.
1207f1c00a22SHaicheng Wu   if (PtrA == PtrB)
1208f1c00a22SHaicheng Wu     return OffsetDelta == Size;
1209f1c00a22SHaicheng Wu 
1210f1c00a22SHaicheng Wu   // Compute the necessary base pointer delta to have the necessary final delta
1211f1c00a22SHaicheng Wu   // equal to the size.
1212f1c00a22SHaicheng Wu   // BaseDelta = Size - OffsetDelta;
1213f1c00a22SHaicheng Wu   const SCEV *SizeSCEV = SE.getConstant(Size);
1214f1c00a22SHaicheng Wu   const SCEV *BaseDelta = SE.getMinusSCEV(SizeSCEV, OffsetDeltaSCEV);
1215f1c00a22SHaicheng Wu 
1216f1c00a22SHaicheng Wu   // Otherwise compute the distance with SCEV between the base pointers.
1217f1c00a22SHaicheng Wu   const SCEV *PtrSCEVA = SE.getSCEV(PtrA);
1218f1c00a22SHaicheng Wu   const SCEV *PtrSCEVB = SE.getSCEV(PtrB);
1219f1c00a22SHaicheng Wu   const SCEV *X = SE.getAddExpr(PtrSCEVA, BaseDelta);
1220f1c00a22SHaicheng Wu   return X == PtrSCEVB;
1221f1c00a22SHaicheng Wu }
1222f1c00a22SHaicheng Wu 
1223485f2826SFlorian Hahn MemoryDepChecker::VectorizationSafetyStatus
1224485f2826SFlorian Hahn MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
12259c926579SAdam Nemet   switch (Type) {
12269c926579SAdam Nemet   case NoDep:
12279c926579SAdam Nemet   case Forward:
12289c926579SAdam Nemet   case BackwardVectorizable:
1229485f2826SFlorian Hahn     return VectorizationSafetyStatus::Safe;
12309c926579SAdam Nemet 
12319c926579SAdam Nemet   case Unknown:
1232ef307b8cSFlorian Hahn     return VectorizationSafetyStatus::PossiblySafeWithRtChecks;
12339c926579SAdam Nemet   case ForwardButPreventsForwarding:
12349c926579SAdam Nemet   case Backward:
12359c926579SAdam Nemet   case BackwardVectorizableButPreventsForwarding:
1236485f2826SFlorian Hahn     return VectorizationSafetyStatus::Unsafe;
12379c926579SAdam Nemet   }
1238d388e930SDavid Majnemer   llvm_unreachable("unexpected DepType!");
12399c926579SAdam Nemet }
12409c926579SAdam Nemet 
1241397f5829SAdam Nemet bool MemoryDepChecker::Dependence::isBackward() const {
12429c926579SAdam Nemet   switch (Type) {
12439c926579SAdam Nemet   case NoDep:
12449c926579SAdam Nemet   case Forward:
12459c926579SAdam Nemet   case ForwardButPreventsForwarding:
1246397f5829SAdam Nemet   case Unknown:
12479c926579SAdam Nemet     return false;
12489c926579SAdam Nemet 
12499c926579SAdam Nemet   case BackwardVectorizable:
12509c926579SAdam Nemet   case Backward:
12519c926579SAdam Nemet   case BackwardVectorizableButPreventsForwarding:
12529c926579SAdam Nemet     return true;
12539c926579SAdam Nemet   }
1254d388e930SDavid Majnemer   llvm_unreachable("unexpected DepType!");
12559c926579SAdam Nemet }
12569c926579SAdam Nemet 
1257397f5829SAdam Nemet bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
1258397f5829SAdam Nemet   return isBackward() || Type == Unknown;
1259397f5829SAdam Nemet }
1260397f5829SAdam Nemet 
1261397f5829SAdam Nemet bool MemoryDepChecker::Dependence::isForward() const {
1262397f5829SAdam Nemet   switch (Type) {
1263397f5829SAdam Nemet   case Forward:
1264397f5829SAdam Nemet   case ForwardButPreventsForwarding:
1265397f5829SAdam Nemet     return true;
1266397f5829SAdam Nemet 
1267397f5829SAdam Nemet   case NoDep:
1268397f5829SAdam Nemet   case Unknown:
1269397f5829SAdam Nemet   case BackwardVectorizable:
1270397f5829SAdam Nemet   case Backward:
1271397f5829SAdam Nemet   case BackwardVectorizableButPreventsForwarding:
1272397f5829SAdam Nemet     return false;
1273397f5829SAdam Nemet   }
1274397f5829SAdam Nemet   llvm_unreachable("unexpected DepType!");
1275397f5829SAdam Nemet }
1276397f5829SAdam Nemet 
12777afb46d3SDavid Majnemer bool MemoryDepChecker::couldPreventStoreLoadForward(uint64_t Distance,
12787afb46d3SDavid Majnemer                                                     uint64_t TypeByteSize) {
12790456327cSAdam Nemet   // If loads occur at a distance that is not a multiple of a feasible vector
12800456327cSAdam Nemet   // factor store-load forwarding does not take place.
12810456327cSAdam Nemet   // Positive dependences might cause troubles because vectorizing them might
12820456327cSAdam Nemet   // prevent store-load forwarding making vectorized code run a lot slower.
12830456327cSAdam Nemet   //   a[i] = a[i-3] ^ a[i-8];
12840456327cSAdam Nemet   //   The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
12850456327cSAdam Nemet   //   hence on your typical architecture store-load forwarding does not take
12860456327cSAdam Nemet   //   place. Vectorizing in such cases does not make sense.
12870456327cSAdam Nemet   // Store-load forwarding distance.
1288884d313bSAdam Nemet 
1289884d313bSAdam Nemet   // After this many iterations store-to-load forwarding conflicts should not
1290884d313bSAdam Nemet   // cause any slowdowns.
12917afb46d3SDavid Majnemer   const uint64_t NumItersForStoreLoadThroughMemory = 8 * TypeByteSize;
12920456327cSAdam Nemet   // Maximum vector factor.
12937afb46d3SDavid Majnemer   uint64_t MaxVFWithoutSLForwardIssues = std::min(
12942c34ab51SAdam Nemet       VectorizerParams::MaxVectorWidth * TypeByteSize, MaxSafeDepDistBytes);
12950456327cSAdam Nemet 
1296884d313bSAdam Nemet   // Compute the smallest VF at which the store and load would be misaligned.
12977afb46d3SDavid Majnemer   for (uint64_t VF = 2 * TypeByteSize; VF <= MaxVFWithoutSLForwardIssues;
12989b5852aeSAdam Nemet        VF *= 2) {
1299884d313bSAdam Nemet     // If the number of vector iteration between the store and the load are
1300884d313bSAdam Nemet     // small we could incur conflicts.
1301884d313bSAdam Nemet     if (Distance % VF && Distance / VF < NumItersForStoreLoadThroughMemory) {
13029b5852aeSAdam Nemet       MaxVFWithoutSLForwardIssues = (VF >>= 1);
13030456327cSAdam Nemet       break;
13040456327cSAdam Nemet     }
13050456327cSAdam Nemet   }
13060456327cSAdam Nemet 
13070456327cSAdam Nemet   if (MaxVFWithoutSLForwardIssues < 2 * TypeByteSize) {
1308d34e60caSNicola Zaghen     LLVM_DEBUG(
1309d34e60caSNicola Zaghen         dbgs() << "LAA: Distance " << Distance
13109b5852aeSAdam Nemet                << " that could cause a store-load forwarding conflict\n");
13110456327cSAdam Nemet     return true;
13120456327cSAdam Nemet   }
13130456327cSAdam Nemet 
13140456327cSAdam Nemet   if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
1315f219c647SAdam Nemet       MaxVFWithoutSLForwardIssues !=
1316f219c647SAdam Nemet           VectorizerParams::MaxVectorWidth * TypeByteSize)
13170456327cSAdam Nemet     MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
13180456327cSAdam Nemet   return false;
13190456327cSAdam Nemet }
13200456327cSAdam Nemet 
1321485f2826SFlorian Hahn void MemoryDepChecker::mergeInStatus(VectorizationSafetyStatus S) {
1322485f2826SFlorian Hahn   if (Status < S)
1323485f2826SFlorian Hahn     Status = S;
1324485f2826SFlorian Hahn }
1325485f2826SFlorian Hahn 
1326eac89d73SDorit Nuzman /// Given a non-constant (unknown) dependence-distance \p Dist between two
1327eac89d73SDorit Nuzman /// memory accesses, that have the same stride whose absolute value is given
1328eac89d73SDorit Nuzman /// in \p Stride, and that have the same type size \p TypeByteSize,
1329eac89d73SDorit Nuzman /// in a loop whose takenCount is \p BackedgeTakenCount, check if it is
1330eac89d73SDorit Nuzman /// possible to prove statically that the dependence distance is larger
1331eac89d73SDorit Nuzman /// than the range that the accesses will travel through the execution of
1332eac89d73SDorit Nuzman /// the loop. If so, return true; false otherwise. This is useful for
1333eac89d73SDorit Nuzman /// example in loops such as the following (PR31098):
1334eac89d73SDorit Nuzman ///     for (i = 0; i < D; ++i) {
1335eac89d73SDorit Nuzman ///                = out[i];
1336eac89d73SDorit Nuzman ///       out[i+D] =
1337eac89d73SDorit Nuzman ///     }
1338eac89d73SDorit Nuzman static bool isSafeDependenceDistance(const DataLayout &DL, ScalarEvolution &SE,
1339eac89d73SDorit Nuzman                                      const SCEV &BackedgeTakenCount,
1340eac89d73SDorit Nuzman                                      const SCEV &Dist, uint64_t Stride,
1341eac89d73SDorit Nuzman                                      uint64_t TypeByteSize) {
1342eac89d73SDorit Nuzman 
1343eac89d73SDorit Nuzman   // If we can prove that
1344eac89d73SDorit Nuzman   //      (**) |Dist| > BackedgeTakenCount * Step
1345eac89d73SDorit Nuzman   // where Step is the absolute stride of the memory accesses in bytes,
1346eac89d73SDorit Nuzman   // then there is no dependence.
1347eac89d73SDorit Nuzman   //
1348c437f310SHiroshi Inoue   // Rationale:
1349eac89d73SDorit Nuzman   // We basically want to check if the absolute distance (|Dist/Step|)
1350eac89d73SDorit Nuzman   // is >= the loop iteration count (or > BackedgeTakenCount).
1351eac89d73SDorit Nuzman   // This is equivalent to the Strong SIV Test (Practical Dependence Testing,
1352eac89d73SDorit Nuzman   // Section 4.2.1); Note, that for vectorization it is sufficient to prove
1353eac89d73SDorit Nuzman   // that the dependence distance is >= VF; This is checked elsewhere.
1354eac89d73SDorit Nuzman   // But in some cases we can prune unknown dependence distances early, and
1355eac89d73SDorit Nuzman   // even before selecting the VF, and without a runtime test, by comparing
1356eac89d73SDorit Nuzman   // the distance against the loop iteration count. Since the vectorized code
1357eac89d73SDorit Nuzman   // will be executed only if LoopCount >= VF, proving distance >= LoopCount
1358eac89d73SDorit Nuzman   // also guarantees that distance >= VF.
1359eac89d73SDorit Nuzman   //
1360eac89d73SDorit Nuzman   const uint64_t ByteStride = Stride * TypeByteSize;
1361eac89d73SDorit Nuzman   const SCEV *Step = SE.getConstant(BackedgeTakenCount.getType(), ByteStride);
1362eac89d73SDorit Nuzman   const SCEV *Product = SE.getMulExpr(&BackedgeTakenCount, Step);
1363eac89d73SDorit Nuzman 
1364eac89d73SDorit Nuzman   const SCEV *CastedDist = &Dist;
1365eac89d73SDorit Nuzman   const SCEV *CastedProduct = Product;
1366eac89d73SDorit Nuzman   uint64_t DistTypeSize = DL.getTypeAllocSize(Dist.getType());
1367eac89d73SDorit Nuzman   uint64_t ProductTypeSize = DL.getTypeAllocSize(Product->getType());
1368eac89d73SDorit Nuzman 
1369eac89d73SDorit Nuzman   // The dependence distance can be positive/negative, so we sign extend Dist;
1370eac89d73SDorit Nuzman   // The multiplication of the absolute stride in bytes and the
1371c437f310SHiroshi Inoue   // backedgeTakenCount is non-negative, so we zero extend Product.
1372eac89d73SDorit Nuzman   if (DistTypeSize > ProductTypeSize)
1373eac89d73SDorit Nuzman     CastedProduct = SE.getZeroExtendExpr(Product, Dist.getType());
1374eac89d73SDorit Nuzman   else
1375eac89d73SDorit Nuzman     CastedDist = SE.getNoopOrSignExtend(&Dist, Product->getType());
1376eac89d73SDorit Nuzman 
1377eac89d73SDorit Nuzman   // Is  Dist - (BackedgeTakenCount * Step) > 0 ?
1378eac89d73SDorit Nuzman   // (If so, then we have proven (**) because |Dist| >= Dist)
1379eac89d73SDorit Nuzman   const SCEV *Minus = SE.getMinusSCEV(CastedDist, CastedProduct);
1380eac89d73SDorit Nuzman   if (SE.isKnownPositive(Minus))
1381eac89d73SDorit Nuzman     return true;
1382eac89d73SDorit Nuzman 
1383eac89d73SDorit Nuzman   // Second try: Is  -Dist - (BackedgeTakenCount * Step) > 0 ?
1384eac89d73SDorit Nuzman   // (If so, then we have proven (**) because |Dist| >= -1*Dist)
1385eac89d73SDorit Nuzman   const SCEV *NegDist = SE.getNegativeSCEV(CastedDist);
1386eac89d73SDorit Nuzman   Minus = SE.getMinusSCEV(NegDist, CastedProduct);
1387eac89d73SDorit Nuzman   if (SE.isKnownPositive(Minus))
1388eac89d73SDorit Nuzman     return true;
1389eac89d73SDorit Nuzman 
1390eac89d73SDorit Nuzman   return false;
1391eac89d73SDorit Nuzman }
1392eac89d73SDorit Nuzman 
13935f8f34e4SAdrian Prantl /// Check the dependence for two accesses with the same stride \p Stride.
1394751004a6SHao Liu /// \p Distance is the positive distance and \p TypeByteSize is type size in
1395751004a6SHao Liu /// bytes.
1396751004a6SHao Liu ///
1397751004a6SHao Liu /// \returns true if they are independent.
13987afb46d3SDavid Majnemer static bool areStridedAccessesIndependent(uint64_t Distance, uint64_t Stride,
13997afb46d3SDavid Majnemer                                           uint64_t TypeByteSize) {
1400751004a6SHao Liu   assert(Stride > 1 && "The stride must be greater than 1");
1401751004a6SHao Liu   assert(TypeByteSize > 0 && "The type size in byte must be non-zero");
1402751004a6SHao Liu   assert(Distance > 0 && "The distance must be non-zero");
1403751004a6SHao Liu 
1404751004a6SHao Liu   // Skip if the distance is not multiple of type byte size.
1405751004a6SHao Liu   if (Distance % TypeByteSize)
1406751004a6SHao Liu     return false;
1407751004a6SHao Liu 
14087afb46d3SDavid Majnemer   uint64_t ScaledDist = Distance / TypeByteSize;
1409751004a6SHao Liu 
1410751004a6SHao Liu   // No dependence if the scaled distance is not multiple of the stride.
1411751004a6SHao Liu   // E.g.
1412751004a6SHao Liu   //      for (i = 0; i < 1024 ; i += 4)
1413751004a6SHao Liu   //        A[i+2] = A[i] + 1;
1414751004a6SHao Liu   //
1415751004a6SHao Liu   // Two accesses in memory (scaled distance is 2, stride is 4):
1416751004a6SHao Liu   //     | A[0] |      |      |      | A[4] |      |      |      |
1417751004a6SHao Liu   //     |      |      | A[2] |      |      |      | A[6] |      |
1418751004a6SHao Liu   //
1419751004a6SHao Liu   // E.g.
1420751004a6SHao Liu   //      for (i = 0; i < 1024 ; i += 3)
1421751004a6SHao Liu   //        A[i+4] = A[i] + 1;
1422751004a6SHao Liu   //
1423751004a6SHao Liu   // Two accesses in memory (scaled distance is 4, stride is 3):
1424751004a6SHao Liu   //     | A[0] |      |      | A[3] |      |      | A[6] |      |      |
1425751004a6SHao Liu   //     |      |      |      |      | A[4] |      |      | A[7] |      |
1426751004a6SHao Liu   return ScaledDist % Stride;
1427751004a6SHao Liu }
1428751004a6SHao Liu 
14299c926579SAdam Nemet MemoryDepChecker::Dependence::DepType
14309c926579SAdam Nemet MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
14310456327cSAdam Nemet                               const MemAccessInfo &B, unsigned BIdx,
14328bc61df9SAdam Nemet                               const ValueToValueMap &Strides) {
14330456327cSAdam Nemet   assert (AIdx < BIdx && "Must pass arguments in program order");
14340456327cSAdam Nemet 
14350456327cSAdam Nemet   Value *APtr = A.getPointer();
14360456327cSAdam Nemet   Value *BPtr = B.getPointer();
14370456327cSAdam Nemet   bool AIsWrite = A.getInt();
14380456327cSAdam Nemet   bool BIsWrite = B.getInt();
14390456327cSAdam Nemet 
14400456327cSAdam Nemet   // Two reads are independent.
14410456327cSAdam Nemet   if (!AIsWrite && !BIsWrite)
14429c926579SAdam Nemet     return Dependence::NoDep;
14430456327cSAdam Nemet 
14440456327cSAdam Nemet   // We cannot check pointers in different address spaces.
14450456327cSAdam Nemet   if (APtr->getType()->getPointerAddressSpace() !=
14460456327cSAdam Nemet       BPtr->getType()->getPointerAddressSpace())
14479c926579SAdam Nemet     return Dependence::Unknown;
14480456327cSAdam Nemet 
14497afb46d3SDavid Majnemer   int64_t StrideAPtr = getPtrStride(PSE, APtr, InnermostLoop, Strides, true);
14507afb46d3SDavid Majnemer   int64_t StrideBPtr = getPtrStride(PSE, BPtr, InnermostLoop, Strides, true);
14510456327cSAdam Nemet 
1452adf4b739SSilviu Baranga   const SCEV *Src = PSE.getSCEV(APtr);
1453adf4b739SSilviu Baranga   const SCEV *Sink = PSE.getSCEV(BPtr);
14540456327cSAdam Nemet 
14550456327cSAdam Nemet   // If the induction step is negative we have to invert source and sink of the
14560456327cSAdam Nemet   // dependence.
14570456327cSAdam Nemet   if (StrideAPtr < 0) {
14580456327cSAdam Nemet     std::swap(APtr, BPtr);
14590456327cSAdam Nemet     std::swap(Src, Sink);
14600456327cSAdam Nemet     std::swap(AIsWrite, BIsWrite);
14610456327cSAdam Nemet     std::swap(AIdx, BIdx);
14620456327cSAdam Nemet     std::swap(StrideAPtr, StrideBPtr);
14630456327cSAdam Nemet   }
14640456327cSAdam Nemet 
14659cd9a7e3SSilviu Baranga   const SCEV *Dist = PSE.getSE()->getMinusSCEV(Sink, Src);
14660456327cSAdam Nemet 
1467d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
14680456327cSAdam Nemet                     << "(Induction step: " << StrideAPtr << ")\n");
1469d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
14700456327cSAdam Nemet                     << *InstMap[BIdx] << ": " << *Dist << "\n");
14710456327cSAdam Nemet 
1472943befedSAdam Nemet   // Need accesses with constant stride. We don't want to vectorize
14730456327cSAdam Nemet   // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
14740456327cSAdam Nemet   // the address space.
14750456327cSAdam Nemet   if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
1476d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Pointer access with non-constant stride\n");
14779c926579SAdam Nemet     return Dependence::Unknown;
14780456327cSAdam Nemet   }
14790456327cSAdam Nemet 
1480eac89d73SDorit Nuzman   Type *ATy = APtr->getType()->getPointerElementType();
1481eac89d73SDorit Nuzman   Type *BTy = BPtr->getType()->getPointerElementType();
1482eac89d73SDorit Nuzman   auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
1483eac89d73SDorit Nuzman   uint64_t TypeByteSize = DL.getTypeAllocSize(ATy);
1484eac89d73SDorit Nuzman   uint64_t Stride = std::abs(StrideAPtr);
14850456327cSAdam Nemet   const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
14860456327cSAdam Nemet   if (!C) {
1487eac89d73SDorit Nuzman     if (TypeByteSize == DL.getTypeAllocSize(BTy) &&
1488eac89d73SDorit Nuzman         isSafeDependenceDistance(DL, *(PSE.getSE()),
1489eac89d73SDorit Nuzman                                  *(PSE.getBackedgeTakenCount()), *Dist, Stride,
1490eac89d73SDorit Nuzman                                  TypeByteSize))
1491eac89d73SDorit Nuzman       return Dependence::NoDep;
1492eac89d73SDorit Nuzman 
1493d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
1494ef307b8cSFlorian Hahn     FoundNonConstantDistanceDependence = true;
14959c926579SAdam Nemet     return Dependence::Unknown;
14960456327cSAdam Nemet   }
14970456327cSAdam Nemet 
14980de2feceSSanjoy Das   const APInt &Val = C->getAPInt();
14996feebe98SMatthew Simpson   int64_t Distance = Val.getSExtValue();
15006feebe98SMatthew Simpson 
15016feebe98SMatthew Simpson   // Attempt to prove strided accesses independent.
15026feebe98SMatthew Simpson   if (std::abs(Distance) > 0 && Stride > 1 && ATy == BTy &&
15036feebe98SMatthew Simpson       areStridedAccessesIndependent(std::abs(Distance), Stride, TypeByteSize)) {
1504d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LAA: Strided accesses are independent\n");
15056feebe98SMatthew Simpson     return Dependence::NoDep;
15066feebe98SMatthew Simpson   }
15076feebe98SMatthew Simpson 
15086feebe98SMatthew Simpson   // Negative distances are not plausible dependencies.
15090456327cSAdam Nemet   if (Val.isNegative()) {
15100456327cSAdam Nemet     bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
151137ec5f91SMatthew Simpson     if (IsTrueDataDependence && EnableForwardingConflictDetection &&
15120456327cSAdam Nemet         (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
1513b8486e5aSAdam Nemet          ATy != BTy)) {
1514d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "LAA: Forward but may prevent st->ld forwarding\n");
15159c926579SAdam Nemet       return Dependence::ForwardButPreventsForwarding;
1516b8486e5aSAdam Nemet     }
15170456327cSAdam Nemet 
1518d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LAA: Dependence is negative\n");
15199c926579SAdam Nemet     return Dependence::Forward;
15200456327cSAdam Nemet   }
15210456327cSAdam Nemet 
15220456327cSAdam Nemet   // Write to the same location with the same size.
15230456327cSAdam Nemet   // Could be improved to assert type sizes are the same (i32 == float, etc).
15240456327cSAdam Nemet   if (Val == 0) {
15250456327cSAdam Nemet     if (ATy == BTy)
1526d7037c56SAdam Nemet       return Dependence::Forward;
1527d34e60caSNicola Zaghen     LLVM_DEBUG(
1528d34e60caSNicola Zaghen         dbgs() << "LAA: Zero dependence difference but different types\n");
15299c926579SAdam Nemet     return Dependence::Unknown;
15300456327cSAdam Nemet   }
15310456327cSAdam Nemet 
15320456327cSAdam Nemet   assert(Val.isStrictlyPositive() && "Expect a positive value");
15330456327cSAdam Nemet 
15340456327cSAdam Nemet   if (ATy != BTy) {
1535d34e60caSNicola Zaghen     LLVM_DEBUG(
1536d34e60caSNicola Zaghen         dbgs()
1537d34e60caSNicola Zaghen         << "LAA: ReadWrite-Write positive dependency with different types\n");
15389c926579SAdam Nemet     return Dependence::Unknown;
15390456327cSAdam Nemet   }
15400456327cSAdam Nemet 
15410456327cSAdam Nemet   // Bail out early if passed-in parameters make vectorization not feasible.
1542f219c647SAdam Nemet   unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
1543f219c647SAdam Nemet                            VectorizerParams::VectorizationFactor : 1);
1544f219c647SAdam Nemet   unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
1545f219c647SAdam Nemet                            VectorizerParams::VectorizationInterleave : 1);
1546751004a6SHao Liu   // The minimum number of iterations for a vectorized/unrolled version.
1547751004a6SHao Liu   unsigned MinNumIter = std::max(ForcedFactor * ForcedUnroll, 2U);
15480456327cSAdam Nemet 
1549751004a6SHao Liu   // It's not vectorizable if the distance is smaller than the minimum distance
1550751004a6SHao Liu   // needed for a vectroized/unrolled version. Vectorizing one iteration in
1551751004a6SHao Liu   // front needs TypeByteSize * Stride. Vectorizing the last iteration needs
1552751004a6SHao Liu   // TypeByteSize (No need to plus the last gap distance).
1553751004a6SHao Liu   //
1554751004a6SHao Liu   // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1555751004a6SHao Liu   //      foo(int *A) {
1556751004a6SHao Liu   //        int *B = (int *)((char *)A + 14);
1557751004a6SHao Liu   //        for (i = 0 ; i < 1024 ; i += 2)
1558751004a6SHao Liu   //          B[i] = A[i] + 1;
1559751004a6SHao Liu   //      }
1560751004a6SHao Liu   //
1561751004a6SHao Liu   // Two accesses in memory (stride is 2):
1562751004a6SHao Liu   //     | A[0] |      | A[2] |      | A[4] |      | A[6] |      |
1563751004a6SHao Liu   //                              | B[0] |      | B[2] |      | B[4] |
1564751004a6SHao Liu   //
1565751004a6SHao Liu   // Distance needs for vectorizing iterations except the last iteration:
1566751004a6SHao Liu   // 4 * 2 * (MinNumIter - 1). Distance needs for the last iteration: 4.
1567751004a6SHao Liu   // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4.
1568751004a6SHao Liu   //
1569751004a6SHao Liu   // If MinNumIter is 2, it is vectorizable as the minimum distance needed is
1570751004a6SHao Liu   // 12, which is less than distance.
1571751004a6SHao Liu   //
1572751004a6SHao Liu   // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4),
1573751004a6SHao Liu   // the minimum distance needed is 28, which is greater than distance. It is
1574751004a6SHao Liu   // not safe to do vectorization.
15757afb46d3SDavid Majnemer   uint64_t MinDistanceNeeded =
1576751004a6SHao Liu       TypeByteSize * Stride * (MinNumIter - 1) + TypeByteSize;
15777afb46d3SDavid Majnemer   if (MinDistanceNeeded > static_cast<uint64_t>(Distance)) {
1578d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LAA: Failure because of positive distance "
1579d34e60caSNicola Zaghen                       << Distance << '\n');
1580751004a6SHao Liu     return Dependence::Backward;
1581751004a6SHao Liu   }
1582751004a6SHao Liu 
1583751004a6SHao Liu   // Unsafe if the minimum distance needed is greater than max safe distance.
1584751004a6SHao Liu   if (MinDistanceNeeded > MaxSafeDepDistBytes) {
1585d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LAA: Failure because it needs at least "
1586751004a6SHao Liu                       << MinDistanceNeeded << " size in bytes");
15879c926579SAdam Nemet     return Dependence::Backward;
15880456327cSAdam Nemet   }
15890456327cSAdam Nemet 
15909cc0c399SAdam Nemet   // Positive distance bigger than max vectorization factor.
1591751004a6SHao Liu   // FIXME: Should use max factor instead of max distance in bytes, which could
1592751004a6SHao Liu   // not handle different types.
1593751004a6SHao Liu   // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1594751004a6SHao Liu   //      void foo (int *A, char *B) {
1595751004a6SHao Liu   //        for (unsigned i = 0; i < 1024; i++) {
1596751004a6SHao Liu   //          A[i+2] = A[i] + 1;
1597751004a6SHao Liu   //          B[i+2] = B[i] + 1;
1598751004a6SHao Liu   //        }
1599751004a6SHao Liu   //      }
1600751004a6SHao Liu   //
1601751004a6SHao Liu   // This case is currently unsafe according to the max safe distance. If we
1602751004a6SHao Liu   // analyze the two accesses on array B, the max safe dependence distance
1603751004a6SHao Liu   // is 2. Then we analyze the accesses on array A, the minimum distance needed
1604751004a6SHao Liu   // is 8, which is less than 2 and forbidden vectorization, But actually
1605751004a6SHao Liu   // both A and B could be vectorized by 2 iterations.
1606751004a6SHao Liu   MaxSafeDepDistBytes =
16077afb46d3SDavid Majnemer       std::min(static_cast<uint64_t>(Distance), MaxSafeDepDistBytes);
16080456327cSAdam Nemet 
16090456327cSAdam Nemet   bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
161037ec5f91SMatthew Simpson   if (IsTrueDataDependence && EnableForwardingConflictDetection &&
16110456327cSAdam Nemet       couldPreventStoreLoadForward(Distance, TypeByteSize))
16129c926579SAdam Nemet     return Dependence::BackwardVectorizableButPreventsForwarding;
16130456327cSAdam Nemet 
1614682cfc1dSAlon Kom   uint64_t MaxVF = MaxSafeDepDistBytes / (TypeByteSize * Stride);
1615d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue()
1616682cfc1dSAlon Kom                     << " with max VF = " << MaxVF << '\n');
1617682cfc1dSAlon Kom   uint64_t MaxVFInBits = MaxVF * TypeByteSize * 8;
1618682cfc1dSAlon Kom   MaxSafeRegisterWidth = std::min(MaxSafeRegisterWidth, MaxVFInBits);
16199c926579SAdam Nemet   return Dependence::BackwardVectorizable;
16200456327cSAdam Nemet }
16210456327cSAdam Nemet 
1622dee666bcSAdam Nemet bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets,
16235448e989SAmjad Aboud                                    MemAccessInfoList &CheckDeps,
16248bc61df9SAdam Nemet                                    const ValueToValueMap &Strides) {
16250456327cSAdam Nemet 
16267afb46d3SDavid Majnemer   MaxSafeDepDistBytes = -1;
16275448e989SAmjad Aboud   SmallPtrSet<MemAccessInfo, 8> Visited;
16285448e989SAmjad Aboud   for (MemAccessInfo CurAccess : CheckDeps) {
16295448e989SAmjad Aboud     if (Visited.count(CurAccess))
16305448e989SAmjad Aboud       continue;
16310456327cSAdam Nemet 
16320456327cSAdam Nemet     // Get the relevant memory access set.
16330456327cSAdam Nemet     EquivalenceClasses<MemAccessInfo>::iterator I =
16340456327cSAdam Nemet       AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
16350456327cSAdam Nemet 
16360456327cSAdam Nemet     // Check accesses within this set.
16377a083814SRichard Trieu     EquivalenceClasses<MemAccessInfo>::member_iterator AI =
16387a083814SRichard Trieu         AccessSets.member_begin(I);
16397a083814SRichard Trieu     EquivalenceClasses<MemAccessInfo>::member_iterator AE =
16407a083814SRichard Trieu         AccessSets.member_end();
16410456327cSAdam Nemet 
16420456327cSAdam Nemet     // Check every access pair.
16430456327cSAdam Nemet     while (AI != AE) {
16445448e989SAmjad Aboud       Visited.insert(*AI);
16450456327cSAdam Nemet       EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
16460456327cSAdam Nemet       while (OI != AE) {
16470456327cSAdam Nemet         // Check every accessing instruction pair in program order.
16480456327cSAdam Nemet         for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
16490456327cSAdam Nemet              I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
16500456327cSAdam Nemet           for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
16510456327cSAdam Nemet                I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
16529c926579SAdam Nemet             auto A = std::make_pair(&*AI, *I1);
16539c926579SAdam Nemet             auto B = std::make_pair(&*OI, *I2);
16549c926579SAdam Nemet 
16559c926579SAdam Nemet             assert(*I1 != *I2);
16569c926579SAdam Nemet             if (*I1 > *I2)
16579c926579SAdam Nemet               std::swap(A, B);
16589c926579SAdam Nemet 
16599c926579SAdam Nemet             Dependence::DepType Type =
16609c926579SAdam Nemet                 isDependent(*A.first, A.second, *B.first, B.second, Strides);
1661485f2826SFlorian Hahn             mergeInStatus(Dependence::isSafeForVectorization(Type));
16629c926579SAdam Nemet 
1663a2df750fSAdam Nemet             // Gather dependences unless we accumulated MaxDependences
16649c926579SAdam Nemet             // dependences.  In that case return as soon as we find the first
16659c926579SAdam Nemet             // unsafe dependence.  This puts a limit on this quadratic
16669c926579SAdam Nemet             // algorithm.
1667a2df750fSAdam Nemet             if (RecordDependences) {
1668a2df750fSAdam Nemet               if (Type != Dependence::NoDep)
1669a2df750fSAdam Nemet                 Dependences.push_back(Dependence(A.second, B.second, Type));
16709c926579SAdam Nemet 
1671a2df750fSAdam Nemet               if (Dependences.size() >= MaxDependences) {
1672a2df750fSAdam Nemet                 RecordDependences = false;
1673a2df750fSAdam Nemet                 Dependences.clear();
1674d34e60caSNicola Zaghen                 LLVM_DEBUG(dbgs()
1675d34e60caSNicola Zaghen                            << "Too many dependences, stopped recording\n");
16769c926579SAdam Nemet               }
16779c926579SAdam Nemet             }
1678485f2826SFlorian Hahn             if (!RecordDependences && !isSafeForVectorization())
16790456327cSAdam Nemet               return false;
16800456327cSAdam Nemet           }
16810456327cSAdam Nemet         ++OI;
16820456327cSAdam Nemet       }
16830456327cSAdam Nemet       AI++;
16840456327cSAdam Nemet     }
16850456327cSAdam Nemet   }
16869c926579SAdam Nemet 
1687d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Total Dependences: " << Dependences.size() << "\n");
1688485f2826SFlorian Hahn   return isSafeForVectorization();
16890456327cSAdam Nemet }
16900456327cSAdam Nemet 
1691ec1e2bb6SAdam Nemet SmallVector<Instruction *, 4>
1692ec1e2bb6SAdam Nemet MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const {
1693ec1e2bb6SAdam Nemet   MemAccessInfo Access(Ptr, isWrite);
1694ec1e2bb6SAdam Nemet   auto &IndexVector = Accesses.find(Access)->second;
1695ec1e2bb6SAdam Nemet 
1696ec1e2bb6SAdam Nemet   SmallVector<Instruction *, 4> Insts;
16972d006e76SDavid Majnemer   transform(IndexVector,
1698ec1e2bb6SAdam Nemet                  std::back_inserter(Insts),
1699ec1e2bb6SAdam Nemet                  [&](unsigned Idx) { return this->InstMap[Idx]; });
1700ec1e2bb6SAdam Nemet   return Insts;
1701ec1e2bb6SAdam Nemet }
1702ec1e2bb6SAdam Nemet 
170358913d65SAdam Nemet const char *MemoryDepChecker::Dependence::DepName[] = {
170458913d65SAdam Nemet     "NoDep", "Unknown", "Forward", "ForwardButPreventsForwarding", "Backward",
170558913d65SAdam Nemet     "BackwardVectorizable", "BackwardVectorizableButPreventsForwarding"};
170658913d65SAdam Nemet 
170758913d65SAdam Nemet void MemoryDepChecker::Dependence::print(
170858913d65SAdam Nemet     raw_ostream &OS, unsigned Depth,
170958913d65SAdam Nemet     const SmallVectorImpl<Instruction *> &Instrs) const {
171058913d65SAdam Nemet   OS.indent(Depth) << DepName[Type] << ":\n";
171158913d65SAdam Nemet   OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
171258913d65SAdam Nemet   OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
171358913d65SAdam Nemet }
171458913d65SAdam Nemet 
1715929c38e8SAdam Nemet bool LoopAccessInfo::canAnalyzeLoop() {
17168dcb3b6aSAdam Nemet   // We need to have a loop header.
1717d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "LAA: Found a loop in "
1718d8968f09SAdam Nemet                     << TheLoop->getHeader()->getParent()->getName() << ": "
1719d8968f09SAdam Nemet                     << TheLoop->getHeader()->getName() << '\n');
17208dcb3b6aSAdam Nemet 
1721929c38e8SAdam Nemet   // We can only analyze innermost loops.
1722929c38e8SAdam Nemet   if (!TheLoop->empty()) {
1723d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
1724877ccee8SAdam Nemet     recordAnalysis("NotInnerMostLoop") << "loop is not the innermost loop";
1725929c38e8SAdam Nemet     return false;
1726929c38e8SAdam Nemet   }
1727929c38e8SAdam Nemet 
1728929c38e8SAdam Nemet   // We must have a single backedge.
1729929c38e8SAdam Nemet   if (TheLoop->getNumBackEdges() != 1) {
1730d34e60caSNicola Zaghen     LLVM_DEBUG(
1731d34e60caSNicola Zaghen         dbgs() << "LAA: loop control flow is not understood by analyzer\n");
1732877ccee8SAdam Nemet     recordAnalysis("CFGNotUnderstood")
1733877ccee8SAdam Nemet         << "loop control flow is not understood by analyzer";
1734929c38e8SAdam Nemet     return false;
1735929c38e8SAdam Nemet   }
1736929c38e8SAdam Nemet 
1737929c38e8SAdam Nemet   // We must have a single exiting block.
1738929c38e8SAdam Nemet   if (!TheLoop->getExitingBlock()) {
1739d34e60caSNicola Zaghen     LLVM_DEBUG(
1740d34e60caSNicola Zaghen         dbgs() << "LAA: loop control flow is not understood by analyzer\n");
1741877ccee8SAdam Nemet     recordAnalysis("CFGNotUnderstood")
1742877ccee8SAdam Nemet         << "loop control flow is not understood by analyzer";
1743929c38e8SAdam Nemet     return false;
1744929c38e8SAdam Nemet   }
1745929c38e8SAdam Nemet 
1746929c38e8SAdam Nemet   // We only handle bottom-tested loops, i.e. loop in which the condition is
1747929c38e8SAdam Nemet   // checked at the end of each iteration. With that we can assume that all
1748929c38e8SAdam Nemet   // instructions in the loop are executed the same number of times.
1749929c38e8SAdam Nemet   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
1750d34e60caSNicola Zaghen     LLVM_DEBUG(
1751d34e60caSNicola Zaghen         dbgs() << "LAA: loop control flow is not understood by analyzer\n");
1752877ccee8SAdam Nemet     recordAnalysis("CFGNotUnderstood")
1753877ccee8SAdam Nemet         << "loop control flow is not understood by analyzer";
1754929c38e8SAdam Nemet     return false;
1755929c38e8SAdam Nemet   }
1756929c38e8SAdam Nemet 
1757929c38e8SAdam Nemet   // ScalarEvolution needs to be able to find the exit count.
175894734eefSXinliang David Li   const SCEV *ExitCount = PSE->getBackedgeTakenCount();
175994734eefSXinliang David Li   if (ExitCount == PSE->getSE()->getCouldNotCompute()) {
1760877ccee8SAdam Nemet     recordAnalysis("CantComputeNumberOfIterations")
1761877ccee8SAdam Nemet         << "could not determine number of loop iterations";
1762d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
1763929c38e8SAdam Nemet     return false;
1764929c38e8SAdam Nemet   }
1765929c38e8SAdam Nemet 
1766929c38e8SAdam Nemet   return true;
1767929c38e8SAdam Nemet }
1768929c38e8SAdam Nemet 
1769b49d9a56SAdam Nemet void LoopAccessInfo::analyzeLoop(AliasAnalysis *AA, LoopInfo *LI,
17707da74abfSAdam Nemet                                  const TargetLibraryInfo *TLI,
17717da74abfSAdam Nemet                                  DominatorTree *DT) {
17720456327cSAdam Nemet   typedef SmallPtrSet<Value*, 16> ValueSet;
17730456327cSAdam Nemet 
1774e3e3b994SMatthew Simpson   // Holds the Load and Store instructions.
1775e3e3b994SMatthew Simpson   SmallVector<LoadInst *, 16> Loads;
1776e3e3b994SMatthew Simpson   SmallVector<StoreInst *, 16> Stores;
17770456327cSAdam Nemet 
17780456327cSAdam Nemet   // Holds all the different accesses in the loop.
17790456327cSAdam Nemet   unsigned NumReads = 0;
17800456327cSAdam Nemet   unsigned NumReadWrites = 0;
17810456327cSAdam Nemet 
1782ce030acbSXinliang David Li   PtrRtChecking->Pointers.clear();
1783ce030acbSXinliang David Li   PtrRtChecking->Need = false;
17840456327cSAdam Nemet 
17850456327cSAdam Nemet   const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
17860456327cSAdam Nemet 
17870456327cSAdam Nemet   // For each block.
17888b401013SDavid Majnemer   for (BasicBlock *BB : TheLoop->blocks()) {
17890456327cSAdam Nemet     // Scan the BB and collect legal loads and stores.
17908b401013SDavid Majnemer     for (Instruction &I : *BB) {
17910456327cSAdam Nemet       // If this is a load, save it. If this instruction can read from memory
17920456327cSAdam Nemet       // but is not a load, then we quit. Notice that we don't handle function
17930456327cSAdam Nemet       // calls that read or write.
17948b401013SDavid Majnemer       if (I.mayReadFromMemory()) {
17950456327cSAdam Nemet         // Many math library functions read the rounding mode. We will only
17960456327cSAdam Nemet         // vectorize a loop if it contains known function calls that don't set
17970456327cSAdam Nemet         // the flag. Therefore, it is safe to ignore this read from memory.
17988b401013SDavid Majnemer         auto *Call = dyn_cast<CallInst>(&I);
1799b4b27230SDavid Majnemer         if (Call && getVectorIntrinsicIDForCall(Call, TLI))
18000456327cSAdam Nemet           continue;
18010456327cSAdam Nemet 
18029b3cf604SMichael Zolotukhin         // If the function has an explicit vectorized counterpart, we can safely
18039b3cf604SMichael Zolotukhin         // assume that it can be vectorized.
18049b3cf604SMichael Zolotukhin         if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
18059b3cf604SMichael Zolotukhin             TLI->isFunctionVectorizable(Call->getCalledFunction()->getName()))
18069b3cf604SMichael Zolotukhin           continue;
18079b3cf604SMichael Zolotukhin 
18088b401013SDavid Majnemer         auto *Ld = dyn_cast<LoadInst>(&I);
18090456327cSAdam Nemet         if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
1810877ccee8SAdam Nemet           recordAnalysis("NonSimpleLoad", Ld)
1811877ccee8SAdam Nemet               << "read with atomic ordering or volatile read";
1812d34e60caSNicola Zaghen           LLVM_DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
1813436018c3SAdam Nemet           CanVecMem = false;
1814436018c3SAdam Nemet           return;
18150456327cSAdam Nemet         }
18160456327cSAdam Nemet         NumLoads++;
18170456327cSAdam Nemet         Loads.push_back(Ld);
1818ce030acbSXinliang David Li         DepChecker->addAccess(Ld);
1819a9f09c62SAdam Nemet         if (EnableMemAccessVersioning)
1820c953bb99SAdam Nemet           collectStridedAccess(Ld);
18210456327cSAdam Nemet         continue;
18220456327cSAdam Nemet       }
18230456327cSAdam Nemet 
18240456327cSAdam Nemet       // Save 'store' instructions. Abort if other instructions write to memory.
18258b401013SDavid Majnemer       if (I.mayWriteToMemory()) {
18268b401013SDavid Majnemer         auto *St = dyn_cast<StoreInst>(&I);
18270456327cSAdam Nemet         if (!St) {
1828877ccee8SAdam Nemet           recordAnalysis("CantVectorizeInstruction", St)
1829877ccee8SAdam Nemet               << "instruction cannot be vectorized";
1830436018c3SAdam Nemet           CanVecMem = false;
1831436018c3SAdam Nemet           return;
18320456327cSAdam Nemet         }
18330456327cSAdam Nemet         if (!St->isSimple() && !IsAnnotatedParallel) {
1834877ccee8SAdam Nemet           recordAnalysis("NonSimpleStore", St)
1835877ccee8SAdam Nemet               << "write with atomic ordering or volatile write";
1836d34e60caSNicola Zaghen           LLVM_DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
1837436018c3SAdam Nemet           CanVecMem = false;
1838436018c3SAdam Nemet           return;
18390456327cSAdam Nemet         }
18400456327cSAdam Nemet         NumStores++;
18410456327cSAdam Nemet         Stores.push_back(St);
1842ce030acbSXinliang David Li         DepChecker->addAccess(St);
1843a9f09c62SAdam Nemet         if (EnableMemAccessVersioning)
1844c953bb99SAdam Nemet           collectStridedAccess(St);
18450456327cSAdam Nemet       }
18460456327cSAdam Nemet     } // Next instr.
18470456327cSAdam Nemet   } // Next block.
18480456327cSAdam Nemet 
18490456327cSAdam Nemet   // Now we have two lists that hold the loads and the stores.
18500456327cSAdam Nemet   // Next, we find the pointers that they use.
18510456327cSAdam Nemet 
18520456327cSAdam Nemet   // Check if we see any stores. If there are no stores, then we don't
18530456327cSAdam Nemet   // care if the pointers are *restrict*.
18540456327cSAdam Nemet   if (!Stores.size()) {
1855d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
1856436018c3SAdam Nemet     CanVecMem = true;
1857436018c3SAdam Nemet     return;
18580456327cSAdam Nemet   }
18590456327cSAdam Nemet 
1860dee666bcSAdam Nemet   MemoryDepChecker::DepCandidates DependentAccesses;
1861a28d91d8SMehdi Amini   AccessAnalysis Accesses(TheLoop->getHeader()->getModule()->getDataLayout(),
186277eeac3dSManoj Gupta                           TheLoop, AA, LI, DependentAccesses, *PSE);
18630456327cSAdam Nemet 
18640456327cSAdam Nemet   // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
18650456327cSAdam Nemet   // multiple times on the same object. If the ptr is accessed twice, once
18660456327cSAdam Nemet   // for read and once for write, it will only appear once (on the write
18670456327cSAdam Nemet   // list). This is okay, since we are going to check for conflicts between
18680456327cSAdam Nemet   // writes and between reads and writes, but not between reads and reads.
18690456327cSAdam Nemet   ValueSet Seen;
18700456327cSAdam Nemet 
1871b1e3d453SAnna Thomas   // Record uniform store addresses to identify if we have multiple stores
1872b1e3d453SAnna Thomas   // to the same address.
1873b1e3d453SAnna Thomas   ValueSet UniformStores;
1874b1e3d453SAnna Thomas 
1875e3e3b994SMatthew Simpson   for (StoreInst *ST : Stores) {
18760456327cSAdam Nemet     Value *Ptr = ST->getPointerOperand();
1877b1e3d453SAnna Thomas 
18786f732bfbSAnna Thomas     if (isUniform(Ptr))
18795e9215f0SAnna Thomas       HasDependenceInvolvingLoopInvariantAddress |=
18806f732bfbSAnna Thomas           !UniformStores.insert(Ptr).second;
1881b1e3d453SAnna Thomas 
18820456327cSAdam Nemet     // If we did *not* see this pointer before, insert it to  the read-write
18830456327cSAdam Nemet     // list. At this phase it is only a 'write' list.
18840456327cSAdam Nemet     if (Seen.insert(Ptr).second) {
18850456327cSAdam Nemet       ++NumReadWrites;
18860456327cSAdam Nemet 
1887ac80dc75SChandler Carruth       MemoryLocation Loc = MemoryLocation::get(ST);
18880456327cSAdam Nemet       // The TBAA metadata could have a control dependency on the predication
18890456327cSAdam Nemet       // condition, so we cannot rely on it when determining whether or not we
18900456327cSAdam Nemet       // need runtime pointer checks.
189101abb2c3SAdam Nemet       if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
18920456327cSAdam Nemet         Loc.AATags.TBAA = nullptr;
18930456327cSAdam Nemet 
18940456327cSAdam Nemet       Accesses.addStore(Loc);
18950456327cSAdam Nemet     }
18960456327cSAdam Nemet   }
18970456327cSAdam Nemet 
18980456327cSAdam Nemet   if (IsAnnotatedParallel) {
1899d34e60caSNicola Zaghen     LLVM_DEBUG(
1900d34e60caSNicola Zaghen         dbgs() << "LAA: A loop annotated parallel, ignore memory dependency "
19010456327cSAdam Nemet                << "checks.\n");
1902436018c3SAdam Nemet     CanVecMem = true;
1903436018c3SAdam Nemet     return;
19040456327cSAdam Nemet   }
19050456327cSAdam Nemet 
1906e3e3b994SMatthew Simpson   for (LoadInst *LD : Loads) {
19070456327cSAdam Nemet     Value *Ptr = LD->getPointerOperand();
19080456327cSAdam Nemet     // If we did *not* see this pointer before, insert it to the
19090456327cSAdam Nemet     // read list. If we *did* see it before, then it is already in
19100456327cSAdam Nemet     // the read-write list. This allows us to vectorize expressions
19110456327cSAdam Nemet     // such as A[i] += x;  Because the address of A[i] is a read-write
19120456327cSAdam Nemet     // pointer. This only works if the index of A[i] is consecutive.
19130456327cSAdam Nemet     // If the address of i is unknown (for example A[B[i]]) then we may
19140456327cSAdam Nemet     // read a few words, modify, and write a few words, and some of the
19150456327cSAdam Nemet     // words may be written to the same address.
19160456327cSAdam Nemet     bool IsReadOnlyPtr = false;
1917139ffba3SAdam Nemet     if (Seen.insert(Ptr).second ||
191894734eefSXinliang David Li         !getPtrStride(*PSE, Ptr, TheLoop, SymbolicStrides)) {
19190456327cSAdam Nemet       ++NumReads;
19200456327cSAdam Nemet       IsReadOnlyPtr = true;
19210456327cSAdam Nemet     }
19220456327cSAdam Nemet 
19235e9215f0SAnna Thomas     // See if there is an unsafe dependency between a load to a uniform address and
19245e9215f0SAnna Thomas     // store to the same uniform address.
19255e9215f0SAnna Thomas     if (UniformStores.count(Ptr)) {
19265e9215f0SAnna Thomas       LLVM_DEBUG(dbgs() << "LAA: Found an unsafe dependency between a uniform "
19275e9215f0SAnna Thomas                            "load and uniform store to the same address!\n");
19285e9215f0SAnna Thomas       HasDependenceInvolvingLoopInvariantAddress = true;
19295e9215f0SAnna Thomas     }
19305e9215f0SAnna Thomas 
1931ac80dc75SChandler Carruth     MemoryLocation Loc = MemoryLocation::get(LD);
19320456327cSAdam Nemet     // The TBAA metadata could have a control dependency on the predication
19330456327cSAdam Nemet     // condition, so we cannot rely on it when determining whether or not we
19340456327cSAdam Nemet     // need runtime pointer checks.
193501abb2c3SAdam Nemet     if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
19360456327cSAdam Nemet       Loc.AATags.TBAA = nullptr;
19370456327cSAdam Nemet 
19380456327cSAdam Nemet     Accesses.addLoad(Loc, IsReadOnlyPtr);
19390456327cSAdam Nemet   }
19400456327cSAdam Nemet 
19410456327cSAdam Nemet   // If we write (or read-write) to a single destination and there are no
19420456327cSAdam Nemet   // other reads in this loop then is it safe to vectorize.
19430456327cSAdam Nemet   if (NumReadWrites == 1 && NumReads == 0) {
1944d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
1945436018c3SAdam Nemet     CanVecMem = true;
1946436018c3SAdam Nemet     return;
19470456327cSAdam Nemet   }
19480456327cSAdam Nemet 
19490456327cSAdam Nemet   // Build dependence sets and check whether we need a runtime pointer bounds
19500456327cSAdam Nemet   // check.
19510456327cSAdam Nemet   Accesses.buildDependenceSets();
19520456327cSAdam Nemet 
19530456327cSAdam Nemet   // Find pointers with computable bounds. We are going to use this information
19540456327cSAdam Nemet   // to place a runtime bound check.
195594734eefSXinliang David Li   bool CanDoRTIfNeeded = Accesses.canCheckPtrAtRT(*PtrRtChecking, PSE->getSE(),
1956139ffba3SAdam Nemet                                                   TheLoop, SymbolicStrides);
1957ee61474aSAdam Nemet   if (!CanDoRTIfNeeded) {
1958877ccee8SAdam Nemet     recordAnalysis("CantIdentifyArrayBounds") << "cannot identify array bounds";
1959d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LAA: We can't vectorize because we can't find "
1960ee61474aSAdam Nemet                       << "the array bounds.\n");
1961436018c3SAdam Nemet     CanVecMem = false;
1962436018c3SAdam Nemet     return;
19630456327cSAdam Nemet   }
19640456327cSAdam Nemet 
1965d34e60caSNicola Zaghen   LLVM_DEBUG(
1966d34e60caSNicola Zaghen       dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
19670456327cSAdam Nemet 
1968436018c3SAdam Nemet   CanVecMem = true;
19690456327cSAdam Nemet   if (Accesses.isDependencyCheckNeeded()) {
1970d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
1971ce030acbSXinliang David Li     CanVecMem = DepChecker->areDepsSafe(
1972139ffba3SAdam Nemet         DependentAccesses, Accesses.getDependenciesToCheck(), SymbolicStrides);
1973ce030acbSXinliang David Li     MaxSafeDepDistBytes = DepChecker->getMaxSafeDepDistBytes();
19740456327cSAdam Nemet 
1975ce030acbSXinliang David Li     if (!CanVecMem && DepChecker->shouldRetryWithRuntimeCheck()) {
1976d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
19770456327cSAdam Nemet 
19780456327cSAdam Nemet       // Clear the dependency checks. We assume they are not needed.
1979ce030acbSXinliang David Li       Accesses.resetDepChecks(*DepChecker);
19800456327cSAdam Nemet 
1981ce030acbSXinliang David Li       PtrRtChecking->reset();
1982ce030acbSXinliang David Li       PtrRtChecking->Need = true;
19830456327cSAdam Nemet 
198494734eefSXinliang David Li       auto *SE = PSE->getSE();
1985ce030acbSXinliang David Li       CanDoRTIfNeeded = Accesses.canCheckPtrAtRT(*PtrRtChecking, SE, TheLoop,
1986139ffba3SAdam Nemet                                                  SymbolicStrides, true);
198798a13719SSilviu Baranga 
1988949e91a6SAdam Nemet       // Check that we found the bounds for the pointer.
1989ee61474aSAdam Nemet       if (!CanDoRTIfNeeded) {
1990877ccee8SAdam Nemet         recordAnalysis("CantCheckMemDepsAtRunTime")
1991877ccee8SAdam Nemet             << "cannot check memory dependencies at runtime";
1992d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
1993b6dc76ffSAdam Nemet         CanVecMem = false;
1994b6dc76ffSAdam Nemet         return;
1995b6dc76ffSAdam Nemet       }
1996b6dc76ffSAdam Nemet 
19970456327cSAdam Nemet       CanVecMem = true;
19980456327cSAdam Nemet     }
19990456327cSAdam Nemet   }
20000456327cSAdam Nemet 
20014bb90a71SAdam Nemet   if (CanVecMem)
2002d34e60caSNicola Zaghen     LLVM_DEBUG(
2003d34e60caSNicola Zaghen         dbgs() << "LAA: No unsafe dependent memory operations in loop.  We"
2004ce030acbSXinliang David Li                << (PtrRtChecking->Need ? "" : " don't")
20050f67c6c1SAdam Nemet                << " need runtime memory checks.\n");
20064bb90a71SAdam Nemet   else {
2007877ccee8SAdam Nemet     recordAnalysis("UnsafeMemDep")
20080a77dfadSAdam Nemet         << "unsafe dependent memory operations in loop. Use "
20090a77dfadSAdam Nemet            "#pragma loop distribute(enable) to allow loop distribution "
20100a77dfadSAdam Nemet            "to attempt to isolate the offending operations into a separate "
2011877ccee8SAdam Nemet            "loop";
2012d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
20134bb90a71SAdam Nemet   }
20140456327cSAdam Nemet }
20150456327cSAdam Nemet 
201601abb2c3SAdam Nemet bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
201701abb2c3SAdam Nemet                                            DominatorTree *DT)  {
20180456327cSAdam Nemet   assert(TheLoop->contains(BB) && "Unknown block used");
20190456327cSAdam Nemet 
20200456327cSAdam Nemet   // Blocks that do not dominate the latch need predication.
20210456327cSAdam Nemet   BasicBlock* Latch = TheLoop->getLoopLatch();
20220456327cSAdam Nemet   return !DT->dominates(BB, Latch);
20230456327cSAdam Nemet }
20240456327cSAdam Nemet 
2025877ccee8SAdam Nemet OptimizationRemarkAnalysis &LoopAccessInfo::recordAnalysis(StringRef RemarkName,
2026877ccee8SAdam Nemet                                                            Instruction *I) {
2027c922853bSAdam Nemet   assert(!Report && "Multiple reports generated");
2028877ccee8SAdam Nemet 
2029877ccee8SAdam Nemet   Value *CodeRegion = TheLoop->getHeader();
2030877ccee8SAdam Nemet   DebugLoc DL = TheLoop->getStartLoc();
2031877ccee8SAdam Nemet 
2032877ccee8SAdam Nemet   if (I) {
2033877ccee8SAdam Nemet     CodeRegion = I->getParent();
2034877ccee8SAdam Nemet     // If there is no debug location attached to the instruction, revert back to
2035877ccee8SAdam Nemet     // using the loop's.
2036877ccee8SAdam Nemet     if (I->getDebugLoc())
2037877ccee8SAdam Nemet       DL = I->getDebugLoc();
2038877ccee8SAdam Nemet   }
2039877ccee8SAdam Nemet 
2040877ccee8SAdam Nemet   Report = make_unique<OptimizationRemarkAnalysis>(DEBUG_TYPE, RemarkName, DL,
2041877ccee8SAdam Nemet                                                    CodeRegion);
2042877ccee8SAdam Nemet   return *Report;
20430456327cSAdam Nemet }
20440456327cSAdam Nemet 
204557ac766eSAdam Nemet bool LoopAccessInfo::isUniform(Value *V) const {
20463ceac2bbSMichael Kuperstein   auto *SE = PSE->getSE();
20473ceac2bbSMichael Kuperstein   // Since we rely on SCEV for uniformity, if the type is not SCEVable, it is
20483ceac2bbSMichael Kuperstein   // never considered uniform.
20493ceac2bbSMichael Kuperstein   // TODO: Is this really what we want? Even without FP SCEV, we may want some
20503ceac2bbSMichael Kuperstein   // trivially loop-invariant FP values to be considered uniform.
20513ceac2bbSMichael Kuperstein   if (!SE->isSCEVable(V->getType()))
20523ceac2bbSMichael Kuperstein     return false;
20533ceac2bbSMichael Kuperstein   return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
20540456327cSAdam Nemet }
20557206d7a5SAdam Nemet 
20567206d7a5SAdam Nemet // FIXME: this function is currently a duplicate of the one in
20577206d7a5SAdam Nemet // LoopVectorize.cpp.
20587206d7a5SAdam Nemet static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
20597206d7a5SAdam Nemet                                  Instruction *Loc) {
20607206d7a5SAdam Nemet   if (FirstInst)
20617206d7a5SAdam Nemet     return FirstInst;
20627206d7a5SAdam Nemet   if (Instruction *I = dyn_cast<Instruction>(V))
20637206d7a5SAdam Nemet     return I->getParent() == Loc->getParent() ? I : nullptr;
20647206d7a5SAdam Nemet   return nullptr;
20657206d7a5SAdam Nemet }
20667206d7a5SAdam Nemet 
2067039b1042SBenjamin Kramer namespace {
2068a3fe70d2SEugene Zelenko 
20695f8f34e4SAdrian Prantl /// IR Values for the lower and upper bounds of a pointer evolution.  We
20704e533ef7SAdam Nemet /// need to use value-handles because SCEV expansion can invalidate previously
20714e533ef7SAdam Nemet /// expanded values.  Thus expansion of a pointer can invalidate the bounds for
20724e533ef7SAdam Nemet /// a previous one.
20731da7df37SAdam Nemet struct PointerBounds {
20744e533ef7SAdam Nemet   TrackingVH<Value> Start;
20754e533ef7SAdam Nemet   TrackingVH<Value> End;
20761da7df37SAdam Nemet };
2077a3fe70d2SEugene Zelenko 
2078039b1042SBenjamin Kramer } // end anonymous namespace
20797206d7a5SAdam Nemet 
20805f8f34e4SAdrian Prantl /// Expand code for the lower and upper bound of the pointer group \p CG
20811da7df37SAdam Nemet /// in \p TheLoop.  \return the values for the bounds.
20821da7df37SAdam Nemet static PointerBounds
20831da7df37SAdam Nemet expandBounds(const RuntimePointerChecking::CheckingPtrGroup *CG, Loop *TheLoop,
20841da7df37SAdam Nemet              Instruction *Loc, SCEVExpander &Exp, ScalarEvolution *SE,
20851da7df37SAdam Nemet              const RuntimePointerChecking &PtrRtChecking) {
20861da7df37SAdam Nemet   Value *Ptr = PtrRtChecking.Pointers[CG->Members[0]].PointerValue;
20877206d7a5SAdam Nemet   const SCEV *Sc = SE->getSCEV(Ptr);
20887206d7a5SAdam Nemet 
20897206d7a5SAdam Nemet   unsigned AS = Ptr->getType()->getPointerAddressSpace();
20901da7df37SAdam Nemet   LLVMContext &Ctx = Loc->getContext();
20917206d7a5SAdam Nemet 
20927206d7a5SAdam Nemet   // Use this type for pointer arithmetic.
20937206d7a5SAdam Nemet   Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
20947206d7a5SAdam Nemet 
209592f377bdSKeno Fischer   if (SE->isLoopInvariant(Sc, TheLoop)) {
2096d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:"
2097d34e60caSNicola Zaghen                       << *Ptr << "\n");
209892f377bdSKeno Fischer     // Ptr could be in the loop body. If so, expand a new one at the correct
209992f377bdSKeno Fischer     // location.
210092f377bdSKeno Fischer     Instruction *Inst = dyn_cast<Instruction>(Ptr);
210192f377bdSKeno Fischer     Value *NewPtr = (Inst && TheLoop->contains(Inst))
210292f377bdSKeno Fischer                         ? Exp.expandCodeFor(Sc, PtrArithTy, Loc)
210392f377bdSKeno Fischer                         : Ptr;
210437dd4d7aSJames Molloy     // We must return a half-open range, which means incrementing Sc.
210537dd4d7aSJames Molloy     const SCEV *ScPlusOne = SE->getAddExpr(Sc, SE->getOne(PtrArithTy));
210637dd4d7aSJames Molloy     Value *NewPtrPlusOne = Exp.expandCodeFor(ScPlusOne, PtrArithTy, Loc);
210737dd4d7aSJames Molloy     return {NewPtr, NewPtrPlusOne};
210892f377bdSKeno Fischer   } else {
210992f377bdSKeno Fischer     Value *Start = nullptr, *End = nullptr;
2110d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LAA: Adding RT check for range:\n");
21111da7df37SAdam Nemet     Start = Exp.expandCodeFor(CG->Low, PtrArithTy, Loc);
21121da7df37SAdam Nemet     End = Exp.expandCodeFor(CG->High, PtrArithTy, Loc);
2113d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Start: " << *CG->Low << " End: " << *CG->High
2114d34e60caSNicola Zaghen                       << "\n");
21151da7df37SAdam Nemet     return {Start, End};
21167206d7a5SAdam Nemet   }
21177206d7a5SAdam Nemet }
21187206d7a5SAdam Nemet 
21195f8f34e4SAdrian Prantl /// Turns a collection of checks into a collection of expanded upper and
21201da7df37SAdam Nemet /// lower bounds for both pointers in the check.
21211da7df37SAdam Nemet static SmallVector<std::pair<PointerBounds, PointerBounds>, 4> expandBounds(
21221da7df37SAdam Nemet     const SmallVectorImpl<RuntimePointerChecking::PointerCheck> &PointerChecks,
21231da7df37SAdam Nemet     Loop *L, Instruction *Loc, ScalarEvolution *SE, SCEVExpander &Exp,
21241da7df37SAdam Nemet     const RuntimePointerChecking &PtrRtChecking) {
21251da7df37SAdam Nemet   SmallVector<std::pair<PointerBounds, PointerBounds>, 4> ChecksWithBounds;
21261da7df37SAdam Nemet 
21271da7df37SAdam Nemet   // Here we're relying on the SCEV Expander's cache to only emit code for the
21281da7df37SAdam Nemet   // same bounds once.
21292d006e76SDavid Majnemer   transform(
21302d006e76SDavid Majnemer       PointerChecks, std::back_inserter(ChecksWithBounds),
21311da7df37SAdam Nemet       [&](const RuntimePointerChecking::PointerCheck &Check) {
213294abbbd6SNAKAMURA Takumi         PointerBounds
213394abbbd6SNAKAMURA Takumi           First = expandBounds(Check.first, L, Loc, Exp, SE, PtrRtChecking),
213494abbbd6SNAKAMURA Takumi           Second = expandBounds(Check.second, L, Loc, Exp, SE, PtrRtChecking);
213594abbbd6SNAKAMURA Takumi         return std::make_pair(First, Second);
21361da7df37SAdam Nemet       });
21371da7df37SAdam Nemet 
21381da7df37SAdam Nemet   return ChecksWithBounds;
21391da7df37SAdam Nemet }
21401da7df37SAdam Nemet 
21415b0a4795SAdam Nemet std::pair<Instruction *, Instruction *> LoopAccessInfo::addRuntimeChecks(
21421da7df37SAdam Nemet     Instruction *Loc,
21431da7df37SAdam Nemet     const SmallVectorImpl<RuntimePointerChecking::PointerCheck> &PointerChecks)
21441da7df37SAdam Nemet     const {
21451824e411SAdam Nemet   const DataLayout &DL = TheLoop->getHeader()->getModule()->getDataLayout();
214694734eefSXinliang David Li   auto *SE = PSE->getSE();
21471824e411SAdam Nemet   SCEVExpander Exp(*SE, DL, "induction");
21481da7df37SAdam Nemet   auto ExpandedChecks =
2149ce030acbSXinliang David Li       expandBounds(PointerChecks, TheLoop, Loc, SE, Exp, *PtrRtChecking);
21501da7df37SAdam Nemet 
21511da7df37SAdam Nemet   LLVMContext &Ctx = Loc->getContext();
21521da7df37SAdam Nemet   Instruction *FirstInst = nullptr;
21537206d7a5SAdam Nemet   IRBuilder<> ChkBuilder(Loc);
21547206d7a5SAdam Nemet   // Our instructions might fold to a constant.
21557206d7a5SAdam Nemet   Value *MemoryRuntimeCheck = nullptr;
21561b6b50a9SSilviu Baranga 
21571da7df37SAdam Nemet   for (const auto &Check : ExpandedChecks) {
21581da7df37SAdam Nemet     const PointerBounds &A = Check.first, &B = Check.second;
2159cdb791cdSAdam Nemet     // Check if two pointers (A and B) conflict where conflict is computed as:
2160cdb791cdSAdam Nemet     // start(A) <= end(B) && start(B) <= end(A)
21611da7df37SAdam Nemet     unsigned AS0 = A.Start->getType()->getPointerAddressSpace();
21621da7df37SAdam Nemet     unsigned AS1 = B.Start->getType()->getPointerAddressSpace();
21637206d7a5SAdam Nemet 
21641da7df37SAdam Nemet     assert((AS0 == B.End->getType()->getPointerAddressSpace()) &&
21651da7df37SAdam Nemet            (AS1 == A.End->getType()->getPointerAddressSpace()) &&
21667206d7a5SAdam Nemet            "Trying to bounds check pointers with different address spaces");
21677206d7a5SAdam Nemet 
21687206d7a5SAdam Nemet     Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
21697206d7a5SAdam Nemet     Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
21707206d7a5SAdam Nemet 
21711da7df37SAdam Nemet     Value *Start0 = ChkBuilder.CreateBitCast(A.Start, PtrArithTy0, "bc");
21721da7df37SAdam Nemet     Value *Start1 = ChkBuilder.CreateBitCast(B.Start, PtrArithTy1, "bc");
21731da7df37SAdam Nemet     Value *End0 =   ChkBuilder.CreateBitCast(A.End,   PtrArithTy1, "bc");
21741da7df37SAdam Nemet     Value *End1 =   ChkBuilder.CreateBitCast(B.End,   PtrArithTy0, "bc");
21757206d7a5SAdam Nemet 
21763622fbfcSElena Demikhovsky     // [A|B].Start points to the first accessed byte under base [A|B].
21773622fbfcSElena Demikhovsky     // [A|B].End points to the last accessed byte, plus one.
21783622fbfcSElena Demikhovsky     // There is no conflict when the intervals are disjoint:
21793622fbfcSElena Demikhovsky     // NoConflict = (B.Start >= A.End) || (A.Start >= B.End)
21803622fbfcSElena Demikhovsky     //
21813622fbfcSElena Demikhovsky     // bound0 = (B.Start < A.End)
21823622fbfcSElena Demikhovsky     // bound1 = (A.Start < B.End)
21833622fbfcSElena Demikhovsky     //  IsConflict = bound0 & bound1
21843622fbfcSElena Demikhovsky     Value *Cmp0 = ChkBuilder.CreateICmpULT(Start0, End1, "bound0");
21857206d7a5SAdam Nemet     FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
21863622fbfcSElena Demikhovsky     Value *Cmp1 = ChkBuilder.CreateICmpULT(Start1, End0, "bound1");
21877206d7a5SAdam Nemet     FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
21887206d7a5SAdam Nemet     Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
21897206d7a5SAdam Nemet     FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
21907206d7a5SAdam Nemet     if (MemoryRuntimeCheck) {
21911da7df37SAdam Nemet       IsConflict =
21921da7df37SAdam Nemet           ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx");
21937206d7a5SAdam Nemet       FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
21947206d7a5SAdam Nemet     }
21957206d7a5SAdam Nemet     MemoryRuntimeCheck = IsConflict;
21967206d7a5SAdam Nemet   }
21977206d7a5SAdam Nemet 
219890fec840SAdam Nemet   if (!MemoryRuntimeCheck)
219990fec840SAdam Nemet     return std::make_pair(nullptr, nullptr);
220090fec840SAdam Nemet 
22017206d7a5SAdam Nemet   // We have to do this trickery because the IRBuilder might fold the check to a
22027206d7a5SAdam Nemet   // constant expression in which case there is no Instruction anchored in a
22037206d7a5SAdam Nemet   // the block.
22047206d7a5SAdam Nemet   Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
22057206d7a5SAdam Nemet                                                  ConstantInt::getTrue(Ctx));
22067206d7a5SAdam Nemet   ChkBuilder.Insert(Check, "memcheck.conflict");
22077206d7a5SAdam Nemet   FirstInst = getFirstInst(FirstInst, Check, Loc);
22087206d7a5SAdam Nemet   return std::make_pair(FirstInst, Check);
22097206d7a5SAdam Nemet }
22103bfd93d7SAdam Nemet 
22115b0a4795SAdam Nemet std::pair<Instruction *, Instruction *>
22125b0a4795SAdam Nemet LoopAccessInfo::addRuntimeChecks(Instruction *Loc) const {
2213ce030acbSXinliang David Li   if (!PtrRtChecking->Need)
22141da7df37SAdam Nemet     return std::make_pair(nullptr, nullptr);
22151da7df37SAdam Nemet 
2216ce030acbSXinliang David Li   return addRuntimeChecks(Loc, PtrRtChecking->getChecks());
22171da7df37SAdam Nemet }
22181da7df37SAdam Nemet 
2219c953bb99SAdam Nemet void LoopAccessInfo::collectStridedAccess(Value *MemAccess) {
2220c953bb99SAdam Nemet   Value *Ptr = nullptr;
2221c953bb99SAdam Nemet   if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
2222c953bb99SAdam Nemet     Ptr = LI->getPointerOperand();
2223c953bb99SAdam Nemet   else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
2224c953bb99SAdam Nemet     Ptr = SI->getPointerOperand();
2225c953bb99SAdam Nemet   else
2226c953bb99SAdam Nemet     return;
2227c953bb99SAdam Nemet 
222894734eefSXinliang David Li   Value *Stride = getStrideFromPointer(Ptr, PSE->getSE(), TheLoop);
2229c953bb99SAdam Nemet   if (!Stride)
2230c953bb99SAdam Nemet     return;
2231c953bb99SAdam Nemet 
2232d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "LAA: Found a strided access that is a candidate for "
2233eb13dd3eSDorit Nuzman                        "versioning:");
2234d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
2235eb13dd3eSDorit Nuzman 
2236eb13dd3eSDorit Nuzman   // Avoid adding the "Stride == 1" predicate when we know that
2237eb13dd3eSDorit Nuzman   // Stride >= Trip-Count. Such a predicate will effectively optimize a single
2238eb13dd3eSDorit Nuzman   // or zero iteration loop, as Trip-Count <= Stride == 1.
2239eb13dd3eSDorit Nuzman   //
2240eb13dd3eSDorit Nuzman   // TODO: We are currently not making a very informed decision on when it is
2241eb13dd3eSDorit Nuzman   // beneficial to apply stride versioning. It might make more sense that the
2242eb13dd3eSDorit Nuzman   // users of this analysis (such as the vectorizer) will trigger it, based on
2243eb13dd3eSDorit Nuzman   // their specific cost considerations; For example, in cases where stride
2244eb13dd3eSDorit Nuzman   // versioning does  not help resolving memory accesses/dependences, the
2245eb13dd3eSDorit Nuzman   // vectorizer should evaluate the cost of the runtime test, and the benefit
2246eb13dd3eSDorit Nuzman   // of various possible stride specializations, considering the alternatives
2247eb13dd3eSDorit Nuzman   // of using gather/scatters (if available).
2248eb13dd3eSDorit Nuzman 
2249eb13dd3eSDorit Nuzman   const SCEV *StrideExpr = PSE->getSCEV(Stride);
2250eb13dd3eSDorit Nuzman   const SCEV *BETakenCount = PSE->getBackedgeTakenCount();
2251eb13dd3eSDorit Nuzman 
2252eb13dd3eSDorit Nuzman   // Match the types so we can compare the stride and the BETakenCount.
2253eb13dd3eSDorit Nuzman   // The Stride can be positive/negative, so we sign extend Stride;
2254*02a2bb2fSHiroshi Inoue   // The backedgeTakenCount is non-negative, so we zero extend BETakenCount.
2255eb13dd3eSDorit Nuzman   const DataLayout &DL = TheLoop->getHeader()->getModule()->getDataLayout();
2256eb13dd3eSDorit Nuzman   uint64_t StrideTypeSize = DL.getTypeAllocSize(StrideExpr->getType());
2257eb13dd3eSDorit Nuzman   uint64_t BETypeSize = DL.getTypeAllocSize(BETakenCount->getType());
2258eb13dd3eSDorit Nuzman   const SCEV *CastedStride = StrideExpr;
2259eb13dd3eSDorit Nuzman   const SCEV *CastedBECount = BETakenCount;
2260eb13dd3eSDorit Nuzman   ScalarEvolution *SE = PSE->getSE();
2261eb13dd3eSDorit Nuzman   if (BETypeSize >= StrideTypeSize)
2262eb13dd3eSDorit Nuzman     CastedStride = SE->getNoopOrSignExtend(StrideExpr, BETakenCount->getType());
2263eb13dd3eSDorit Nuzman   else
2264eb13dd3eSDorit Nuzman     CastedBECount = SE->getZeroExtendExpr(BETakenCount, StrideExpr->getType());
2265eb13dd3eSDorit Nuzman   const SCEV *StrideMinusBETaken = SE->getMinusSCEV(CastedStride, CastedBECount);
2266eb13dd3eSDorit Nuzman   // Since TripCount == BackEdgeTakenCount + 1, checking:
2267eb13dd3eSDorit Nuzman   // "Stride >= TripCount" is equivalent to checking:
2268eb13dd3eSDorit Nuzman   // Stride - BETakenCount > 0
2269eb13dd3eSDorit Nuzman   if (SE->isKnownPositive(StrideMinusBETaken)) {
2270d34e60caSNicola Zaghen     LLVM_DEBUG(
2271d34e60caSNicola Zaghen         dbgs() << "LAA: Stride>=TripCount; No point in versioning as the "
2272eb13dd3eSDorit Nuzman                   "Stride==1 predicate will imply that the loop executes "
2273eb13dd3eSDorit Nuzman                   "at most once.\n");
2274eb13dd3eSDorit Nuzman     return;
2275eb13dd3eSDorit Nuzman   }
2276d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "LAA: Found a strided access that we can version.");
2277eb13dd3eSDorit Nuzman 
2278c953bb99SAdam Nemet   SymbolicStrides[Ptr] = Stride;
2279c953bb99SAdam Nemet   StrideSet.insert(Stride);
2280c953bb99SAdam Nemet }
2281c953bb99SAdam Nemet 
22823bfd93d7SAdam Nemet LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
22833bfd93d7SAdam Nemet                                const TargetLibraryInfo *TLI, AliasAnalysis *AA,
2284a9f09c62SAdam Nemet                                DominatorTree *DT, LoopInfo *LI)
228594734eefSXinliang David Li     : PSE(llvm::make_unique<PredicatedScalarEvolution>(*SE, *L)),
2286ce030acbSXinliang David Li       PtrRtChecking(llvm::make_unique<RuntimePointerChecking>(SE)),
228794734eefSXinliang David Li       DepChecker(llvm::make_unique<MemoryDepChecker>(*PSE, L)), TheLoop(L),
22887da74abfSAdam Nemet       NumLoads(0), NumStores(0), MaxSafeDepDistBytes(-1), CanVecMem(false),
22895e9215f0SAnna Thomas       HasDependenceInvolvingLoopInvariantAddress(false) {
2290929c38e8SAdam Nemet   if (canAnalyzeLoop())
22917da74abfSAdam Nemet     analyzeLoop(AA, LI, TLI, DT);
22923bfd93d7SAdam Nemet }
22933bfd93d7SAdam Nemet 
2294e91cc6efSAdam Nemet void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
2295e91cc6efSAdam Nemet   if (CanVecMem) {
22964ad38b63SAdam Nemet     OS.indent(Depth) << "Memory dependences are safe";
22977afb46d3SDavid Majnemer     if (MaxSafeDepDistBytes != -1ULL)
2298c62e554eSAdam Nemet       OS << " with a maximum dependence distance of " << MaxSafeDepDistBytes
2299c62e554eSAdam Nemet          << " bytes";
2300ce030acbSXinliang David Li     if (PtrRtChecking->Need)
23014ad38b63SAdam Nemet       OS << " with run-time checks";
23024ad38b63SAdam Nemet     OS << "\n";
2303e91cc6efSAdam Nemet   }
2304e91cc6efSAdam Nemet 
2305e91cc6efSAdam Nemet   if (Report)
2306877ccee8SAdam Nemet     OS.indent(Depth) << "Report: " << Report->getMsg() << "\n";
2307e91cc6efSAdam Nemet 
2308ce030acbSXinliang David Li   if (auto *Dependences = DepChecker->getDependences()) {
2309a2df750fSAdam Nemet     OS.indent(Depth) << "Dependences:\n";
2310a2df750fSAdam Nemet     for (auto &Dep : *Dependences) {
2311ce030acbSXinliang David Li       Dep.print(OS, Depth + 2, DepChecker->getMemoryInstructions());
231258913d65SAdam Nemet       OS << "\n";
231358913d65SAdam Nemet     }
231458913d65SAdam Nemet   } else
2315a2df750fSAdam Nemet     OS.indent(Depth) << "Too many dependences, not recorded\n";
2316e91cc6efSAdam Nemet 
2317e91cc6efSAdam Nemet   // List the pair of accesses need run-time checks to prove independence.
2318ce030acbSXinliang David Li   PtrRtChecking->print(OS, Depth);
2319e91cc6efSAdam Nemet   OS << "\n";
2320c3384320SAdam Nemet 
23215e9215f0SAnna Thomas   OS.indent(Depth) << "Non vectorizable stores to invariant address were "
23225e9215f0SAnna Thomas                    << (HasDependenceInvolvingLoopInvariantAddress ? "" : "not ")
2323c3384320SAdam Nemet                    << "found in loop.\n";
2324e3c0534bSSilviu Baranga 
2325e3c0534bSSilviu Baranga   OS.indent(Depth) << "SCEV assumptions:\n";
232694734eefSXinliang David Li   PSE->getUnionPredicate().print(OS, Depth);
2327b77365b5SSilviu Baranga 
2328b77365b5SSilviu Baranga   OS << "\n";
2329b77365b5SSilviu Baranga 
2330b77365b5SSilviu Baranga   OS.indent(Depth) << "Expressions re-written:\n";
233194734eefSXinliang David Li   PSE->print(OS, Depth);
2332e91cc6efSAdam Nemet }
2333e91cc6efSAdam Nemet 
23347853c1ddSXinliang David Li const LoopAccessInfo &LoopAccessLegacyAnalysis::getInfo(Loop *L) {
23353bfd93d7SAdam Nemet   auto &LAI = LoopAccessInfoMap[L];
23363bfd93d7SAdam Nemet 
23371824e411SAdam Nemet   if (!LAI)
23381824e411SAdam Nemet     LAI = llvm::make_unique<LoopAccessInfo>(L, SE, TLI, AA, DT, LI);
23391824e411SAdam Nemet 
23403bfd93d7SAdam Nemet   return *LAI.get();
23413bfd93d7SAdam Nemet }
23423bfd93d7SAdam Nemet 
23437853c1ddSXinliang David Li void LoopAccessLegacyAnalysis::print(raw_ostream &OS, const Module *M) const {
23447853c1ddSXinliang David Li   LoopAccessLegacyAnalysis &LAA = *const_cast<LoopAccessLegacyAnalysis *>(this);
2345ecde1c7fSXinliang David Li 
2346e91cc6efSAdam Nemet   for (Loop *TopLevelLoop : *LI)
2347e91cc6efSAdam Nemet     for (Loop *L : depth_first(TopLevelLoop)) {
2348e91cc6efSAdam Nemet       OS.indent(2) << L->getHeader()->getName() << ":\n";
2349bdbc5227SAdam Nemet       auto &LAI = LAA.getInfo(L);
2350e91cc6efSAdam Nemet       LAI.print(OS, 4);
2351e91cc6efSAdam Nemet     }
2352e91cc6efSAdam Nemet }
2353e91cc6efSAdam Nemet 
23547853c1ddSXinliang David Li bool LoopAccessLegacyAnalysis::runOnFunction(Function &F) {
2355ecde1c7fSXinliang David Li   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
23563bfd93d7SAdam Nemet   auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2357ecde1c7fSXinliang David Li   TLI = TLIP ? &TLIP->getTLI() : nullptr;
2358ecde1c7fSXinliang David Li   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2359ecde1c7fSXinliang David Li   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2360ecde1c7fSXinliang David Li   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
23613bfd93d7SAdam Nemet 
23623bfd93d7SAdam Nemet   return false;
23633bfd93d7SAdam Nemet }
23643bfd93d7SAdam Nemet 
23657853c1ddSXinliang David Li void LoopAccessLegacyAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
23662f1fd165SChandler Carruth     AU.addRequired<ScalarEvolutionWrapperPass>();
23677b560d40SChandler Carruth     AU.addRequired<AAResultsWrapperPass>();
23683bfd93d7SAdam Nemet     AU.addRequired<DominatorTreeWrapperPass>();
2369e91cc6efSAdam Nemet     AU.addRequired<LoopInfoWrapperPass>();
23703bfd93d7SAdam Nemet 
23713bfd93d7SAdam Nemet     AU.setPreservesAll();
23723bfd93d7SAdam Nemet }
23733bfd93d7SAdam Nemet 
23747853c1ddSXinliang David Li char LoopAccessLegacyAnalysis::ID = 0;
23753bfd93d7SAdam Nemet static const char laa_name[] = "Loop Access Analysis";
23763bfd93d7SAdam Nemet #define LAA_NAME "loop-accesses"
23773bfd93d7SAdam Nemet 
23787853c1ddSXinliang David Li INITIALIZE_PASS_BEGIN(LoopAccessLegacyAnalysis, LAA_NAME, laa_name, false, true)
23797b560d40SChandler Carruth INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
23802f1fd165SChandler Carruth INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
23813bfd93d7SAdam Nemet INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2382e91cc6efSAdam Nemet INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
23837853c1ddSXinliang David Li INITIALIZE_PASS_END(LoopAccessLegacyAnalysis, LAA_NAME, laa_name, false, true)
23843bfd93d7SAdam Nemet 
2385dab4eae2SChandler Carruth AnalysisKey LoopAccessAnalysis::Key;
23868a021317SXinliang David Li 
2387410eaeb0SChandler Carruth LoopAccessInfo LoopAccessAnalysis::run(Loop &L, LoopAnalysisManager &AM,
2388410eaeb0SChandler Carruth                                        LoopStandardAnalysisResults &AR) {
2389410eaeb0SChandler Carruth   return LoopAccessInfo(&L, &AR.SE, &AR.TLI, &AR.AA, &AR.DT, &AR.LI);
23908a021317SXinliang David Li }
23918a021317SXinliang David Li 
23923bfd93d7SAdam Nemet namespace llvm {
2393a3fe70d2SEugene Zelenko 
23943bfd93d7SAdam Nemet   Pass *createLAAPass() {
23957853c1ddSXinliang David Li     return new LoopAccessLegacyAnalysis();
23963bfd93d7SAdam Nemet   }
2397a3fe70d2SEugene Zelenko 
2398a3fe70d2SEugene Zelenko } // end namespace llvm
2399