1*0b57cec5SDimitry Andric //===- LoopAccessAnalysis.cpp - Loop Access Analysis Implementation --------==//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric //
9*0b57cec5SDimitry Andric // The implementation for the loop memory dependence that was originally
10*0b57cec5SDimitry Andric // developed for the loop vectorizer.
11*0b57cec5SDimitry Andric //
12*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
13*0b57cec5SDimitry Andric 
14*0b57cec5SDimitry Andric #include "llvm/Analysis/LoopAccessAnalysis.h"
15*0b57cec5SDimitry Andric #include "llvm/ADT/APInt.h"
16*0b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
17*0b57cec5SDimitry Andric #include "llvm/ADT/DepthFirstIterator.h"
18*0b57cec5SDimitry Andric #include "llvm/ADT/EquivalenceClasses.h"
19*0b57cec5SDimitry Andric #include "llvm/ADT/PointerIntPair.h"
20*0b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
21*0b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h"
22*0b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
23*0b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
24*0b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
25*0b57cec5SDimitry Andric #include "llvm/ADT/iterator_range.h"
26*0b57cec5SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
27*0b57cec5SDimitry Andric #include "llvm/Analysis/AliasSetTracker.h"
28*0b57cec5SDimitry Andric #include "llvm/Analysis/LoopAnalysisManager.h"
29*0b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
30*0b57cec5SDimitry Andric #include "llvm/Analysis/MemoryLocation.h"
31*0b57cec5SDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h"
32*0b57cec5SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
33*0b57cec5SDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpressions.h"
34*0b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
35*0b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
36*0b57cec5SDimitry Andric #include "llvm/Analysis/VectorUtils.h"
37*0b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
38*0b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
39*0b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
40*0b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
41*0b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
42*0b57cec5SDimitry Andric #include "llvm/IR/DiagnosticInfo.h"
43*0b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
44*0b57cec5SDimitry Andric #include "llvm/IR/Function.h"
45*0b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
46*0b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
47*0b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
48*0b57cec5SDimitry Andric #include "llvm/IR/Operator.h"
49*0b57cec5SDimitry Andric #include "llvm/IR/PassManager.h"
5081ad6265SDimitry Andric #include "llvm/IR/PatternMatch.h"
51*0b57cec5SDimitry Andric #include "llvm/IR/Type.h"
52*0b57cec5SDimitry Andric #include "llvm/IR/Value.h"
53*0b57cec5SDimitry Andric #include "llvm/IR/ValueHandle.h"
54480093f4SDimitry Andric #include "llvm/InitializePasses.h"
55*0b57cec5SDimitry Andric #include "llvm/Pass.h"
56*0b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
57*0b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
58*0b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
59*0b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
60*0b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
61*0b57cec5SDimitry Andric #include <algorithm>
62*0b57cec5SDimitry Andric #include <cassert>
63*0b57cec5SDimitry Andric #include <cstdint>
64*0b57cec5SDimitry Andric #include <iterator>
65*0b57cec5SDimitry Andric #include <utility>
66*0b57cec5SDimitry Andric #include <vector>
67*0b57cec5SDimitry Andric 
68*0b57cec5SDimitry Andric using namespace llvm;
6981ad6265SDimitry Andric using namespace llvm::PatternMatch;
70*0b57cec5SDimitry Andric 
71*0b57cec5SDimitry Andric #define DEBUG_TYPE "loop-accesses"
72*0b57cec5SDimitry Andric 
73*0b57cec5SDimitry Andric static cl::opt<unsigned, true>
74*0b57cec5SDimitry Andric VectorizationFactor("force-vector-width", cl::Hidden,
75*0b57cec5SDimitry Andric                     cl::desc("Sets the SIMD width. Zero is autoselect."),
76*0b57cec5SDimitry Andric                     cl::location(VectorizerParams::VectorizationFactor));
77*0b57cec5SDimitry Andric unsigned VectorizerParams::VectorizationFactor;
78*0b57cec5SDimitry Andric 
79*0b57cec5SDimitry Andric static cl::opt<unsigned, true>
80*0b57cec5SDimitry Andric VectorizationInterleave("force-vector-interleave", cl::Hidden,
81*0b57cec5SDimitry Andric                         cl::desc("Sets the vectorization interleave count. "
82*0b57cec5SDimitry Andric                                  "Zero is autoselect."),
83*0b57cec5SDimitry Andric                         cl::location(
84*0b57cec5SDimitry Andric                             VectorizerParams::VectorizationInterleave));
85*0b57cec5SDimitry Andric unsigned VectorizerParams::VectorizationInterleave;
86*0b57cec5SDimitry Andric 
87*0b57cec5SDimitry Andric static cl::opt<unsigned, true> RuntimeMemoryCheckThreshold(
88*0b57cec5SDimitry Andric     "runtime-memory-check-threshold", cl::Hidden,
89*0b57cec5SDimitry Andric     cl::desc("When performing memory disambiguation checks at runtime do not "
90*0b57cec5SDimitry Andric              "generate more than this number of comparisons (default = 8)."),
91*0b57cec5SDimitry Andric     cl::location(VectorizerParams::RuntimeMemoryCheckThreshold), cl::init(8));
92*0b57cec5SDimitry Andric unsigned VectorizerParams::RuntimeMemoryCheckThreshold;
93*0b57cec5SDimitry Andric 
94*0b57cec5SDimitry Andric /// The maximum iterations used to merge memory checks
95*0b57cec5SDimitry Andric static cl::opt<unsigned> MemoryCheckMergeThreshold(
96*0b57cec5SDimitry Andric     "memory-check-merge-threshold", cl::Hidden,
97*0b57cec5SDimitry Andric     cl::desc("Maximum number of comparisons done when trying to merge "
98*0b57cec5SDimitry Andric              "runtime memory checks. (default = 100)"),
99*0b57cec5SDimitry Andric     cl::init(100));
100*0b57cec5SDimitry Andric 
101*0b57cec5SDimitry Andric /// Maximum SIMD width.
102*0b57cec5SDimitry Andric const unsigned VectorizerParams::MaxVectorWidth = 64;
103*0b57cec5SDimitry Andric 
104*0b57cec5SDimitry Andric /// We collect dependences up to this threshold.
105*0b57cec5SDimitry Andric static cl::opt<unsigned>
106*0b57cec5SDimitry Andric     MaxDependences("max-dependences", cl::Hidden,
107*0b57cec5SDimitry Andric                    cl::desc("Maximum number of dependences collected by "
108*0b57cec5SDimitry Andric                             "loop-access analysis (default = 100)"),
109*0b57cec5SDimitry Andric                    cl::init(100));
110*0b57cec5SDimitry Andric 
111*0b57cec5SDimitry Andric /// This enables versioning on the strides of symbolically striding memory
112*0b57cec5SDimitry Andric /// accesses in code like the following.
113*0b57cec5SDimitry Andric ///   for (i = 0; i < N; ++i)
114*0b57cec5SDimitry Andric ///     A[i * Stride1] += B[i * Stride2] ...
115*0b57cec5SDimitry Andric ///
116*0b57cec5SDimitry Andric /// Will be roughly translated to
117*0b57cec5SDimitry Andric ///    if (Stride1 == 1 && Stride2 == 1) {
118*0b57cec5SDimitry Andric ///      for (i = 0; i < N; i+=4)
119*0b57cec5SDimitry Andric ///       A[i:i+3] += ...
120*0b57cec5SDimitry Andric ///    } else
121*0b57cec5SDimitry Andric ///      ...
122*0b57cec5SDimitry Andric static cl::opt<bool> EnableMemAccessVersioning(
123*0b57cec5SDimitry Andric     "enable-mem-access-versioning", cl::init(true), cl::Hidden,
124*0b57cec5SDimitry Andric     cl::desc("Enable symbolic stride memory access versioning"));
125*0b57cec5SDimitry Andric 
126*0b57cec5SDimitry Andric /// Enable store-to-load forwarding conflict detection. This option can
127*0b57cec5SDimitry Andric /// be disabled for correctness testing.
128*0b57cec5SDimitry Andric static cl::opt<bool> EnableForwardingConflictDetection(
129*0b57cec5SDimitry Andric     "store-to-load-forwarding-conflict-detection", cl::Hidden,
130*0b57cec5SDimitry Andric     cl::desc("Enable conflict detection in loop-access analysis"),
131*0b57cec5SDimitry Andric     cl::init(true));
132*0b57cec5SDimitry Andric 
133fcaf7f86SDimitry Andric static cl::opt<unsigned> MaxForkedSCEVDepth(
134fcaf7f86SDimitry Andric     "max-forked-scev-depth", cl::Hidden,
135fcaf7f86SDimitry Andric     cl::desc("Maximum recursion depth when finding forked SCEVs (default = 5)"),
136fcaf7f86SDimitry Andric     cl::init(5));
137fcaf7f86SDimitry Andric 
138*0b57cec5SDimitry Andric bool VectorizerParams::isInterleaveForced() {
139*0b57cec5SDimitry Andric   return ::VectorizationInterleave.getNumOccurrences() > 0;
140*0b57cec5SDimitry Andric }
141*0b57cec5SDimitry Andric 
142*0b57cec5SDimitry Andric Value *llvm::stripIntegerCast(Value *V) {
143*0b57cec5SDimitry Andric   if (auto *CI = dyn_cast<CastInst>(V))
144*0b57cec5SDimitry Andric     if (CI->getOperand(0)->getType()->isIntegerTy())
145*0b57cec5SDimitry Andric       return CI->getOperand(0);
146*0b57cec5SDimitry Andric   return V;
147*0b57cec5SDimitry Andric }
148*0b57cec5SDimitry Andric 
149*0b57cec5SDimitry Andric const SCEV *llvm::replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE,
150*0b57cec5SDimitry Andric                                             const ValueToValueMap &PtrToStride,
151349cc55cSDimitry Andric                                             Value *Ptr) {
152*0b57cec5SDimitry Andric   const SCEV *OrigSCEV = PSE.getSCEV(Ptr);
153*0b57cec5SDimitry Andric 
154*0b57cec5SDimitry Andric   // If there is an entry in the map return the SCEV of the pointer with the
155*0b57cec5SDimitry Andric   // symbolic stride replaced by one.
156349cc55cSDimitry Andric   ValueToValueMap::const_iterator SI = PtrToStride.find(Ptr);
157e8d8bef9SDimitry Andric   if (SI == PtrToStride.end())
158e8d8bef9SDimitry Andric     // For a non-symbolic stride, just return the original expression.
159e8d8bef9SDimitry Andric     return OrigSCEV;
160*0b57cec5SDimitry Andric 
161e8d8bef9SDimitry Andric   Value *StrideVal = stripIntegerCast(SI->second);
162*0b57cec5SDimitry Andric 
163*0b57cec5SDimitry Andric   ScalarEvolution *SE = PSE.getSE();
164*0b57cec5SDimitry Andric   const auto *U = cast<SCEVUnknown>(SE->getSCEV(StrideVal));
165*0b57cec5SDimitry Andric   const auto *CT =
166*0b57cec5SDimitry Andric     static_cast<const SCEVConstant *>(SE->getOne(StrideVal->getType()));
167*0b57cec5SDimitry Andric 
168*0b57cec5SDimitry Andric   PSE.addPredicate(*SE->getEqualPredicate(U, CT));
169*0b57cec5SDimitry Andric   auto *Expr = PSE.getSCEV(Ptr);
170*0b57cec5SDimitry Andric 
171*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV
172*0b57cec5SDimitry Andric 	     << " by: " << *Expr << "\n");
173*0b57cec5SDimitry Andric   return Expr;
174*0b57cec5SDimitry Andric }
175*0b57cec5SDimitry Andric 
1765ffd83dbSDimitry Andric RuntimeCheckingPtrGroup::RuntimeCheckingPtrGroup(
1775ffd83dbSDimitry Andric     unsigned Index, RuntimePointerChecking &RtCheck)
178fe6060f1SDimitry Andric     : High(RtCheck.Pointers[Index].End), Low(RtCheck.Pointers[Index].Start),
179fe6060f1SDimitry Andric       AddressSpace(RtCheck.Pointers[Index]
180fe6060f1SDimitry Andric                        .PointerValue->getType()
18181ad6265SDimitry Andric                        ->getPointerAddressSpace()),
18281ad6265SDimitry Andric       NeedsFreeze(RtCheck.Pointers[Index].NeedsFreeze) {
1835ffd83dbSDimitry Andric   Members.push_back(Index);
1845ffd83dbSDimitry Andric }
1855ffd83dbSDimitry Andric 
186*0b57cec5SDimitry Andric /// Calculate Start and End points of memory access.
187*0b57cec5SDimitry Andric /// Let's assume A is the first access and B is a memory access on N-th loop
188*0b57cec5SDimitry Andric /// iteration. Then B is calculated as:
189*0b57cec5SDimitry Andric ///   B = A + Step*N .
190*0b57cec5SDimitry Andric /// Step value may be positive or negative.
191*0b57cec5SDimitry Andric /// N is a calculated back-edge taken count:
192*0b57cec5SDimitry Andric ///     N = (TripCount > 0) ? RoundDown(TripCount -1 , VF) : 0
193*0b57cec5SDimitry Andric /// Start and End points are calculated in the following way:
194*0b57cec5SDimitry Andric /// Start = UMIN(A, B) ; End = UMAX(A, B) + SizeOfElt,
195*0b57cec5SDimitry Andric /// where SizeOfElt is the size of single memory access in bytes.
196*0b57cec5SDimitry Andric ///
197*0b57cec5SDimitry Andric /// There is no conflict when the intervals are disjoint:
198*0b57cec5SDimitry Andric /// NoConflict = (P2.Start >= P1.End) || (P1.Start >= P2.End)
19981ad6265SDimitry Andric void RuntimePointerChecking::insert(Loop *Lp, Value *Ptr, const SCEV *PtrExpr,
20081ad6265SDimitry Andric                                     Type *AccessTy, bool WritePtr,
201*0b57cec5SDimitry Andric                                     unsigned DepSetId, unsigned ASId,
20281ad6265SDimitry Andric                                     PredicatedScalarEvolution &PSE,
20381ad6265SDimitry Andric                                     bool NeedsFreeze) {
204*0b57cec5SDimitry Andric   ScalarEvolution *SE = PSE.getSE();
205*0b57cec5SDimitry Andric 
206*0b57cec5SDimitry Andric   const SCEV *ScStart;
207*0b57cec5SDimitry Andric   const SCEV *ScEnd;
208*0b57cec5SDimitry Andric 
20981ad6265SDimitry Andric   if (SE->isLoopInvariant(PtrExpr, Lp)) {
21081ad6265SDimitry Andric     ScStart = ScEnd = PtrExpr;
211fe6060f1SDimitry Andric   } else {
21281ad6265SDimitry Andric     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrExpr);
213*0b57cec5SDimitry Andric     assert(AR && "Invalid addrec expression");
214*0b57cec5SDimitry Andric     const SCEV *Ex = PSE.getBackedgeTakenCount();
215*0b57cec5SDimitry Andric 
216*0b57cec5SDimitry Andric     ScStart = AR->getStart();
217*0b57cec5SDimitry Andric     ScEnd = AR->evaluateAtIteration(Ex, *SE);
218*0b57cec5SDimitry Andric     const SCEV *Step = AR->getStepRecurrence(*SE);
219*0b57cec5SDimitry Andric 
220*0b57cec5SDimitry Andric     // For expressions with negative step, the upper bound is ScStart and the
221*0b57cec5SDimitry Andric     // lower bound is ScEnd.
222*0b57cec5SDimitry Andric     if (const auto *CStep = dyn_cast<SCEVConstant>(Step)) {
223*0b57cec5SDimitry Andric       if (CStep->getValue()->isNegative())
224*0b57cec5SDimitry Andric         std::swap(ScStart, ScEnd);
225*0b57cec5SDimitry Andric     } else {
226*0b57cec5SDimitry Andric       // Fallback case: the step is not constant, but we can still
227*0b57cec5SDimitry Andric       // get the upper and lower bounds of the interval by using min/max
228*0b57cec5SDimitry Andric       // expressions.
229*0b57cec5SDimitry Andric       ScStart = SE->getUMinExpr(ScStart, ScEnd);
230*0b57cec5SDimitry Andric       ScEnd = SE->getUMaxExpr(AR->getStart(), ScEnd);
231*0b57cec5SDimitry Andric     }
232fe6060f1SDimitry Andric   }
233*0b57cec5SDimitry Andric   // Add the size of the pointed element to ScEnd.
234e8d8bef9SDimitry Andric   auto &DL = Lp->getHeader()->getModule()->getDataLayout();
235e8d8bef9SDimitry Andric   Type *IdxTy = DL.getIndexType(Ptr->getType());
23681ad6265SDimitry Andric   const SCEV *EltSizeSCEV = SE->getStoreSizeOfExpr(IdxTy, AccessTy);
237*0b57cec5SDimitry Andric   ScEnd = SE->getAddExpr(ScEnd, EltSizeSCEV);
238*0b57cec5SDimitry Andric 
23981ad6265SDimitry Andric   Pointers.emplace_back(Ptr, ScStart, ScEnd, WritePtr, DepSetId, ASId, PtrExpr,
24081ad6265SDimitry Andric                         NeedsFreeze);
241*0b57cec5SDimitry Andric }
242*0b57cec5SDimitry Andric 
24381ad6265SDimitry Andric void RuntimePointerChecking::tryToCreateDiffCheck(
24481ad6265SDimitry Andric     const RuntimeCheckingPtrGroup &CGI, const RuntimeCheckingPtrGroup &CGJ) {
24581ad6265SDimitry Andric   if (!CanUseDiffCheck)
24681ad6265SDimitry Andric     return;
24781ad6265SDimitry Andric 
24881ad6265SDimitry Andric   // If either group contains multiple different pointers, bail out.
24981ad6265SDimitry Andric   // TODO: Support multiple pointers by using the minimum or maximum pointer,
25081ad6265SDimitry Andric   // depending on src & sink.
25181ad6265SDimitry Andric   if (CGI.Members.size() != 1 || CGJ.Members.size() != 1) {
25281ad6265SDimitry Andric     CanUseDiffCheck = false;
25381ad6265SDimitry Andric     return;
25481ad6265SDimitry Andric   }
25581ad6265SDimitry Andric 
25681ad6265SDimitry Andric   PointerInfo *Src = &Pointers[CGI.Members[0]];
25781ad6265SDimitry Andric   PointerInfo *Sink = &Pointers[CGJ.Members[0]];
25881ad6265SDimitry Andric 
25981ad6265SDimitry Andric   // If either pointer is read and written, multiple checks may be needed. Bail
26081ad6265SDimitry Andric   // out.
26181ad6265SDimitry Andric   if (!DC.getOrderForAccess(Src->PointerValue, !Src->IsWritePtr).empty() ||
26281ad6265SDimitry Andric       !DC.getOrderForAccess(Sink->PointerValue, !Sink->IsWritePtr).empty()) {
26381ad6265SDimitry Andric     CanUseDiffCheck = false;
26481ad6265SDimitry Andric     return;
26581ad6265SDimitry Andric   }
26681ad6265SDimitry Andric 
26781ad6265SDimitry Andric   ArrayRef<unsigned> AccSrc =
26881ad6265SDimitry Andric       DC.getOrderForAccess(Src->PointerValue, Src->IsWritePtr);
26981ad6265SDimitry Andric   ArrayRef<unsigned> AccSink =
27081ad6265SDimitry Andric       DC.getOrderForAccess(Sink->PointerValue, Sink->IsWritePtr);
27181ad6265SDimitry Andric   // If either pointer is accessed multiple times, there may not be a clear
27281ad6265SDimitry Andric   // src/sink relation. Bail out for now.
27381ad6265SDimitry Andric   if (AccSrc.size() != 1 || AccSink.size() != 1) {
27481ad6265SDimitry Andric     CanUseDiffCheck = false;
27581ad6265SDimitry Andric     return;
27681ad6265SDimitry Andric   }
27781ad6265SDimitry Andric   // If the sink is accessed before src, swap src/sink.
27881ad6265SDimitry Andric   if (AccSink[0] < AccSrc[0])
27981ad6265SDimitry Andric     std::swap(Src, Sink);
28081ad6265SDimitry Andric 
28181ad6265SDimitry Andric   auto *SrcAR = dyn_cast<SCEVAddRecExpr>(Src->Expr);
28281ad6265SDimitry Andric   auto *SinkAR = dyn_cast<SCEVAddRecExpr>(Sink->Expr);
283a4a491e2SDimitry Andric   if (!SrcAR || !SinkAR || SrcAR->getLoop() != DC.getInnermostLoop() ||
284a4a491e2SDimitry Andric       SinkAR->getLoop() != DC.getInnermostLoop()) {
28581ad6265SDimitry Andric     CanUseDiffCheck = false;
28681ad6265SDimitry Andric     return;
28781ad6265SDimitry Andric   }
28881ad6265SDimitry Andric 
28981ad6265SDimitry Andric   const DataLayout &DL =
29081ad6265SDimitry Andric       SinkAR->getLoop()->getHeader()->getModule()->getDataLayout();
29181ad6265SDimitry Andric   SmallVector<Instruction *, 4> SrcInsts =
29281ad6265SDimitry Andric       DC.getInstructionsForAccess(Src->PointerValue, Src->IsWritePtr);
29381ad6265SDimitry Andric   SmallVector<Instruction *, 4> SinkInsts =
29481ad6265SDimitry Andric       DC.getInstructionsForAccess(Sink->PointerValue, Sink->IsWritePtr);
29581ad6265SDimitry Andric   Type *SrcTy = getLoadStoreType(SrcInsts[0]);
29681ad6265SDimitry Andric   Type *DstTy = getLoadStoreType(SinkInsts[0]);
297fcaf7f86SDimitry Andric   if (isa<ScalableVectorType>(SrcTy) || isa<ScalableVectorType>(DstTy)) {
298fcaf7f86SDimitry Andric     CanUseDiffCheck = false;
29981ad6265SDimitry Andric     return;
300fcaf7f86SDimitry Andric   }
30181ad6265SDimitry Andric   unsigned AllocSize =
30281ad6265SDimitry Andric       std::max(DL.getTypeAllocSize(SrcTy), DL.getTypeAllocSize(DstTy));
30381ad6265SDimitry Andric   IntegerType *IntTy =
30481ad6265SDimitry Andric       IntegerType::get(Src->PointerValue->getContext(),
30581ad6265SDimitry Andric                        DL.getPointerSizeInBits(CGI.AddressSpace));
30681ad6265SDimitry Andric 
30781ad6265SDimitry Andric   // Only matching constant steps matching the AllocSize are supported at the
30881ad6265SDimitry Andric   // moment. This simplifies the difference computation. Can be extended in the
30981ad6265SDimitry Andric   // future.
31081ad6265SDimitry Andric   auto *Step = dyn_cast<SCEVConstant>(SinkAR->getStepRecurrence(*SE));
31181ad6265SDimitry Andric   if (!Step || Step != SrcAR->getStepRecurrence(*SE) ||
31281ad6265SDimitry Andric       Step->getAPInt().abs() != AllocSize) {
31381ad6265SDimitry Andric     CanUseDiffCheck = false;
31481ad6265SDimitry Andric     return;
31581ad6265SDimitry Andric   }
31681ad6265SDimitry Andric 
31781ad6265SDimitry Andric   // When counting down, the dependence distance needs to be swapped.
31881ad6265SDimitry Andric   if (Step->getValue()->isNegative())
31981ad6265SDimitry Andric     std::swap(SinkAR, SrcAR);
32081ad6265SDimitry Andric 
32181ad6265SDimitry Andric   const SCEV *SinkStartInt = SE->getPtrToIntExpr(SinkAR->getStart(), IntTy);
32281ad6265SDimitry Andric   const SCEV *SrcStartInt = SE->getPtrToIntExpr(SrcAR->getStart(), IntTy);
32381ad6265SDimitry Andric   if (isa<SCEVCouldNotCompute>(SinkStartInt) ||
32481ad6265SDimitry Andric       isa<SCEVCouldNotCompute>(SrcStartInt)) {
32581ad6265SDimitry Andric     CanUseDiffCheck = false;
32681ad6265SDimitry Andric     return;
32781ad6265SDimitry Andric   }
32881ad6265SDimitry Andric   DiffChecks.emplace_back(SrcStartInt, SinkStartInt, AllocSize,
32981ad6265SDimitry Andric                           Src->NeedsFreeze || Sink->NeedsFreeze);
33081ad6265SDimitry Andric }
33181ad6265SDimitry Andric 
33281ad6265SDimitry Andric SmallVector<RuntimePointerCheck, 4> RuntimePointerChecking::generateChecks() {
3335ffd83dbSDimitry Andric   SmallVector<RuntimePointerCheck, 4> Checks;
334*0b57cec5SDimitry Andric 
335*0b57cec5SDimitry Andric   for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
336*0b57cec5SDimitry Andric     for (unsigned J = I + 1; J < CheckingGroups.size(); ++J) {
3375ffd83dbSDimitry Andric       const RuntimeCheckingPtrGroup &CGI = CheckingGroups[I];
3385ffd83dbSDimitry Andric       const RuntimeCheckingPtrGroup &CGJ = CheckingGroups[J];
339*0b57cec5SDimitry Andric 
34081ad6265SDimitry Andric       if (needsChecking(CGI, CGJ)) {
34181ad6265SDimitry Andric         tryToCreateDiffCheck(CGI, CGJ);
342*0b57cec5SDimitry Andric         Checks.push_back(std::make_pair(&CGI, &CGJ));
343*0b57cec5SDimitry Andric       }
344*0b57cec5SDimitry Andric     }
34581ad6265SDimitry Andric   }
346*0b57cec5SDimitry Andric   return Checks;
347*0b57cec5SDimitry Andric }
348*0b57cec5SDimitry Andric 
349*0b57cec5SDimitry Andric void RuntimePointerChecking::generateChecks(
350*0b57cec5SDimitry Andric     MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
351*0b57cec5SDimitry Andric   assert(Checks.empty() && "Checks is not empty");
352*0b57cec5SDimitry Andric   groupChecks(DepCands, UseDependencies);
353*0b57cec5SDimitry Andric   Checks = generateChecks();
354*0b57cec5SDimitry Andric }
355*0b57cec5SDimitry Andric 
3565ffd83dbSDimitry Andric bool RuntimePointerChecking::needsChecking(
3575ffd83dbSDimitry Andric     const RuntimeCheckingPtrGroup &M, const RuntimeCheckingPtrGroup &N) const {
358*0b57cec5SDimitry Andric   for (unsigned I = 0, EI = M.Members.size(); EI != I; ++I)
359*0b57cec5SDimitry Andric     for (unsigned J = 0, EJ = N.Members.size(); EJ != J; ++J)
360*0b57cec5SDimitry Andric       if (needsChecking(M.Members[I], N.Members[J]))
361*0b57cec5SDimitry Andric         return true;
362*0b57cec5SDimitry Andric   return false;
363*0b57cec5SDimitry Andric }
364*0b57cec5SDimitry Andric 
365*0b57cec5SDimitry Andric /// Compare \p I and \p J and return the minimum.
366*0b57cec5SDimitry Andric /// Return nullptr in case we couldn't find an answer.
367*0b57cec5SDimitry Andric static const SCEV *getMinFromExprs(const SCEV *I, const SCEV *J,
368*0b57cec5SDimitry Andric                                    ScalarEvolution *SE) {
369*0b57cec5SDimitry Andric   const SCEV *Diff = SE->getMinusSCEV(J, I);
370*0b57cec5SDimitry Andric   const SCEVConstant *C = dyn_cast<const SCEVConstant>(Diff);
371*0b57cec5SDimitry Andric 
372*0b57cec5SDimitry Andric   if (!C)
373*0b57cec5SDimitry Andric     return nullptr;
374*0b57cec5SDimitry Andric   if (C->getValue()->isNegative())
375*0b57cec5SDimitry Andric     return J;
376*0b57cec5SDimitry Andric   return I;
377*0b57cec5SDimitry Andric }
378*0b57cec5SDimitry Andric 
379fe6060f1SDimitry Andric bool RuntimeCheckingPtrGroup::addPointer(unsigned Index,
380fe6060f1SDimitry Andric                                          RuntimePointerChecking &RtCheck) {
381fe6060f1SDimitry Andric   return addPointer(
382fe6060f1SDimitry Andric       Index, RtCheck.Pointers[Index].Start, RtCheck.Pointers[Index].End,
383fe6060f1SDimitry Andric       RtCheck.Pointers[Index].PointerValue->getType()->getPointerAddressSpace(),
38481ad6265SDimitry Andric       RtCheck.Pointers[Index].NeedsFreeze, *RtCheck.SE);
385fe6060f1SDimitry Andric }
386fe6060f1SDimitry Andric 
387fe6060f1SDimitry Andric bool RuntimeCheckingPtrGroup::addPointer(unsigned Index, const SCEV *Start,
388fe6060f1SDimitry Andric                                          const SCEV *End, unsigned AS,
38981ad6265SDimitry Andric                                          bool NeedsFreeze,
390fe6060f1SDimitry Andric                                          ScalarEvolution &SE) {
391fe6060f1SDimitry Andric   assert(AddressSpace == AS &&
392fe6060f1SDimitry Andric          "all pointers in a checking group must be in the same address space");
393*0b57cec5SDimitry Andric 
394*0b57cec5SDimitry Andric   // Compare the starts and ends with the known minimum and maximum
395*0b57cec5SDimitry Andric   // of this set. We need to know how we compare against the min/max
396*0b57cec5SDimitry Andric   // of the set in order to be able to emit memchecks.
397fe6060f1SDimitry Andric   const SCEV *Min0 = getMinFromExprs(Start, Low, &SE);
398*0b57cec5SDimitry Andric   if (!Min0)
399*0b57cec5SDimitry Andric     return false;
400*0b57cec5SDimitry Andric 
401fe6060f1SDimitry Andric   const SCEV *Min1 = getMinFromExprs(End, High, &SE);
402*0b57cec5SDimitry Andric   if (!Min1)
403*0b57cec5SDimitry Andric     return false;
404*0b57cec5SDimitry Andric 
405*0b57cec5SDimitry Andric   // Update the low bound  expression if we've found a new min value.
406*0b57cec5SDimitry Andric   if (Min0 == Start)
407*0b57cec5SDimitry Andric     Low = Start;
408*0b57cec5SDimitry Andric 
409*0b57cec5SDimitry Andric   // Update the high bound expression if we've found a new max value.
410*0b57cec5SDimitry Andric   if (Min1 != End)
411*0b57cec5SDimitry Andric     High = End;
412*0b57cec5SDimitry Andric 
413*0b57cec5SDimitry Andric   Members.push_back(Index);
41481ad6265SDimitry Andric   this->NeedsFreeze |= NeedsFreeze;
415*0b57cec5SDimitry Andric   return true;
416*0b57cec5SDimitry Andric }
417*0b57cec5SDimitry Andric 
418*0b57cec5SDimitry Andric void RuntimePointerChecking::groupChecks(
419*0b57cec5SDimitry Andric     MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
420*0b57cec5SDimitry Andric   // We build the groups from dependency candidates equivalence classes
421*0b57cec5SDimitry Andric   // because:
422*0b57cec5SDimitry Andric   //    - We know that pointers in the same equivalence class share
423*0b57cec5SDimitry Andric   //      the same underlying object and therefore there is a chance
424*0b57cec5SDimitry Andric   //      that we can compare pointers
425*0b57cec5SDimitry Andric   //    - We wouldn't be able to merge two pointers for which we need
426*0b57cec5SDimitry Andric   //      to emit a memcheck. The classes in DepCands are already
427*0b57cec5SDimitry Andric   //      conveniently built such that no two pointers in the same
428*0b57cec5SDimitry Andric   //      class need checking against each other.
429*0b57cec5SDimitry Andric 
430*0b57cec5SDimitry Andric   // We use the following (greedy) algorithm to construct the groups
431*0b57cec5SDimitry Andric   // For every pointer in the equivalence class:
432*0b57cec5SDimitry Andric   //   For each existing group:
433*0b57cec5SDimitry Andric   //   - if the difference between this pointer and the min/max bounds
434*0b57cec5SDimitry Andric   //     of the group is a constant, then make the pointer part of the
435*0b57cec5SDimitry Andric   //     group and update the min/max bounds of that group as required.
436*0b57cec5SDimitry Andric 
437*0b57cec5SDimitry Andric   CheckingGroups.clear();
438*0b57cec5SDimitry Andric 
439*0b57cec5SDimitry Andric   // If we need to check two pointers to the same underlying object
440*0b57cec5SDimitry Andric   // with a non-constant difference, we shouldn't perform any pointer
441*0b57cec5SDimitry Andric   // grouping with those pointers. This is because we can easily get
442*0b57cec5SDimitry Andric   // into cases where the resulting check would return false, even when
443*0b57cec5SDimitry Andric   // the accesses are safe.
444*0b57cec5SDimitry Andric   //
445*0b57cec5SDimitry Andric   // The following example shows this:
446*0b57cec5SDimitry Andric   // for (i = 0; i < 1000; ++i)
447*0b57cec5SDimitry Andric   //   a[5000 + i * m] = a[i] + a[i + 9000]
448*0b57cec5SDimitry Andric   //
449*0b57cec5SDimitry Andric   // Here grouping gives a check of (5000, 5000 + 1000 * m) against
450*0b57cec5SDimitry Andric   // (0, 10000) which is always false. However, if m is 1, there is no
451*0b57cec5SDimitry Andric   // dependence. Not grouping the checks for a[i] and a[i + 9000] allows
452*0b57cec5SDimitry Andric   // us to perform an accurate check in this case.
453*0b57cec5SDimitry Andric   //
454*0b57cec5SDimitry Andric   // The above case requires that we have an UnknownDependence between
455*0b57cec5SDimitry Andric   // accesses to the same underlying object. This cannot happen unless
456*0b57cec5SDimitry Andric   // FoundNonConstantDistanceDependence is set, and therefore UseDependencies
457*0b57cec5SDimitry Andric   // is also false. In this case we will use the fallback path and create
458*0b57cec5SDimitry Andric   // separate checking groups for all pointers.
459*0b57cec5SDimitry Andric 
460*0b57cec5SDimitry Andric   // If we don't have the dependency partitions, construct a new
461*0b57cec5SDimitry Andric   // checking pointer group for each pointer. This is also required
462*0b57cec5SDimitry Andric   // for correctness, because in this case we can have checking between
463*0b57cec5SDimitry Andric   // pointers to the same underlying object.
464*0b57cec5SDimitry Andric   if (!UseDependencies) {
465*0b57cec5SDimitry Andric     for (unsigned I = 0; I < Pointers.size(); ++I)
4665ffd83dbSDimitry Andric       CheckingGroups.push_back(RuntimeCheckingPtrGroup(I, *this));
467*0b57cec5SDimitry Andric     return;
468*0b57cec5SDimitry Andric   }
469*0b57cec5SDimitry Andric 
470*0b57cec5SDimitry Andric   unsigned TotalComparisons = 0;
471*0b57cec5SDimitry Andric 
47281ad6265SDimitry Andric   DenseMap<Value *, SmallVector<unsigned>> PositionMap;
47381ad6265SDimitry Andric   for (unsigned Index = 0; Index < Pointers.size(); ++Index) {
47481ad6265SDimitry Andric     auto Iter = PositionMap.insert({Pointers[Index].PointerValue, {}});
47581ad6265SDimitry Andric     Iter.first->second.push_back(Index);
47681ad6265SDimitry Andric   }
477*0b57cec5SDimitry Andric 
478*0b57cec5SDimitry Andric   // We need to keep track of what pointers we've already seen so we
479*0b57cec5SDimitry Andric   // don't process them twice.
480*0b57cec5SDimitry Andric   SmallSet<unsigned, 2> Seen;
481*0b57cec5SDimitry Andric 
482*0b57cec5SDimitry Andric   // Go through all equivalence classes, get the "pointer check groups"
483*0b57cec5SDimitry Andric   // and add them to the overall solution. We use the order in which accesses
484*0b57cec5SDimitry Andric   // appear in 'Pointers' to enforce determinism.
485*0b57cec5SDimitry Andric   for (unsigned I = 0; I < Pointers.size(); ++I) {
486*0b57cec5SDimitry Andric     // We've seen this pointer before, and therefore already processed
487*0b57cec5SDimitry Andric     // its equivalence class.
488*0b57cec5SDimitry Andric     if (Seen.count(I))
489*0b57cec5SDimitry Andric       continue;
490*0b57cec5SDimitry Andric 
491*0b57cec5SDimitry Andric     MemoryDepChecker::MemAccessInfo Access(Pointers[I].PointerValue,
492*0b57cec5SDimitry Andric                                            Pointers[I].IsWritePtr);
493*0b57cec5SDimitry Andric 
4945ffd83dbSDimitry Andric     SmallVector<RuntimeCheckingPtrGroup, 2> Groups;
495*0b57cec5SDimitry Andric     auto LeaderI = DepCands.findValue(DepCands.getLeaderValue(Access));
496*0b57cec5SDimitry Andric 
497*0b57cec5SDimitry Andric     // Because DepCands is constructed by visiting accesses in the order in
498*0b57cec5SDimitry Andric     // which they appear in alias sets (which is deterministic) and the
499*0b57cec5SDimitry Andric     // iteration order within an equivalence class member is only dependent on
500*0b57cec5SDimitry Andric     // the order in which unions and insertions are performed on the
501*0b57cec5SDimitry Andric     // equivalence class, the iteration order is deterministic.
502*0b57cec5SDimitry Andric     for (auto MI = DepCands.member_begin(LeaderI), ME = DepCands.member_end();
503*0b57cec5SDimitry Andric          MI != ME; ++MI) {
5041106035dSDimitry Andric       auto PointerI = PositionMap.find(MI->getPointer());
5051106035dSDimitry Andric       assert(PointerI != PositionMap.end() &&
5061106035dSDimitry Andric              "pointer in equivalence class not found in PositionMap");
50781ad6265SDimitry Andric       for (unsigned Pointer : PointerI->second) {
508*0b57cec5SDimitry Andric         bool Merged = false;
509*0b57cec5SDimitry Andric         // Mark this pointer as seen.
510*0b57cec5SDimitry Andric         Seen.insert(Pointer);
511*0b57cec5SDimitry Andric 
512*0b57cec5SDimitry Andric         // Go through all the existing sets and see if we can find one
513*0b57cec5SDimitry Andric         // which can include this pointer.
5145ffd83dbSDimitry Andric         for (RuntimeCheckingPtrGroup &Group : Groups) {
515*0b57cec5SDimitry Andric           // Don't perform more than a certain amount of comparisons.
516*0b57cec5SDimitry Andric           // This should limit the cost of grouping the pointers to something
517*0b57cec5SDimitry Andric           // reasonable.  If we do end up hitting this threshold, the algorithm
518*0b57cec5SDimitry Andric           // will create separate groups for all remaining pointers.
519*0b57cec5SDimitry Andric           if (TotalComparisons > MemoryCheckMergeThreshold)
520*0b57cec5SDimitry Andric             break;
521*0b57cec5SDimitry Andric 
522*0b57cec5SDimitry Andric           TotalComparisons++;
523*0b57cec5SDimitry Andric 
524fe6060f1SDimitry Andric           if (Group.addPointer(Pointer, *this)) {
525*0b57cec5SDimitry Andric             Merged = true;
526*0b57cec5SDimitry Andric             break;
527*0b57cec5SDimitry Andric           }
528*0b57cec5SDimitry Andric         }
529*0b57cec5SDimitry Andric 
530*0b57cec5SDimitry Andric         if (!Merged)
531*0b57cec5SDimitry Andric           // We couldn't add this pointer to any existing set or the threshold
532*0b57cec5SDimitry Andric           // for the number of comparisons has been reached. Create a new group
533*0b57cec5SDimitry Andric           // to hold the current pointer.
5345ffd83dbSDimitry Andric           Groups.push_back(RuntimeCheckingPtrGroup(Pointer, *this));
535*0b57cec5SDimitry Andric       }
53681ad6265SDimitry Andric     }
537*0b57cec5SDimitry Andric 
538*0b57cec5SDimitry Andric     // We've computed the grouped checks for this partition.
539*0b57cec5SDimitry Andric     // Save the results and continue with the next one.
540*0b57cec5SDimitry Andric     llvm::copy(Groups, std::back_inserter(CheckingGroups));
541*0b57cec5SDimitry Andric   }
542*0b57cec5SDimitry Andric }
543*0b57cec5SDimitry Andric 
544*0b57cec5SDimitry Andric bool RuntimePointerChecking::arePointersInSamePartition(
545*0b57cec5SDimitry Andric     const SmallVectorImpl<int> &PtrToPartition, unsigned PtrIdx1,
546*0b57cec5SDimitry Andric     unsigned PtrIdx2) {
547*0b57cec5SDimitry Andric   return (PtrToPartition[PtrIdx1] != -1 &&
548*0b57cec5SDimitry Andric           PtrToPartition[PtrIdx1] == PtrToPartition[PtrIdx2]);
549*0b57cec5SDimitry Andric }
550*0b57cec5SDimitry Andric 
551*0b57cec5SDimitry Andric bool RuntimePointerChecking::needsChecking(unsigned I, unsigned J) const {
552*0b57cec5SDimitry Andric   const PointerInfo &PointerI = Pointers[I];
553*0b57cec5SDimitry Andric   const PointerInfo &PointerJ = Pointers[J];
554*0b57cec5SDimitry Andric 
555*0b57cec5SDimitry Andric   // No need to check if two readonly pointers intersect.
556*0b57cec5SDimitry Andric   if (!PointerI.IsWritePtr && !PointerJ.IsWritePtr)
557*0b57cec5SDimitry Andric     return false;
558*0b57cec5SDimitry Andric 
559*0b57cec5SDimitry Andric   // Only need to check pointers between two different dependency sets.
560*0b57cec5SDimitry Andric   if (PointerI.DependencySetId == PointerJ.DependencySetId)
561*0b57cec5SDimitry Andric     return false;
562*0b57cec5SDimitry Andric 
563*0b57cec5SDimitry Andric   // Only need to check pointers in the same alias set.
564*0b57cec5SDimitry Andric   if (PointerI.AliasSetId != PointerJ.AliasSetId)
565*0b57cec5SDimitry Andric     return false;
566*0b57cec5SDimitry Andric 
567*0b57cec5SDimitry Andric   return true;
568*0b57cec5SDimitry Andric }
569*0b57cec5SDimitry Andric 
570*0b57cec5SDimitry Andric void RuntimePointerChecking::printChecks(
5715ffd83dbSDimitry Andric     raw_ostream &OS, const SmallVectorImpl<RuntimePointerCheck> &Checks,
572*0b57cec5SDimitry Andric     unsigned Depth) const {
573*0b57cec5SDimitry Andric   unsigned N = 0;
574*0b57cec5SDimitry Andric   for (const auto &Check : Checks) {
575*0b57cec5SDimitry Andric     const auto &First = Check.first->Members, &Second = Check.second->Members;
576*0b57cec5SDimitry Andric 
577*0b57cec5SDimitry Andric     OS.indent(Depth) << "Check " << N++ << ":\n";
578*0b57cec5SDimitry Andric 
579*0b57cec5SDimitry Andric     OS.indent(Depth + 2) << "Comparing group (" << Check.first << "):\n";
580*0b57cec5SDimitry Andric     for (unsigned K = 0; K < First.size(); ++K)
581*0b57cec5SDimitry Andric       OS.indent(Depth + 2) << *Pointers[First[K]].PointerValue << "\n";
582*0b57cec5SDimitry Andric 
583*0b57cec5SDimitry Andric     OS.indent(Depth + 2) << "Against group (" << Check.second << "):\n";
584*0b57cec5SDimitry Andric     for (unsigned K = 0; K < Second.size(); ++K)
585*0b57cec5SDimitry Andric       OS.indent(Depth + 2) << *Pointers[Second[K]].PointerValue << "\n";
586*0b57cec5SDimitry Andric   }
587*0b57cec5SDimitry Andric }
588*0b57cec5SDimitry Andric 
589*0b57cec5SDimitry Andric void RuntimePointerChecking::print(raw_ostream &OS, unsigned Depth) const {
590*0b57cec5SDimitry Andric 
591*0b57cec5SDimitry Andric   OS.indent(Depth) << "Run-time memory checks:\n";
592*0b57cec5SDimitry Andric   printChecks(OS, Checks, Depth);
593*0b57cec5SDimitry Andric 
594*0b57cec5SDimitry Andric   OS.indent(Depth) << "Grouped accesses:\n";
595*0b57cec5SDimitry Andric   for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
596*0b57cec5SDimitry Andric     const auto &CG = CheckingGroups[I];
597*0b57cec5SDimitry Andric 
598*0b57cec5SDimitry Andric     OS.indent(Depth + 2) << "Group " << &CG << ":\n";
599*0b57cec5SDimitry Andric     OS.indent(Depth + 4) << "(Low: " << *CG.Low << " High: " << *CG.High
600*0b57cec5SDimitry Andric                          << ")\n";
601*0b57cec5SDimitry Andric     for (unsigned J = 0; J < CG.Members.size(); ++J) {
602*0b57cec5SDimitry Andric       OS.indent(Depth + 6) << "Member: " << *Pointers[CG.Members[J]].Expr
603*0b57cec5SDimitry Andric                            << "\n";
604*0b57cec5SDimitry Andric     }
605*0b57cec5SDimitry Andric   }
606*0b57cec5SDimitry Andric }
607*0b57cec5SDimitry Andric 
608*0b57cec5SDimitry Andric namespace {
609*0b57cec5SDimitry Andric 
610*0b57cec5SDimitry Andric /// Analyses memory accesses in a loop.
611*0b57cec5SDimitry Andric ///
612*0b57cec5SDimitry Andric /// Checks whether run time pointer checks are needed and builds sets for data
613*0b57cec5SDimitry Andric /// dependence checking.
614*0b57cec5SDimitry Andric class AccessAnalysis {
615*0b57cec5SDimitry Andric public:
616*0b57cec5SDimitry Andric   /// Read or write access location.
617*0b57cec5SDimitry Andric   typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
618*0b57cec5SDimitry Andric   typedef SmallVector<MemAccessInfo, 8> MemAccessInfoList;
619*0b57cec5SDimitry Andric 
620e8d8bef9SDimitry Andric   AccessAnalysis(Loop *TheLoop, AAResults *AA, LoopInfo *LI,
621e8d8bef9SDimitry Andric                  MemoryDepChecker::DepCandidates &DA,
622*0b57cec5SDimitry Andric                  PredicatedScalarEvolution &PSE)
62304eeddc0SDimitry Andric       : TheLoop(TheLoop), AST(*AA), LI(LI), DepCands(DA), PSE(PSE) {}
624*0b57cec5SDimitry Andric 
625*0b57cec5SDimitry Andric   /// Register a load  and whether it is only read from.
62681ad6265SDimitry Andric   void addLoad(MemoryLocation &Loc, Type *AccessTy, bool IsReadOnly) {
627*0b57cec5SDimitry Andric     Value *Ptr = const_cast<Value*>(Loc.Ptr);
628e8d8bef9SDimitry Andric     AST.add(Ptr, LocationSize::beforeOrAfterPointer(), Loc.AATags);
62981ad6265SDimitry Andric     Accesses[MemAccessInfo(Ptr, false)].insert(AccessTy);
630*0b57cec5SDimitry Andric     if (IsReadOnly)
631*0b57cec5SDimitry Andric       ReadOnlyPtr.insert(Ptr);
632*0b57cec5SDimitry Andric   }
633*0b57cec5SDimitry Andric 
634*0b57cec5SDimitry Andric   /// Register a store.
63581ad6265SDimitry Andric   void addStore(MemoryLocation &Loc, Type *AccessTy) {
636*0b57cec5SDimitry Andric     Value *Ptr = const_cast<Value*>(Loc.Ptr);
637e8d8bef9SDimitry Andric     AST.add(Ptr, LocationSize::beforeOrAfterPointer(), Loc.AATags);
63881ad6265SDimitry Andric     Accesses[MemAccessInfo(Ptr, true)].insert(AccessTy);
639*0b57cec5SDimitry Andric   }
640*0b57cec5SDimitry Andric 
641*0b57cec5SDimitry Andric   /// Check if we can emit a run-time no-alias check for \p Access.
642*0b57cec5SDimitry Andric   ///
643*0b57cec5SDimitry Andric   /// Returns true if we can emit a run-time no alias check for \p Access.
644*0b57cec5SDimitry Andric   /// If we can check this access, this also adds it to a dependence set and
645*0b57cec5SDimitry Andric   /// adds a run-time to check for it to \p RtCheck. If \p Assume is true,
646*0b57cec5SDimitry Andric   /// we will attempt to use additional run-time checks in order to get
647*0b57cec5SDimitry Andric   /// the bounds of the pointer.
648*0b57cec5SDimitry Andric   bool createCheckForAccess(RuntimePointerChecking &RtCheck,
64981ad6265SDimitry Andric                             MemAccessInfo Access, Type *AccessTy,
650*0b57cec5SDimitry Andric                             const ValueToValueMap &Strides,
651*0b57cec5SDimitry Andric                             DenseMap<Value *, unsigned> &DepSetId,
652*0b57cec5SDimitry Andric                             Loop *TheLoop, unsigned &RunningDepId,
65381ad6265SDimitry Andric                             unsigned ASId, bool ShouldCheckStride, bool Assume);
654*0b57cec5SDimitry Andric 
655*0b57cec5SDimitry Andric   /// Check whether we can check the pointers at runtime for
656*0b57cec5SDimitry Andric   /// non-intersection.
657*0b57cec5SDimitry Andric   ///
658*0b57cec5SDimitry Andric   /// Returns true if we need no check or if we do and we can generate them
659*0b57cec5SDimitry Andric   /// (i.e. the pointers have computable bounds).
660*0b57cec5SDimitry Andric   bool canCheckPtrAtRT(RuntimePointerChecking &RtCheck, ScalarEvolution *SE,
661*0b57cec5SDimitry Andric                        Loop *TheLoop, const ValueToValueMap &Strides,
66281ad6265SDimitry Andric                        Value *&UncomputablePtr, bool ShouldCheckWrap = false);
663*0b57cec5SDimitry Andric 
664*0b57cec5SDimitry Andric   /// Goes over all memory accesses, checks whether a RT check is needed
665*0b57cec5SDimitry Andric   /// and builds sets of dependent accesses.
666*0b57cec5SDimitry Andric   void buildDependenceSets() {
667*0b57cec5SDimitry Andric     processMemAccesses();
668*0b57cec5SDimitry Andric   }
669*0b57cec5SDimitry Andric 
670*0b57cec5SDimitry Andric   /// Initial processing of memory accesses determined that we need to
671*0b57cec5SDimitry Andric   /// perform dependency checking.
672*0b57cec5SDimitry Andric   ///
673*0b57cec5SDimitry Andric   /// Note that this can later be cleared if we retry memcheck analysis without
674*0b57cec5SDimitry Andric   /// dependency checking (i.e. FoundNonConstantDistanceDependence).
675*0b57cec5SDimitry Andric   bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
676*0b57cec5SDimitry Andric 
677*0b57cec5SDimitry Andric   /// We decided that no dependence analysis would be used.  Reset the state.
678*0b57cec5SDimitry Andric   void resetDepChecks(MemoryDepChecker &DepChecker) {
679*0b57cec5SDimitry Andric     CheckDeps.clear();
680*0b57cec5SDimitry Andric     DepChecker.clearDependences();
681*0b57cec5SDimitry Andric   }
682*0b57cec5SDimitry Andric 
683*0b57cec5SDimitry Andric   MemAccessInfoList &getDependenciesToCheck() { return CheckDeps; }
684*0b57cec5SDimitry Andric 
685*0b57cec5SDimitry Andric private:
68681ad6265SDimitry Andric   typedef MapVector<MemAccessInfo, SmallSetVector<Type *, 1>> PtrAccessMap;
687*0b57cec5SDimitry Andric 
688*0b57cec5SDimitry Andric   /// Go over all memory access and check whether runtime pointer checks
689*0b57cec5SDimitry Andric   /// are needed and build sets of dependency check candidates.
690*0b57cec5SDimitry Andric   void processMemAccesses();
691*0b57cec5SDimitry Andric 
69281ad6265SDimitry Andric   /// Map of all accesses. Values are the types used to access memory pointed to
69381ad6265SDimitry Andric   /// by the pointer.
69481ad6265SDimitry Andric   PtrAccessMap Accesses;
695*0b57cec5SDimitry Andric 
696*0b57cec5SDimitry Andric   /// The loop being checked.
697*0b57cec5SDimitry Andric   const Loop *TheLoop;
698*0b57cec5SDimitry Andric 
699*0b57cec5SDimitry Andric   /// List of accesses that need a further dependence check.
700*0b57cec5SDimitry Andric   MemAccessInfoList CheckDeps;
701*0b57cec5SDimitry Andric 
702*0b57cec5SDimitry Andric   /// Set of pointers that are read only.
703*0b57cec5SDimitry Andric   SmallPtrSet<Value*, 16> ReadOnlyPtr;
704*0b57cec5SDimitry Andric 
705*0b57cec5SDimitry Andric   /// An alias set tracker to partition the access set by underlying object and
706*0b57cec5SDimitry Andric   //intrinsic property (such as TBAA metadata).
707*0b57cec5SDimitry Andric   AliasSetTracker AST;
708*0b57cec5SDimitry Andric 
709*0b57cec5SDimitry Andric   LoopInfo *LI;
710*0b57cec5SDimitry Andric 
711*0b57cec5SDimitry Andric   /// Sets of potentially dependent accesses - members of one set share an
712*0b57cec5SDimitry Andric   /// underlying pointer. The set "CheckDeps" identfies which sets really need a
713*0b57cec5SDimitry Andric   /// dependence check.
714*0b57cec5SDimitry Andric   MemoryDepChecker::DepCandidates &DepCands;
715*0b57cec5SDimitry Andric 
716*0b57cec5SDimitry Andric   /// Initial processing of memory accesses determined that we may need
717*0b57cec5SDimitry Andric   /// to add memchecks.  Perform the analysis to determine the necessary checks.
718*0b57cec5SDimitry Andric   ///
719*0b57cec5SDimitry Andric   /// Note that, this is different from isDependencyCheckNeeded.  When we retry
720*0b57cec5SDimitry Andric   /// memcheck analysis without dependency checking
721*0b57cec5SDimitry Andric   /// (i.e. FoundNonConstantDistanceDependence), isDependencyCheckNeeded is
722*0b57cec5SDimitry Andric   /// cleared while this remains set if we have potentially dependent accesses.
72304eeddc0SDimitry Andric   bool IsRTCheckAnalysisNeeded = false;
724*0b57cec5SDimitry Andric 
725*0b57cec5SDimitry Andric   /// The SCEV predicate containing all the SCEV-related assumptions.
726*0b57cec5SDimitry Andric   PredicatedScalarEvolution &PSE;
727*0b57cec5SDimitry Andric };
728*0b57cec5SDimitry Andric 
729*0b57cec5SDimitry Andric } // end anonymous namespace
730*0b57cec5SDimitry Andric 
731*0b57cec5SDimitry Andric /// Check whether a pointer can participate in a runtime bounds check.
732*0b57cec5SDimitry Andric /// If \p Assume, try harder to prove that we can compute the bounds of \p Ptr
733*0b57cec5SDimitry Andric /// by adding run-time checks (overflow checks) if necessary.
73481ad6265SDimitry Andric static bool hasComputableBounds(PredicatedScalarEvolution &PSE, Value *Ptr,
73581ad6265SDimitry Andric                                 const SCEV *PtrScev, Loop *L, bool Assume) {
736*0b57cec5SDimitry Andric   // The bounds for loop-invariant pointer is trivial.
737*0b57cec5SDimitry Andric   if (PSE.getSE()->isLoopInvariant(PtrScev, L))
738*0b57cec5SDimitry Andric     return true;
739*0b57cec5SDimitry Andric 
740*0b57cec5SDimitry Andric   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
741*0b57cec5SDimitry Andric 
742*0b57cec5SDimitry Andric   if (!AR && Assume)
743*0b57cec5SDimitry Andric     AR = PSE.getAsAddRec(Ptr);
744*0b57cec5SDimitry Andric 
745*0b57cec5SDimitry Andric   if (!AR)
746*0b57cec5SDimitry Andric     return false;
747*0b57cec5SDimitry Andric 
748*0b57cec5SDimitry Andric   return AR->isAffine();
749*0b57cec5SDimitry Andric }
750*0b57cec5SDimitry Andric 
751*0b57cec5SDimitry Andric /// Check whether a pointer address cannot wrap.
752*0b57cec5SDimitry Andric static bool isNoWrap(PredicatedScalarEvolution &PSE,
75381ad6265SDimitry Andric                      const ValueToValueMap &Strides, Value *Ptr, Type *AccessTy,
75481ad6265SDimitry Andric                      Loop *L) {
755*0b57cec5SDimitry Andric   const SCEV *PtrScev = PSE.getSCEV(Ptr);
756*0b57cec5SDimitry Andric   if (PSE.getSE()->isLoopInvariant(PtrScev, L))
757*0b57cec5SDimitry Andric     return true;
758*0b57cec5SDimitry Andric 
759349cc55cSDimitry Andric   int64_t Stride = getPtrStride(PSE, AccessTy, Ptr, L, Strides);
760*0b57cec5SDimitry Andric   if (Stride == 1 || PSE.hasNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW))
761*0b57cec5SDimitry Andric     return true;
762*0b57cec5SDimitry Andric 
763*0b57cec5SDimitry Andric   return false;
764*0b57cec5SDimitry Andric }
765*0b57cec5SDimitry Andric 
7664824e7fdSDimitry Andric static void visitPointers(Value *StartPtr, const Loop &InnermostLoop,
7674824e7fdSDimitry Andric                           function_ref<void(Value *)> AddPointer) {
7684824e7fdSDimitry Andric   SmallPtrSet<Value *, 8> Visited;
7694824e7fdSDimitry Andric   SmallVector<Value *> WorkList;
7704824e7fdSDimitry Andric   WorkList.push_back(StartPtr);
7714824e7fdSDimitry Andric 
7724824e7fdSDimitry Andric   while (!WorkList.empty()) {
7734824e7fdSDimitry Andric     Value *Ptr = WorkList.pop_back_val();
7744824e7fdSDimitry Andric     if (!Visited.insert(Ptr).second)
7754824e7fdSDimitry Andric       continue;
7764824e7fdSDimitry Andric     auto *PN = dyn_cast<PHINode>(Ptr);
7774824e7fdSDimitry Andric     // SCEV does not look through non-header PHIs inside the loop. Such phis
7784824e7fdSDimitry Andric     // can be analyzed by adding separate accesses for each incoming pointer
7794824e7fdSDimitry Andric     // value.
7804824e7fdSDimitry Andric     if (PN && InnermostLoop.contains(PN->getParent()) &&
7814824e7fdSDimitry Andric         PN->getParent() != InnermostLoop.getHeader()) {
7824824e7fdSDimitry Andric       for (const Use &Inc : PN->incoming_values())
7834824e7fdSDimitry Andric         WorkList.push_back(Inc);
7844824e7fdSDimitry Andric     } else
7854824e7fdSDimitry Andric       AddPointer(Ptr);
7864824e7fdSDimitry Andric   }
7874824e7fdSDimitry Andric }
7884824e7fdSDimitry Andric 
789fcaf7f86SDimitry Andric // Walk back through the IR for a pointer, looking for a select like the
790fcaf7f86SDimitry Andric // following:
791fcaf7f86SDimitry Andric //
792fcaf7f86SDimitry Andric //  %offset = select i1 %cmp, i64 %a, i64 %b
793fcaf7f86SDimitry Andric //  %addr = getelementptr double, double* %base, i64 %offset
794fcaf7f86SDimitry Andric //  %ld = load double, double* %addr, align 8
795fcaf7f86SDimitry Andric //
796fcaf7f86SDimitry Andric // We won't be able to form a single SCEVAddRecExpr from this since the
797fcaf7f86SDimitry Andric // address for each loop iteration depends on %cmp. We could potentially
798fcaf7f86SDimitry Andric // produce multiple valid SCEVAddRecExprs, though, and check all of them for
799fcaf7f86SDimitry Andric // memory safety/aliasing if needed.
800fcaf7f86SDimitry Andric //
801fcaf7f86SDimitry Andric // If we encounter some IR we don't yet handle, or something obviously fine
802fcaf7f86SDimitry Andric // like a constant, then we just add the SCEV for that term to the list passed
803fcaf7f86SDimitry Andric // in by the caller. If we have a node that may potentially yield a valid
804fcaf7f86SDimitry Andric // SCEVAddRecExpr then we decompose it into parts and build the SCEV terms
805fcaf7f86SDimitry Andric // ourselves before adding to the list.
806fcaf7f86SDimitry Andric static void
807fcaf7f86SDimitry Andric findForkedSCEVs(ScalarEvolution *SE, const Loop *L, Value *Ptr,
808fcaf7f86SDimitry Andric                 SmallVectorImpl<std::pair<const SCEV *, bool>> &ScevList,
809fcaf7f86SDimitry Andric                 unsigned Depth) {
810fcaf7f86SDimitry Andric   // If our Value is a SCEVAddRecExpr, loop invariant, not an instruction, or
811fcaf7f86SDimitry Andric   // we've exceeded our limit on recursion, just return whatever we have
812fcaf7f86SDimitry Andric   // regardless of whether it can be used for a forked pointer or not, along
813fcaf7f86SDimitry Andric   // with an indication of whether it might be a poison or undef value.
814fcaf7f86SDimitry Andric   const SCEV *Scev = SE->getSCEV(Ptr);
815fcaf7f86SDimitry Andric   if (isa<SCEVAddRecExpr>(Scev) || L->isLoopInvariant(Ptr) ||
816fcaf7f86SDimitry Andric       !isa<Instruction>(Ptr) || Depth == 0) {
817fcaf7f86SDimitry Andric     ScevList.push_back(
818fcaf7f86SDimitry Andric         std::make_pair(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr)));
819fcaf7f86SDimitry Andric     return;
820fcaf7f86SDimitry Andric   }
821fcaf7f86SDimitry Andric 
822fcaf7f86SDimitry Andric   Depth--;
823fcaf7f86SDimitry Andric 
824fcaf7f86SDimitry Andric   auto UndefPoisonCheck = [](std::pair<const SCEV *, bool> S) -> bool {
825fcaf7f86SDimitry Andric     return S.second;
826fcaf7f86SDimitry Andric   };
827fcaf7f86SDimitry Andric 
828fcaf7f86SDimitry Andric   Instruction *I = cast<Instruction>(Ptr);
829fcaf7f86SDimitry Andric   unsigned Opcode = I->getOpcode();
830fcaf7f86SDimitry Andric   switch (Opcode) {
831fcaf7f86SDimitry Andric   case Instruction::GetElementPtr: {
832fcaf7f86SDimitry Andric     GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
833fcaf7f86SDimitry Andric     Type *SourceTy = GEP->getSourceElementType();
834fcaf7f86SDimitry Andric     // We only handle base + single offset GEPs here for now.
835fcaf7f86SDimitry Andric     // Not dealing with preexisting gathers yet, so no vectors.
836fcaf7f86SDimitry Andric     if (I->getNumOperands() != 2 || SourceTy->isVectorTy()) {
837fcaf7f86SDimitry Andric       ScevList.push_back(
838fcaf7f86SDimitry Andric           std::make_pair(Scev, !isGuaranteedNotToBeUndefOrPoison(GEP)));
839fcaf7f86SDimitry Andric       break;
840fcaf7f86SDimitry Andric     }
841fcaf7f86SDimitry Andric     SmallVector<std::pair<const SCEV *, bool>, 2> BaseScevs;
842fcaf7f86SDimitry Andric     SmallVector<std::pair<const SCEV *, bool>, 2> OffsetScevs;
843fcaf7f86SDimitry Andric     findForkedSCEVs(SE, L, I->getOperand(0), BaseScevs, Depth);
844fcaf7f86SDimitry Andric     findForkedSCEVs(SE, L, I->getOperand(1), OffsetScevs, Depth);
845fcaf7f86SDimitry Andric 
846fcaf7f86SDimitry Andric     // See if we need to freeze our fork...
847fcaf7f86SDimitry Andric     bool NeedsFreeze = any_of(BaseScevs, UndefPoisonCheck) ||
848fcaf7f86SDimitry Andric                        any_of(OffsetScevs, UndefPoisonCheck);
849fcaf7f86SDimitry Andric 
850fcaf7f86SDimitry Andric     // Check that we only have a single fork, on either the base or the offset.
851fcaf7f86SDimitry Andric     // Copy the SCEV across for the one without a fork in order to generate
852fcaf7f86SDimitry Andric     // the full SCEV for both sides of the GEP.
853fcaf7f86SDimitry Andric     if (OffsetScevs.size() == 2 && BaseScevs.size() == 1)
854fcaf7f86SDimitry Andric       BaseScevs.push_back(BaseScevs[0]);
855fcaf7f86SDimitry Andric     else if (BaseScevs.size() == 2 && OffsetScevs.size() == 1)
856fcaf7f86SDimitry Andric       OffsetScevs.push_back(OffsetScevs[0]);
857fcaf7f86SDimitry Andric     else {
858fcaf7f86SDimitry Andric       ScevList.push_back(std::make_pair(Scev, NeedsFreeze));
859fcaf7f86SDimitry Andric       break;
860fcaf7f86SDimitry Andric     }
861fcaf7f86SDimitry Andric 
862fcaf7f86SDimitry Andric     // Find the pointer type we need to extend to.
863fcaf7f86SDimitry Andric     Type *IntPtrTy = SE->getEffectiveSCEVType(
864fcaf7f86SDimitry Andric         SE->getSCEV(GEP->getPointerOperand())->getType());
865fcaf7f86SDimitry Andric 
866fcaf7f86SDimitry Andric     // Find the size of the type being pointed to. We only have a single
867fcaf7f86SDimitry Andric     // index term (guarded above) so we don't need to index into arrays or
868fcaf7f86SDimitry Andric     // structures, just get the size of the scalar value.
869fcaf7f86SDimitry Andric     const SCEV *Size = SE->getSizeOfExpr(IntPtrTy, SourceTy);
870fcaf7f86SDimitry Andric 
871fcaf7f86SDimitry Andric     // Scale up the offsets by the size of the type, then add to the bases.
872fcaf7f86SDimitry Andric     const SCEV *Scaled1 = SE->getMulExpr(
873fcaf7f86SDimitry Andric         Size, SE->getTruncateOrSignExtend(OffsetScevs[0].first, IntPtrTy));
874fcaf7f86SDimitry Andric     const SCEV *Scaled2 = SE->getMulExpr(
875fcaf7f86SDimitry Andric         Size, SE->getTruncateOrSignExtend(OffsetScevs[1].first, IntPtrTy));
876fcaf7f86SDimitry Andric     ScevList.push_back(std::make_pair(
877fcaf7f86SDimitry Andric         SE->getAddExpr(BaseScevs[0].first, Scaled1), NeedsFreeze));
878fcaf7f86SDimitry Andric     ScevList.push_back(std::make_pair(
879fcaf7f86SDimitry Andric         SE->getAddExpr(BaseScevs[1].first, Scaled2), NeedsFreeze));
880fcaf7f86SDimitry Andric     break;
881fcaf7f86SDimitry Andric   }
882fcaf7f86SDimitry Andric   case Instruction::Select: {
883fcaf7f86SDimitry Andric     SmallVector<std::pair<const SCEV *, bool>, 2> ChildScevs;
884fcaf7f86SDimitry Andric     // A select means we've found a forked pointer, but we currently only
885fcaf7f86SDimitry Andric     // support a single select per pointer so if there's another behind this
886fcaf7f86SDimitry Andric     // then we just bail out and return the generic SCEV.
887fcaf7f86SDimitry Andric     findForkedSCEVs(SE, L, I->getOperand(1), ChildScevs, Depth);
888fcaf7f86SDimitry Andric     findForkedSCEVs(SE, L, I->getOperand(2), ChildScevs, Depth);
889fcaf7f86SDimitry Andric     if (ChildScevs.size() == 2) {
890fcaf7f86SDimitry Andric       ScevList.push_back(ChildScevs[0]);
891fcaf7f86SDimitry Andric       ScevList.push_back(ChildScevs[1]);
892fcaf7f86SDimitry Andric     } else
893fcaf7f86SDimitry Andric       ScevList.push_back(
894fcaf7f86SDimitry Andric           std::make_pair(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr)));
895fcaf7f86SDimitry Andric     break;
896fcaf7f86SDimitry Andric   }
897fcaf7f86SDimitry Andric   default:
898fcaf7f86SDimitry Andric     // Just return the current SCEV if we haven't handled the instruction yet.
899fcaf7f86SDimitry Andric     LLVM_DEBUG(dbgs() << "ForkedPtr unhandled instruction: " << *I << "\n");
900fcaf7f86SDimitry Andric     ScevList.push_back(
901fcaf7f86SDimitry Andric         std::make_pair(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr)));
902fcaf7f86SDimitry Andric     break;
903fcaf7f86SDimitry Andric   }
904fcaf7f86SDimitry Andric }
905fcaf7f86SDimitry Andric 
906fcaf7f86SDimitry Andric static SmallVector<std::pair<const SCEV *, bool>>
907fcaf7f86SDimitry Andric findForkedPointer(PredicatedScalarEvolution &PSE,
908fcaf7f86SDimitry Andric                   const ValueToValueMap &StridesMap, Value *Ptr,
909fcaf7f86SDimitry Andric                   const Loop *L) {
910fcaf7f86SDimitry Andric   ScalarEvolution *SE = PSE.getSE();
911fcaf7f86SDimitry Andric   assert(SE->isSCEVable(Ptr->getType()) && "Value is not SCEVable!");
912fcaf7f86SDimitry Andric   SmallVector<std::pair<const SCEV *, bool>> Scevs;
913fcaf7f86SDimitry Andric   findForkedSCEVs(SE, L, Ptr, Scevs, MaxForkedSCEVDepth);
914fcaf7f86SDimitry Andric 
915fcaf7f86SDimitry Andric   // For now, we will only accept a forked pointer with two possible SCEVs.
916fcaf7f86SDimitry Andric   if (Scevs.size() == 2)
917fcaf7f86SDimitry Andric     return Scevs;
918fcaf7f86SDimitry Andric 
919fcaf7f86SDimitry Andric   return {
920fcaf7f86SDimitry Andric       std::make_pair(replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr), false)};
921fcaf7f86SDimitry Andric }
922fcaf7f86SDimitry Andric 
923*0b57cec5SDimitry Andric bool AccessAnalysis::createCheckForAccess(RuntimePointerChecking &RtCheck,
92481ad6265SDimitry Andric                                           MemAccessInfo Access, Type *AccessTy,
925*0b57cec5SDimitry Andric                                           const ValueToValueMap &StridesMap,
926*0b57cec5SDimitry Andric                                           DenseMap<Value *, unsigned> &DepSetId,
927*0b57cec5SDimitry Andric                                           Loop *TheLoop, unsigned &RunningDepId,
928*0b57cec5SDimitry Andric                                           unsigned ASId, bool ShouldCheckWrap,
929*0b57cec5SDimitry Andric                                           bool Assume) {
930*0b57cec5SDimitry Andric   Value *Ptr = Access.getPointer();
931*0b57cec5SDimitry Andric 
932fcaf7f86SDimitry Andric   SmallVector<std::pair<const SCEV *, bool>> TranslatedPtrs =
933fcaf7f86SDimitry Andric       findForkedPointer(PSE, StridesMap, Ptr, TheLoop);
93481ad6265SDimitry Andric 
93581ad6265SDimitry Andric   for (auto &P : TranslatedPtrs) {
93681ad6265SDimitry Andric     const SCEV *PtrExpr = P.first;
93781ad6265SDimitry Andric     if (!hasComputableBounds(PSE, Ptr, PtrExpr, TheLoop, Assume))
938*0b57cec5SDimitry Andric       return false;
939*0b57cec5SDimitry Andric 
940*0b57cec5SDimitry Andric     // When we run after a failing dependency check we have to make sure
941*0b57cec5SDimitry Andric     // we don't have wrapping pointers.
94281ad6265SDimitry Andric     if (ShouldCheckWrap) {
94381ad6265SDimitry Andric       // Skip wrap checking when translating pointers.
94481ad6265SDimitry Andric       if (TranslatedPtrs.size() > 1)
94581ad6265SDimitry Andric         return false;
94681ad6265SDimitry Andric 
94781ad6265SDimitry Andric       if (!isNoWrap(PSE, StridesMap, Ptr, AccessTy, TheLoop)) {
948*0b57cec5SDimitry Andric         auto *Expr = PSE.getSCEV(Ptr);
949*0b57cec5SDimitry Andric         if (!Assume || !isa<SCEVAddRecExpr>(Expr))
950*0b57cec5SDimitry Andric           return false;
951*0b57cec5SDimitry Andric         PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
952*0b57cec5SDimitry Andric       }
95381ad6265SDimitry Andric     }
95481ad6265SDimitry Andric     // If there's only one option for Ptr, look it up after bounds and wrap
95581ad6265SDimitry Andric     // checking, because assumptions might have been added to PSE.
95681ad6265SDimitry Andric     if (TranslatedPtrs.size() == 1)
95781ad6265SDimitry Andric       TranslatedPtrs[0] = std::make_pair(
95881ad6265SDimitry Andric           replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr), false);
95981ad6265SDimitry Andric   }
96081ad6265SDimitry Andric 
96181ad6265SDimitry Andric   for (auto &P : TranslatedPtrs) {
96281ad6265SDimitry Andric     const SCEV *PtrExpr = P.first;
963*0b57cec5SDimitry Andric 
964*0b57cec5SDimitry Andric     // The id of the dependence set.
965*0b57cec5SDimitry Andric     unsigned DepId;
966*0b57cec5SDimitry Andric 
967*0b57cec5SDimitry Andric     if (isDependencyCheckNeeded()) {
968*0b57cec5SDimitry Andric       Value *Leader = DepCands.getLeaderValue(Access).getPointer();
969*0b57cec5SDimitry Andric       unsigned &LeaderId = DepSetId[Leader];
970*0b57cec5SDimitry Andric       if (!LeaderId)
971*0b57cec5SDimitry Andric         LeaderId = RunningDepId++;
972*0b57cec5SDimitry Andric       DepId = LeaderId;
973*0b57cec5SDimitry Andric     } else
974*0b57cec5SDimitry Andric       // Each access has its own dependence set.
975*0b57cec5SDimitry Andric       DepId = RunningDepId++;
976*0b57cec5SDimitry Andric 
977*0b57cec5SDimitry Andric     bool IsWrite = Access.getInt();
97881ad6265SDimitry Andric     RtCheck.insert(TheLoop, Ptr, PtrExpr, AccessTy, IsWrite, DepId, ASId, PSE,
97981ad6265SDimitry Andric                    P.second);
980*0b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
98181ad6265SDimitry Andric   }
982*0b57cec5SDimitry Andric 
983*0b57cec5SDimitry Andric   return true;
984*0b57cec5SDimitry Andric }
985*0b57cec5SDimitry Andric 
986*0b57cec5SDimitry Andric bool AccessAnalysis::canCheckPtrAtRT(RuntimePointerChecking &RtCheck,
987*0b57cec5SDimitry Andric                                      ScalarEvolution *SE, Loop *TheLoop,
988*0b57cec5SDimitry Andric                                      const ValueToValueMap &StridesMap,
98981ad6265SDimitry Andric                                      Value *&UncomputablePtr, bool ShouldCheckWrap) {
990*0b57cec5SDimitry Andric   // Find pointers with computable bounds. We are going to use this information
991*0b57cec5SDimitry Andric   // to place a runtime bound check.
992*0b57cec5SDimitry Andric   bool CanDoRT = true;
993*0b57cec5SDimitry Andric 
9945ffd83dbSDimitry Andric   bool MayNeedRTCheck = false;
995*0b57cec5SDimitry Andric   if (!IsRTCheckAnalysisNeeded) return true;
996*0b57cec5SDimitry Andric 
997*0b57cec5SDimitry Andric   bool IsDepCheckNeeded = isDependencyCheckNeeded();
998*0b57cec5SDimitry Andric 
999*0b57cec5SDimitry Andric   // We assign a consecutive id to access from different alias sets.
1000*0b57cec5SDimitry Andric   // Accesses between different groups doesn't need to be checked.
10015ffd83dbSDimitry Andric   unsigned ASId = 0;
1002*0b57cec5SDimitry Andric   for (auto &AS : AST) {
1003*0b57cec5SDimitry Andric     int NumReadPtrChecks = 0;
1004*0b57cec5SDimitry Andric     int NumWritePtrChecks = 0;
1005*0b57cec5SDimitry Andric     bool CanDoAliasSetRT = true;
10065ffd83dbSDimitry Andric     ++ASId;
1007*0b57cec5SDimitry Andric 
1008*0b57cec5SDimitry Andric     // We assign consecutive id to access from different dependence sets.
1009*0b57cec5SDimitry Andric     // Accesses within the same set don't need a runtime check.
1010*0b57cec5SDimitry Andric     unsigned RunningDepId = 1;
1011*0b57cec5SDimitry Andric     DenseMap<Value *, unsigned> DepSetId;
1012*0b57cec5SDimitry Andric 
1013fcaf7f86SDimitry Andric     SmallVector<std::pair<MemAccessInfo, Type *>, 4> Retries;
1014*0b57cec5SDimitry Andric 
10151106035dSDimitry Andric     // First, count how many write and read accesses are in the alias set. Also
10161106035dSDimitry Andric     // collect MemAccessInfos for later.
10171106035dSDimitry Andric     SmallVector<MemAccessInfo, 4> AccessInfos;
1018e8d8bef9SDimitry Andric     for (const auto &A : AS) {
1019*0b57cec5SDimitry Andric       Value *Ptr = A.getValue();
1020*0b57cec5SDimitry Andric       bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
1021*0b57cec5SDimitry Andric 
1022*0b57cec5SDimitry Andric       if (IsWrite)
1023*0b57cec5SDimitry Andric         ++NumWritePtrChecks;
1024*0b57cec5SDimitry Andric       else
1025*0b57cec5SDimitry Andric         ++NumReadPtrChecks;
10261106035dSDimitry Andric       AccessInfos.emplace_back(Ptr, IsWrite);
1027*0b57cec5SDimitry Andric     }
1028*0b57cec5SDimitry Andric 
10291106035dSDimitry Andric     // We do not need runtime checks for this alias set, if there are no writes
10301106035dSDimitry Andric     // or a single write and no reads.
10311106035dSDimitry Andric     if (NumWritePtrChecks == 0 ||
10321106035dSDimitry Andric         (NumWritePtrChecks == 1 && NumReadPtrChecks == 0)) {
10335ffd83dbSDimitry Andric       assert((AS.size() <= 1 ||
10345ffd83dbSDimitry Andric               all_of(AS,
10355ffd83dbSDimitry Andric                      [this](auto AC) {
10365ffd83dbSDimitry Andric                        MemAccessInfo AccessWrite(AC.getValue(), true);
10371106035dSDimitry Andric                        return DepCands.findValue(AccessWrite) == DepCands.end();
10385ffd83dbSDimitry Andric                      })) &&
10395ffd83dbSDimitry Andric              "Can only skip updating CanDoRT below, if all entries in AS "
10405ffd83dbSDimitry Andric              "are reads or there is at most 1 entry");
10415ffd83dbSDimitry Andric       continue;
10425ffd83dbSDimitry Andric     }
10431106035dSDimitry Andric 
10441106035dSDimitry Andric     for (auto &Access : AccessInfos) {
1045fcaf7f86SDimitry Andric       for (const auto &AccessTy : Accesses[Access]) {
104681ad6265SDimitry Andric         if (!createCheckForAccess(RtCheck, Access, AccessTy, StridesMap,
104781ad6265SDimitry Andric                                   DepSetId, TheLoop, RunningDepId, ASId,
104881ad6265SDimitry Andric                                   ShouldCheckWrap, false)) {
10491106035dSDimitry Andric           LLVM_DEBUG(dbgs() << "LAA: Can't find bounds for ptr:"
10501106035dSDimitry Andric                             << *Access.getPointer() << '\n');
1051fcaf7f86SDimitry Andric           Retries.push_back({Access, AccessTy});
10521106035dSDimitry Andric           CanDoAliasSetRT = false;
10535ffd83dbSDimitry Andric         }
10541106035dSDimitry Andric       }
105581ad6265SDimitry Andric     }
10561106035dSDimitry Andric 
10571106035dSDimitry Andric     // Note that this function computes CanDoRT and MayNeedRTCheck
10581106035dSDimitry Andric     // independently. For example CanDoRT=false, MayNeedRTCheck=false means that
10591106035dSDimitry Andric     // we have a pointer for which we couldn't find the bounds but we don't
10601106035dSDimitry Andric     // actually need to emit any checks so it does not matter.
10611106035dSDimitry Andric     //
10621106035dSDimitry Andric     // We need runtime checks for this alias set, if there are at least 2
10631106035dSDimitry Andric     // dependence sets (in which case RunningDepId > 2) or if we need to re-try
10641106035dSDimitry Andric     // any bound checks (because in that case the number of dependence sets is
10651106035dSDimitry Andric     // incomplete).
10661106035dSDimitry Andric     bool NeedsAliasSetRTCheck = RunningDepId > 2 || !Retries.empty();
1067*0b57cec5SDimitry Andric 
1068*0b57cec5SDimitry Andric     // We need to perform run-time alias checks, but some pointers had bounds
1069*0b57cec5SDimitry Andric     // that couldn't be checked.
1070*0b57cec5SDimitry Andric     if (NeedsAliasSetRTCheck && !CanDoAliasSetRT) {
1071*0b57cec5SDimitry Andric       // Reset the CanDoSetRt flag and retry all accesses that have failed.
1072*0b57cec5SDimitry Andric       // We know that we need these checks, so we can now be more aggressive
1073*0b57cec5SDimitry Andric       // and add further checks if required (overflow checks).
1074*0b57cec5SDimitry Andric       CanDoAliasSetRT = true;
1075fcaf7f86SDimitry Andric       for (auto Retry : Retries) {
1076fcaf7f86SDimitry Andric         MemAccessInfo Access = Retry.first;
1077fcaf7f86SDimitry Andric         Type *AccessTy = Retry.second;
107881ad6265SDimitry Andric         if (!createCheckForAccess(RtCheck, Access, AccessTy, StridesMap,
107981ad6265SDimitry Andric                                   DepSetId, TheLoop, RunningDepId, ASId,
1080*0b57cec5SDimitry Andric                                   ShouldCheckWrap, /*Assume=*/true)) {
1081*0b57cec5SDimitry Andric           CanDoAliasSetRT = false;
108281ad6265SDimitry Andric           UncomputablePtr = Access.getPointer();
1083*0b57cec5SDimitry Andric           break;
1084*0b57cec5SDimitry Andric         }
1085*0b57cec5SDimitry Andric       }
108681ad6265SDimitry Andric     }
1087*0b57cec5SDimitry Andric 
1088*0b57cec5SDimitry Andric     CanDoRT &= CanDoAliasSetRT;
10895ffd83dbSDimitry Andric     MayNeedRTCheck |= NeedsAliasSetRTCheck;
1090*0b57cec5SDimitry Andric     ++ASId;
1091*0b57cec5SDimitry Andric   }
1092*0b57cec5SDimitry Andric 
1093*0b57cec5SDimitry Andric   // If the pointers that we would use for the bounds comparison have different
1094*0b57cec5SDimitry Andric   // address spaces, assume the values aren't directly comparable, so we can't
1095*0b57cec5SDimitry Andric   // use them for the runtime check. We also have to assume they could
1096*0b57cec5SDimitry Andric   // overlap. In the future there should be metadata for whether address spaces
1097*0b57cec5SDimitry Andric   // are disjoint.
1098*0b57cec5SDimitry Andric   unsigned NumPointers = RtCheck.Pointers.size();
1099*0b57cec5SDimitry Andric   for (unsigned i = 0; i < NumPointers; ++i) {
1100*0b57cec5SDimitry Andric     for (unsigned j = i + 1; j < NumPointers; ++j) {
1101*0b57cec5SDimitry Andric       // Only need to check pointers between two different dependency sets.
1102*0b57cec5SDimitry Andric       if (RtCheck.Pointers[i].DependencySetId ==
1103*0b57cec5SDimitry Andric           RtCheck.Pointers[j].DependencySetId)
1104*0b57cec5SDimitry Andric        continue;
1105*0b57cec5SDimitry Andric       // Only need to check pointers in the same alias set.
1106*0b57cec5SDimitry Andric       if (RtCheck.Pointers[i].AliasSetId != RtCheck.Pointers[j].AliasSetId)
1107*0b57cec5SDimitry Andric         continue;
1108*0b57cec5SDimitry Andric 
1109*0b57cec5SDimitry Andric       Value *PtrI = RtCheck.Pointers[i].PointerValue;
1110*0b57cec5SDimitry Andric       Value *PtrJ = RtCheck.Pointers[j].PointerValue;
1111*0b57cec5SDimitry Andric 
1112*0b57cec5SDimitry Andric       unsigned ASi = PtrI->getType()->getPointerAddressSpace();
1113*0b57cec5SDimitry Andric       unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
1114*0b57cec5SDimitry Andric       if (ASi != ASj) {
1115*0b57cec5SDimitry Andric         LLVM_DEBUG(
1116*0b57cec5SDimitry Andric             dbgs() << "LAA: Runtime check would require comparison between"
1117*0b57cec5SDimitry Andric                       " different address spaces\n");
1118*0b57cec5SDimitry Andric         return false;
1119*0b57cec5SDimitry Andric       }
1120*0b57cec5SDimitry Andric     }
1121*0b57cec5SDimitry Andric   }
1122*0b57cec5SDimitry Andric 
11235ffd83dbSDimitry Andric   if (MayNeedRTCheck && CanDoRT)
1124*0b57cec5SDimitry Andric     RtCheck.generateChecks(DepCands, IsDepCheckNeeded);
1125*0b57cec5SDimitry Andric 
1126*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: We need to do " << RtCheck.getNumberOfChecks()
1127*0b57cec5SDimitry Andric                     << " pointer comparisons.\n");
1128*0b57cec5SDimitry Andric 
11295ffd83dbSDimitry Andric   // If we can do run-time checks, but there are no checks, no runtime checks
11305ffd83dbSDimitry Andric   // are needed. This can happen when all pointers point to the same underlying
11315ffd83dbSDimitry Andric   // object for example.
11325ffd83dbSDimitry Andric   RtCheck.Need = CanDoRT ? RtCheck.getNumberOfChecks() != 0 : MayNeedRTCheck;
1133*0b57cec5SDimitry Andric 
11345ffd83dbSDimitry Andric   bool CanDoRTIfNeeded = !RtCheck.Need || CanDoRT;
1135*0b57cec5SDimitry Andric   if (!CanDoRTIfNeeded)
1136*0b57cec5SDimitry Andric     RtCheck.reset();
1137*0b57cec5SDimitry Andric   return CanDoRTIfNeeded;
1138*0b57cec5SDimitry Andric }
1139*0b57cec5SDimitry Andric 
1140*0b57cec5SDimitry Andric void AccessAnalysis::processMemAccesses() {
1141*0b57cec5SDimitry Andric   // We process the set twice: first we process read-write pointers, last we
1142*0b57cec5SDimitry Andric   // process read-only pointers. This allows us to skip dependence tests for
1143*0b57cec5SDimitry Andric   // read-only pointers.
1144*0b57cec5SDimitry Andric 
1145*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
1146*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "  AST: "; AST.dump());
1147*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA:   Accesses(" << Accesses.size() << "):\n");
1148*0b57cec5SDimitry Andric   LLVM_DEBUG({
1149*0b57cec5SDimitry Andric     for (auto A : Accesses)
115081ad6265SDimitry Andric       dbgs() << "\t" << *A.first.getPointer() << " ("
115181ad6265SDimitry Andric              << (A.first.getInt()
115281ad6265SDimitry Andric                      ? "write"
115381ad6265SDimitry Andric                      : (ReadOnlyPtr.count(A.first.getPointer()) ? "read-only"
115481ad6265SDimitry Andric                                                                 : "read"))
115581ad6265SDimitry Andric              << ")\n";
1156*0b57cec5SDimitry Andric   });
1157*0b57cec5SDimitry Andric 
1158*0b57cec5SDimitry Andric   // The AliasSetTracker has nicely partitioned our pointers by metadata
1159*0b57cec5SDimitry Andric   // compatibility and potential for underlying-object overlap. As a result, we
1160*0b57cec5SDimitry Andric   // only need to check for potential pointer dependencies within each alias
1161*0b57cec5SDimitry Andric   // set.
1162e8d8bef9SDimitry Andric   for (const auto &AS : AST) {
1163*0b57cec5SDimitry Andric     // Note that both the alias-set tracker and the alias sets themselves used
1164*0b57cec5SDimitry Andric     // linked lists internally and so the iteration order here is deterministic
1165*0b57cec5SDimitry Andric     // (matching the original instruction order within each set).
1166*0b57cec5SDimitry Andric 
1167*0b57cec5SDimitry Andric     bool SetHasWrite = false;
1168*0b57cec5SDimitry Andric 
1169*0b57cec5SDimitry Andric     // Map of pointers to last access encountered.
1170*0b57cec5SDimitry Andric     typedef DenseMap<const Value*, MemAccessInfo> UnderlyingObjToAccessMap;
1171*0b57cec5SDimitry Andric     UnderlyingObjToAccessMap ObjToLastAccess;
1172*0b57cec5SDimitry Andric 
1173*0b57cec5SDimitry Andric     // Set of access to check after all writes have been processed.
117481ad6265SDimitry Andric     PtrAccessMap DeferredAccesses;
1175*0b57cec5SDimitry Andric 
1176*0b57cec5SDimitry Andric     // Iterate over each alias set twice, once to process read/write pointers,
1177*0b57cec5SDimitry Andric     // and then to process read-only pointers.
1178*0b57cec5SDimitry Andric     for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
1179*0b57cec5SDimitry Andric       bool UseDeferred = SetIteration > 0;
118081ad6265SDimitry Andric       PtrAccessMap &S = UseDeferred ? DeferredAccesses : Accesses;
1181*0b57cec5SDimitry Andric 
1182e8d8bef9SDimitry Andric       for (const auto &AV : AS) {
1183*0b57cec5SDimitry Andric         Value *Ptr = AV.getValue();
1184*0b57cec5SDimitry Andric 
1185*0b57cec5SDimitry Andric         // For a single memory access in AliasSetTracker, Accesses may contain
1186*0b57cec5SDimitry Andric         // both read and write, and they both need to be handled for CheckDeps.
1187e8d8bef9SDimitry Andric         for (const auto &AC : S) {
118881ad6265SDimitry Andric           if (AC.first.getPointer() != Ptr)
1189*0b57cec5SDimitry Andric             continue;
1190*0b57cec5SDimitry Andric 
119181ad6265SDimitry Andric           bool IsWrite = AC.first.getInt();
1192*0b57cec5SDimitry Andric 
1193*0b57cec5SDimitry Andric           // If we're using the deferred access set, then it contains only
1194*0b57cec5SDimitry Andric           // reads.
1195*0b57cec5SDimitry Andric           bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
1196*0b57cec5SDimitry Andric           if (UseDeferred && !IsReadOnlyPtr)
1197*0b57cec5SDimitry Andric             continue;
1198*0b57cec5SDimitry Andric           // Otherwise, the pointer must be in the PtrAccessSet, either as a
1199*0b57cec5SDimitry Andric           // read or a write.
1200*0b57cec5SDimitry Andric           assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
1201*0b57cec5SDimitry Andric                   S.count(MemAccessInfo(Ptr, false))) &&
1202*0b57cec5SDimitry Andric                  "Alias-set pointer not in the access set?");
1203*0b57cec5SDimitry Andric 
1204*0b57cec5SDimitry Andric           MemAccessInfo Access(Ptr, IsWrite);
1205*0b57cec5SDimitry Andric           DepCands.insert(Access);
1206*0b57cec5SDimitry Andric 
1207*0b57cec5SDimitry Andric           // Memorize read-only pointers for later processing and skip them in
1208*0b57cec5SDimitry Andric           // the first round (they need to be checked after we have seen all
1209*0b57cec5SDimitry Andric           // write pointers). Note: we also mark pointer that are not
1210*0b57cec5SDimitry Andric           // consecutive as "read-only" pointers (so that we check
1211*0b57cec5SDimitry Andric           // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
1212*0b57cec5SDimitry Andric           if (!UseDeferred && IsReadOnlyPtr) {
121381ad6265SDimitry Andric             // We only use the pointer keys, the types vector values don't
121481ad6265SDimitry Andric             // matter.
121581ad6265SDimitry Andric             DeferredAccesses.insert({Access, {}});
1216*0b57cec5SDimitry Andric             continue;
1217*0b57cec5SDimitry Andric           }
1218*0b57cec5SDimitry Andric 
1219*0b57cec5SDimitry Andric           // If this is a write - check other reads and writes for conflicts. If
1220*0b57cec5SDimitry Andric           // this is a read only check other writes for conflicts (but only if
1221*0b57cec5SDimitry Andric           // there is no other write to the ptr - this is an optimization to
1222*0b57cec5SDimitry Andric           // catch "a[i] = a[i] + " without having to do a dependence check).
1223*0b57cec5SDimitry Andric           if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
1224*0b57cec5SDimitry Andric             CheckDeps.push_back(Access);
1225*0b57cec5SDimitry Andric             IsRTCheckAnalysisNeeded = true;
1226*0b57cec5SDimitry Andric           }
1227*0b57cec5SDimitry Andric 
1228*0b57cec5SDimitry Andric           if (IsWrite)
1229*0b57cec5SDimitry Andric             SetHasWrite = true;
1230*0b57cec5SDimitry Andric 
1231*0b57cec5SDimitry Andric           // Create sets of pointers connected by a shared alias set and
1232*0b57cec5SDimitry Andric           // underlying object.
1233*0b57cec5SDimitry Andric           typedef SmallVector<const Value *, 16> ValueVector;
1234*0b57cec5SDimitry Andric           ValueVector TempObjects;
1235*0b57cec5SDimitry Andric 
1236e8d8bef9SDimitry Andric           getUnderlyingObjects(Ptr, TempObjects, LI);
1237*0b57cec5SDimitry Andric           LLVM_DEBUG(dbgs()
1238*0b57cec5SDimitry Andric                      << "Underlying objects for pointer " << *Ptr << "\n");
1239*0b57cec5SDimitry Andric           for (const Value *UnderlyingObj : TempObjects) {
1240*0b57cec5SDimitry Andric             // nullptr never alias, don't join sets for pointer that have "null"
1241*0b57cec5SDimitry Andric             // in their UnderlyingObjects list.
1242*0b57cec5SDimitry Andric             if (isa<ConstantPointerNull>(UnderlyingObj) &&
1243*0b57cec5SDimitry Andric                 !NullPointerIsDefined(
1244*0b57cec5SDimitry Andric                     TheLoop->getHeader()->getParent(),
1245*0b57cec5SDimitry Andric                     UnderlyingObj->getType()->getPointerAddressSpace()))
1246*0b57cec5SDimitry Andric               continue;
1247*0b57cec5SDimitry Andric 
1248*0b57cec5SDimitry Andric             UnderlyingObjToAccessMap::iterator Prev =
1249*0b57cec5SDimitry Andric                 ObjToLastAccess.find(UnderlyingObj);
1250*0b57cec5SDimitry Andric             if (Prev != ObjToLastAccess.end())
1251*0b57cec5SDimitry Andric               DepCands.unionSets(Access, Prev->second);
1252*0b57cec5SDimitry Andric 
1253*0b57cec5SDimitry Andric             ObjToLastAccess[UnderlyingObj] = Access;
1254*0b57cec5SDimitry Andric             LLVM_DEBUG(dbgs() << "  " << *UnderlyingObj << "\n");
1255*0b57cec5SDimitry Andric           }
1256*0b57cec5SDimitry Andric         }
1257*0b57cec5SDimitry Andric       }
1258*0b57cec5SDimitry Andric     }
1259*0b57cec5SDimitry Andric   }
1260*0b57cec5SDimitry Andric }
1261*0b57cec5SDimitry Andric 
1262*0b57cec5SDimitry Andric static bool isInBoundsGep(Value *Ptr) {
1263*0b57cec5SDimitry Andric   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
1264*0b57cec5SDimitry Andric     return GEP->isInBounds();
1265*0b57cec5SDimitry Andric   return false;
1266*0b57cec5SDimitry Andric }
1267*0b57cec5SDimitry Andric 
1268*0b57cec5SDimitry Andric /// Return true if an AddRec pointer \p Ptr is unsigned non-wrapping,
1269*0b57cec5SDimitry Andric /// i.e. monotonically increasing/decreasing.
1270*0b57cec5SDimitry Andric static bool isNoWrapAddRec(Value *Ptr, const SCEVAddRecExpr *AR,
1271*0b57cec5SDimitry Andric                            PredicatedScalarEvolution &PSE, const Loop *L) {
1272*0b57cec5SDimitry Andric   // FIXME: This should probably only return true for NUW.
1273*0b57cec5SDimitry Andric   if (AR->getNoWrapFlags(SCEV::NoWrapMask))
1274*0b57cec5SDimitry Andric     return true;
1275*0b57cec5SDimitry Andric 
1276*0b57cec5SDimitry Andric   // Scalar evolution does not propagate the non-wrapping flags to values that
1277*0b57cec5SDimitry Andric   // are derived from a non-wrapping induction variable because non-wrapping
1278*0b57cec5SDimitry Andric   // could be flow-sensitive.
1279*0b57cec5SDimitry Andric   //
1280*0b57cec5SDimitry Andric   // Look through the potentially overflowing instruction to try to prove
1281*0b57cec5SDimitry Andric   // non-wrapping for the *specific* value of Ptr.
1282*0b57cec5SDimitry Andric 
1283*0b57cec5SDimitry Andric   // The arithmetic implied by an inbounds GEP can't overflow.
1284*0b57cec5SDimitry Andric   auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
1285*0b57cec5SDimitry Andric   if (!GEP || !GEP->isInBounds())
1286*0b57cec5SDimitry Andric     return false;
1287*0b57cec5SDimitry Andric 
1288*0b57cec5SDimitry Andric   // Make sure there is only one non-const index and analyze that.
1289*0b57cec5SDimitry Andric   Value *NonConstIndex = nullptr;
1290e8d8bef9SDimitry Andric   for (Value *Index : GEP->indices())
1291*0b57cec5SDimitry Andric     if (!isa<ConstantInt>(Index)) {
1292*0b57cec5SDimitry Andric       if (NonConstIndex)
1293*0b57cec5SDimitry Andric         return false;
1294*0b57cec5SDimitry Andric       NonConstIndex = Index;
1295*0b57cec5SDimitry Andric     }
1296*0b57cec5SDimitry Andric   if (!NonConstIndex)
1297*0b57cec5SDimitry Andric     // The recurrence is on the pointer, ignore for now.
1298*0b57cec5SDimitry Andric     return false;
1299*0b57cec5SDimitry Andric 
1300*0b57cec5SDimitry Andric   // The index in GEP is signed.  It is non-wrapping if it's derived from a NSW
1301*0b57cec5SDimitry Andric   // AddRec using a NSW operation.
1302*0b57cec5SDimitry Andric   if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(NonConstIndex))
1303*0b57cec5SDimitry Andric     if (OBO->hasNoSignedWrap() &&
1304*0b57cec5SDimitry Andric         // Assume constant for other the operand so that the AddRec can be
1305*0b57cec5SDimitry Andric         // easily found.
1306*0b57cec5SDimitry Andric         isa<ConstantInt>(OBO->getOperand(1))) {
1307*0b57cec5SDimitry Andric       auto *OpScev = PSE.getSCEV(OBO->getOperand(0));
1308*0b57cec5SDimitry Andric 
1309*0b57cec5SDimitry Andric       if (auto *OpAR = dyn_cast<SCEVAddRecExpr>(OpScev))
1310*0b57cec5SDimitry Andric         return OpAR->getLoop() == L && OpAR->getNoWrapFlags(SCEV::FlagNSW);
1311*0b57cec5SDimitry Andric     }
1312*0b57cec5SDimitry Andric 
1313*0b57cec5SDimitry Andric   return false;
1314*0b57cec5SDimitry Andric }
1315*0b57cec5SDimitry Andric 
1316*0b57cec5SDimitry Andric /// Check whether the access through \p Ptr has a constant stride.
1317349cc55cSDimitry Andric int64_t llvm::getPtrStride(PredicatedScalarEvolution &PSE, Type *AccessTy,
1318349cc55cSDimitry Andric                            Value *Ptr, const Loop *Lp,
1319349cc55cSDimitry Andric                            const ValueToValueMap &StridesMap, bool Assume,
1320349cc55cSDimitry Andric                            bool ShouldCheckWrap) {
1321*0b57cec5SDimitry Andric   Type *Ty = Ptr->getType();
1322*0b57cec5SDimitry Andric   assert(Ty->isPointerTy() && "Unexpected non-ptr");
1323*0b57cec5SDimitry Andric 
13244824e7fdSDimitry Andric   if (isa<ScalableVectorType>(AccessTy)) {
13254824e7fdSDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Bad stride - Scalable object: " << *AccessTy
13264824e7fdSDimitry Andric                       << "\n");
1327*0b57cec5SDimitry Andric     return 0;
1328*0b57cec5SDimitry Andric   }
1329*0b57cec5SDimitry Andric 
1330*0b57cec5SDimitry Andric   const SCEV *PtrScev = replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr);
1331*0b57cec5SDimitry Andric 
1332*0b57cec5SDimitry Andric   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
1333*0b57cec5SDimitry Andric   if (Assume && !AR)
1334*0b57cec5SDimitry Andric     AR = PSE.getAsAddRec(Ptr);
1335*0b57cec5SDimitry Andric 
1336*0b57cec5SDimitry Andric   if (!AR) {
1337*0b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer " << *Ptr
1338*0b57cec5SDimitry Andric                       << " SCEV: " << *PtrScev << "\n");
1339*0b57cec5SDimitry Andric     return 0;
1340*0b57cec5SDimitry Andric   }
1341*0b57cec5SDimitry Andric 
1342*0b57cec5SDimitry Andric   // The access function must stride over the innermost loop.
1343*0b57cec5SDimitry Andric   if (Lp != AR->getLoop()) {
1344*0b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop "
1345*0b57cec5SDimitry Andric                       << *Ptr << " SCEV: " << *AR << "\n");
1346*0b57cec5SDimitry Andric     return 0;
1347*0b57cec5SDimitry Andric   }
1348*0b57cec5SDimitry Andric 
1349*0b57cec5SDimitry Andric   // The address calculation must not wrap. Otherwise, a dependence could be
1350*0b57cec5SDimitry Andric   // inverted.
1351*0b57cec5SDimitry Andric   // An inbounds getelementptr that is a AddRec with a unit stride
1352*0b57cec5SDimitry Andric   // cannot wrap per definition. The unit stride requirement is checked later.
1353*0b57cec5SDimitry Andric   // An getelementptr without an inbounds attribute and unit stride would have
1354*0b57cec5SDimitry Andric   // to access the pointer value "0" which is undefined behavior in address
1355*0b57cec5SDimitry Andric   // space 0, therefore we can also vectorize this case.
13564824e7fdSDimitry Andric   unsigned AddrSpace = Ty->getPointerAddressSpace();
1357*0b57cec5SDimitry Andric   bool IsInBoundsGEP = isInBoundsGep(Ptr);
1358*0b57cec5SDimitry Andric   bool IsNoWrapAddRec = !ShouldCheckWrap ||
1359*0b57cec5SDimitry Andric     PSE.hasNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW) ||
1360*0b57cec5SDimitry Andric     isNoWrapAddRec(Ptr, AR, PSE, Lp);
1361*0b57cec5SDimitry Andric   if (!IsNoWrapAddRec && !IsInBoundsGEP &&
1362349cc55cSDimitry Andric       NullPointerIsDefined(Lp->getHeader()->getParent(), AddrSpace)) {
1363*0b57cec5SDimitry Andric     if (Assume) {
1364*0b57cec5SDimitry Andric       PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
1365*0b57cec5SDimitry Andric       IsNoWrapAddRec = true;
1366*0b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "LAA: Pointer may wrap in the address space:\n"
1367*0b57cec5SDimitry Andric                         << "LAA:   Pointer: " << *Ptr << "\n"
1368*0b57cec5SDimitry Andric                         << "LAA:   SCEV: " << *AR << "\n"
1369*0b57cec5SDimitry Andric                         << "LAA:   Added an overflow assumption\n");
1370*0b57cec5SDimitry Andric     } else {
1371*0b57cec5SDimitry Andric       LLVM_DEBUG(
1372*0b57cec5SDimitry Andric           dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
1373*0b57cec5SDimitry Andric                  << *Ptr << " SCEV: " << *AR << "\n");
1374*0b57cec5SDimitry Andric       return 0;
1375*0b57cec5SDimitry Andric     }
1376*0b57cec5SDimitry Andric   }
1377*0b57cec5SDimitry Andric 
1378*0b57cec5SDimitry Andric   // Check the step is constant.
1379*0b57cec5SDimitry Andric   const SCEV *Step = AR->getStepRecurrence(*PSE.getSE());
1380*0b57cec5SDimitry Andric 
1381*0b57cec5SDimitry Andric   // Calculate the pointer stride and check if it is constant.
1382*0b57cec5SDimitry Andric   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
1383*0b57cec5SDimitry Andric   if (!C) {
1384*0b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr
1385*0b57cec5SDimitry Andric                       << " SCEV: " << *AR << "\n");
1386*0b57cec5SDimitry Andric     return 0;
1387*0b57cec5SDimitry Andric   }
1388*0b57cec5SDimitry Andric 
1389*0b57cec5SDimitry Andric   auto &DL = Lp->getHeader()->getModule()->getDataLayout();
13904824e7fdSDimitry Andric   TypeSize AllocSize = DL.getTypeAllocSize(AccessTy);
13914824e7fdSDimitry Andric   int64_t Size = AllocSize.getFixedSize();
1392*0b57cec5SDimitry Andric   const APInt &APStepVal = C->getAPInt();
1393*0b57cec5SDimitry Andric 
1394*0b57cec5SDimitry Andric   // Huge step value - give up.
1395*0b57cec5SDimitry Andric   if (APStepVal.getBitWidth() > 64)
1396*0b57cec5SDimitry Andric     return 0;
1397*0b57cec5SDimitry Andric 
1398*0b57cec5SDimitry Andric   int64_t StepVal = APStepVal.getSExtValue();
1399*0b57cec5SDimitry Andric 
1400*0b57cec5SDimitry Andric   // Strided access.
1401*0b57cec5SDimitry Andric   int64_t Stride = StepVal / Size;
1402*0b57cec5SDimitry Andric   int64_t Rem = StepVal % Size;
1403*0b57cec5SDimitry Andric   if (Rem)
1404*0b57cec5SDimitry Andric     return 0;
1405*0b57cec5SDimitry Andric 
1406*0b57cec5SDimitry Andric   // If the SCEV could wrap but we have an inbounds gep with a unit stride we
1407*0b57cec5SDimitry Andric   // know we can't "wrap around the address space". In case of address space
1408*0b57cec5SDimitry Andric   // zero we know that this won't happen without triggering undefined behavior.
1409*0b57cec5SDimitry Andric   if (!IsNoWrapAddRec && Stride != 1 && Stride != -1 &&
1410*0b57cec5SDimitry Andric       (IsInBoundsGEP || !NullPointerIsDefined(Lp->getHeader()->getParent(),
1411349cc55cSDimitry Andric                                               AddrSpace))) {
1412*0b57cec5SDimitry Andric     if (Assume) {
1413*0b57cec5SDimitry Andric       // We can avoid this case by adding a run-time check.
1414*0b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "LAA: Non unit strided pointer which is not either "
1415*0b57cec5SDimitry Andric                         << "inbounds or in address space 0 may wrap:\n"
1416*0b57cec5SDimitry Andric                         << "LAA:   Pointer: " << *Ptr << "\n"
1417*0b57cec5SDimitry Andric                         << "LAA:   SCEV: " << *AR << "\n"
1418*0b57cec5SDimitry Andric                         << "LAA:   Added an overflow assumption\n");
1419*0b57cec5SDimitry Andric       PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
1420*0b57cec5SDimitry Andric     } else
1421*0b57cec5SDimitry Andric       return 0;
1422*0b57cec5SDimitry Andric   }
1423*0b57cec5SDimitry Andric 
1424*0b57cec5SDimitry Andric   return Stride;
1425*0b57cec5SDimitry Andric }
1426*0b57cec5SDimitry Andric 
1427fe6060f1SDimitry Andric Optional<int> llvm::getPointersDiff(Type *ElemTyA, Value *PtrA, Type *ElemTyB,
1428fe6060f1SDimitry Andric                                     Value *PtrB, const DataLayout &DL,
1429fe6060f1SDimitry Andric                                     ScalarEvolution &SE, bool StrictCheck,
1430fe6060f1SDimitry Andric                                     bool CheckType) {
1431fe6060f1SDimitry Andric   assert(PtrA && PtrB && "Expected non-nullptr pointers.");
1432fe6060f1SDimitry Andric   assert(cast<PointerType>(PtrA->getType())
1433fe6060f1SDimitry Andric              ->isOpaqueOrPointeeTypeMatches(ElemTyA) && "Wrong PtrA type");
1434fe6060f1SDimitry Andric   assert(cast<PointerType>(PtrB->getType())
1435fe6060f1SDimitry Andric              ->isOpaqueOrPointeeTypeMatches(ElemTyB) && "Wrong PtrB type");
1436fe6060f1SDimitry Andric 
1437fe6060f1SDimitry Andric   // Make sure that A and B are different pointers.
1438fe6060f1SDimitry Andric   if (PtrA == PtrB)
1439fe6060f1SDimitry Andric     return 0;
1440fe6060f1SDimitry Andric 
1441fe6060f1SDimitry Andric   // Make sure that the element types are the same if required.
1442fe6060f1SDimitry Andric   if (CheckType && ElemTyA != ElemTyB)
1443fe6060f1SDimitry Andric     return None;
1444fe6060f1SDimitry Andric 
1445fe6060f1SDimitry Andric   unsigned ASA = PtrA->getType()->getPointerAddressSpace();
1446fe6060f1SDimitry Andric   unsigned ASB = PtrB->getType()->getPointerAddressSpace();
1447fe6060f1SDimitry Andric 
1448fe6060f1SDimitry Andric   // Check that the address spaces match.
1449fe6060f1SDimitry Andric   if (ASA != ASB)
1450fe6060f1SDimitry Andric     return None;
1451fe6060f1SDimitry Andric   unsigned IdxWidth = DL.getIndexSizeInBits(ASA);
1452fe6060f1SDimitry Andric 
1453fe6060f1SDimitry Andric   APInt OffsetA(IdxWidth, 0), OffsetB(IdxWidth, 0);
1454fe6060f1SDimitry Andric   Value *PtrA1 = PtrA->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetA);
1455fe6060f1SDimitry Andric   Value *PtrB1 = PtrB->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetB);
1456fe6060f1SDimitry Andric 
1457fe6060f1SDimitry Andric   int Val;
1458fe6060f1SDimitry Andric   if (PtrA1 == PtrB1) {
1459fe6060f1SDimitry Andric     // Retrieve the address space again as pointer stripping now tracks through
1460fe6060f1SDimitry Andric     // `addrspacecast`.
1461fe6060f1SDimitry Andric     ASA = cast<PointerType>(PtrA1->getType())->getAddressSpace();
1462fe6060f1SDimitry Andric     ASB = cast<PointerType>(PtrB1->getType())->getAddressSpace();
1463fe6060f1SDimitry Andric     // Check that the address spaces match and that the pointers are valid.
1464fe6060f1SDimitry Andric     if (ASA != ASB)
1465fe6060f1SDimitry Andric       return None;
1466fe6060f1SDimitry Andric 
1467fe6060f1SDimitry Andric     IdxWidth = DL.getIndexSizeInBits(ASA);
1468fe6060f1SDimitry Andric     OffsetA = OffsetA.sextOrTrunc(IdxWidth);
1469fe6060f1SDimitry Andric     OffsetB = OffsetB.sextOrTrunc(IdxWidth);
1470fe6060f1SDimitry Andric 
1471fe6060f1SDimitry Andric     OffsetB -= OffsetA;
1472fe6060f1SDimitry Andric     Val = OffsetB.getSExtValue();
1473fe6060f1SDimitry Andric   } else {
1474fe6060f1SDimitry Andric     // Otherwise compute the distance with SCEV between the base pointers.
1475fe6060f1SDimitry Andric     const SCEV *PtrSCEVA = SE.getSCEV(PtrA);
1476fe6060f1SDimitry Andric     const SCEV *PtrSCEVB = SE.getSCEV(PtrB);
1477fe6060f1SDimitry Andric     const auto *Diff =
1478fe6060f1SDimitry Andric         dyn_cast<SCEVConstant>(SE.getMinusSCEV(PtrSCEVB, PtrSCEVA));
1479fe6060f1SDimitry Andric     if (!Diff)
1480fe6060f1SDimitry Andric       return None;
1481fe6060f1SDimitry Andric     Val = Diff->getAPInt().getSExtValue();
1482fe6060f1SDimitry Andric   }
1483fe6060f1SDimitry Andric   int Size = DL.getTypeStoreSize(ElemTyA);
1484fe6060f1SDimitry Andric   int Dist = Val / Size;
1485fe6060f1SDimitry Andric 
1486fe6060f1SDimitry Andric   // Ensure that the calculated distance matches the type-based one after all
1487fe6060f1SDimitry Andric   // the bitcasts removal in the provided pointers.
1488fe6060f1SDimitry Andric   if (!StrictCheck || Dist * Size == Val)
1489fe6060f1SDimitry Andric     return Dist;
1490fe6060f1SDimitry Andric   return None;
1491fe6060f1SDimitry Andric }
1492fe6060f1SDimitry Andric 
1493fe6060f1SDimitry Andric bool llvm::sortPtrAccesses(ArrayRef<Value *> VL, Type *ElemTy,
1494fe6060f1SDimitry Andric                            const DataLayout &DL, ScalarEvolution &SE,
1495*0b57cec5SDimitry Andric                            SmallVectorImpl<unsigned> &SortedIndices) {
1496*0b57cec5SDimitry Andric   assert(llvm::all_of(
1497*0b57cec5SDimitry Andric              VL, [](const Value *V) { return V->getType()->isPointerTy(); }) &&
1498*0b57cec5SDimitry Andric          "Expected list of pointer operands.");
1499*0b57cec5SDimitry Andric   // Walk over the pointers, and map each of them to an offset relative to
1500*0b57cec5SDimitry Andric   // first pointer in the array.
1501*0b57cec5SDimitry Andric   Value *Ptr0 = VL[0];
1502*0b57cec5SDimitry Andric 
1503fe6060f1SDimitry Andric   using DistOrdPair = std::pair<int64_t, int>;
1504972a253aSDimitry Andric   auto Compare = llvm::less_first();
1505fe6060f1SDimitry Andric   std::set<DistOrdPair, decltype(Compare)> Offsets(Compare);
1506fe6060f1SDimitry Andric   Offsets.emplace(0, 0);
1507fe6060f1SDimitry Andric   int Cnt = 1;
1508fe6060f1SDimitry Andric   bool IsConsecutive = true;
1509fe6060f1SDimitry Andric   for (auto *Ptr : VL.drop_front()) {
1510fe6060f1SDimitry Andric     Optional<int> Diff = getPointersDiff(ElemTy, Ptr0, ElemTy, Ptr, DL, SE,
1511fe6060f1SDimitry Andric                                          /*StrictCheck=*/true);
1512*0b57cec5SDimitry Andric     if (!Diff)
1513*0b57cec5SDimitry Andric       return false;
1514*0b57cec5SDimitry Andric 
1515*0b57cec5SDimitry Andric     // Check if the pointer with the same offset is found.
1516fe6060f1SDimitry Andric     int64_t Offset = *Diff;
1517fe6060f1SDimitry Andric     auto Res = Offsets.emplace(Offset, Cnt);
1518fe6060f1SDimitry Andric     if (!Res.second)
1519*0b57cec5SDimitry Andric       return false;
1520fe6060f1SDimitry Andric     // Consecutive order if the inserted element is the last one.
1521fe6060f1SDimitry Andric     IsConsecutive = IsConsecutive && std::next(Res.first) == Offsets.end();
1522fe6060f1SDimitry Andric     ++Cnt;
1523*0b57cec5SDimitry Andric   }
1524*0b57cec5SDimitry Andric   SortedIndices.clear();
1525fe6060f1SDimitry Andric   if (!IsConsecutive) {
1526fe6060f1SDimitry Andric     // Fill SortedIndices array only if it is non-consecutive.
1527*0b57cec5SDimitry Andric     SortedIndices.resize(VL.size());
1528fe6060f1SDimitry Andric     Cnt = 0;
1529fe6060f1SDimitry Andric     for (const std::pair<int64_t, int> &Pair : Offsets) {
1530fe6060f1SDimitry Andric       SortedIndices[Cnt] = Pair.second;
1531fe6060f1SDimitry Andric       ++Cnt;
1532*0b57cec5SDimitry Andric     }
1533fe6060f1SDimitry Andric   }
1534fe6060f1SDimitry Andric   return true;
1535*0b57cec5SDimitry Andric }
1536*0b57cec5SDimitry Andric 
1537*0b57cec5SDimitry Andric /// Returns true if the memory operations \p A and \p B are consecutive.
1538*0b57cec5SDimitry Andric bool llvm::isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL,
1539*0b57cec5SDimitry Andric                                ScalarEvolution &SE, bool CheckType) {
1540*0b57cec5SDimitry Andric   Value *PtrA = getLoadStorePointerOperand(A);
1541*0b57cec5SDimitry Andric   Value *PtrB = getLoadStorePointerOperand(B);
1542fe6060f1SDimitry Andric   if (!PtrA || !PtrB)
1543*0b57cec5SDimitry Andric     return false;
1544fe6060f1SDimitry Andric   Type *ElemTyA = getLoadStoreType(A);
1545fe6060f1SDimitry Andric   Type *ElemTyB = getLoadStoreType(B);
1546fe6060f1SDimitry Andric   Optional<int> Diff = getPointersDiff(ElemTyA, PtrA, ElemTyB, PtrB, DL, SE,
1547fe6060f1SDimitry Andric                                        /*StrictCheck=*/true, CheckType);
1548fe6060f1SDimitry Andric   return Diff && *Diff == 1;
1549*0b57cec5SDimitry Andric }
1550*0b57cec5SDimitry Andric 
1551349cc55cSDimitry Andric void MemoryDepChecker::addAccess(StoreInst *SI) {
1552349cc55cSDimitry Andric   visitPointers(SI->getPointerOperand(), *InnermostLoop,
1553349cc55cSDimitry Andric                 [this, SI](Value *Ptr) {
1554349cc55cSDimitry Andric                   Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
1555349cc55cSDimitry Andric                   InstMap.push_back(SI);
1556349cc55cSDimitry Andric                   ++AccessIdx;
1557349cc55cSDimitry Andric                 });
1558349cc55cSDimitry Andric }
1559349cc55cSDimitry Andric 
1560349cc55cSDimitry Andric void MemoryDepChecker::addAccess(LoadInst *LI) {
1561349cc55cSDimitry Andric   visitPointers(LI->getPointerOperand(), *InnermostLoop,
1562349cc55cSDimitry Andric                 [this, LI](Value *Ptr) {
1563349cc55cSDimitry Andric                   Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
1564349cc55cSDimitry Andric                   InstMap.push_back(LI);
1565349cc55cSDimitry Andric                   ++AccessIdx;
1566349cc55cSDimitry Andric                 });
1567349cc55cSDimitry Andric }
1568349cc55cSDimitry Andric 
1569*0b57cec5SDimitry Andric MemoryDepChecker::VectorizationSafetyStatus
1570*0b57cec5SDimitry Andric MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
1571*0b57cec5SDimitry Andric   switch (Type) {
1572*0b57cec5SDimitry Andric   case NoDep:
1573*0b57cec5SDimitry Andric   case Forward:
1574*0b57cec5SDimitry Andric   case BackwardVectorizable:
1575*0b57cec5SDimitry Andric     return VectorizationSafetyStatus::Safe;
1576*0b57cec5SDimitry Andric 
1577*0b57cec5SDimitry Andric   case Unknown:
1578*0b57cec5SDimitry Andric     return VectorizationSafetyStatus::PossiblySafeWithRtChecks;
1579*0b57cec5SDimitry Andric   case ForwardButPreventsForwarding:
1580*0b57cec5SDimitry Andric   case Backward:
1581*0b57cec5SDimitry Andric   case BackwardVectorizableButPreventsForwarding:
1582*0b57cec5SDimitry Andric     return VectorizationSafetyStatus::Unsafe;
1583*0b57cec5SDimitry Andric   }
1584*0b57cec5SDimitry Andric   llvm_unreachable("unexpected DepType!");
1585*0b57cec5SDimitry Andric }
1586*0b57cec5SDimitry Andric 
1587*0b57cec5SDimitry Andric bool MemoryDepChecker::Dependence::isBackward() const {
1588*0b57cec5SDimitry Andric   switch (Type) {
1589*0b57cec5SDimitry Andric   case NoDep:
1590*0b57cec5SDimitry Andric   case Forward:
1591*0b57cec5SDimitry Andric   case ForwardButPreventsForwarding:
1592*0b57cec5SDimitry Andric   case Unknown:
1593*0b57cec5SDimitry Andric     return false;
1594*0b57cec5SDimitry Andric 
1595*0b57cec5SDimitry Andric   case BackwardVectorizable:
1596*0b57cec5SDimitry Andric   case Backward:
1597*0b57cec5SDimitry Andric   case BackwardVectorizableButPreventsForwarding:
1598*0b57cec5SDimitry Andric     return true;
1599*0b57cec5SDimitry Andric   }
1600*0b57cec5SDimitry Andric   llvm_unreachable("unexpected DepType!");
1601*0b57cec5SDimitry Andric }
1602*0b57cec5SDimitry Andric 
1603*0b57cec5SDimitry Andric bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
1604*0b57cec5SDimitry Andric   return isBackward() || Type == Unknown;
1605*0b57cec5SDimitry Andric }
1606*0b57cec5SDimitry Andric 
1607*0b57cec5SDimitry Andric bool MemoryDepChecker::Dependence::isForward() const {
1608*0b57cec5SDimitry Andric   switch (Type) {
1609*0b57cec5SDimitry Andric   case Forward:
1610*0b57cec5SDimitry Andric   case ForwardButPreventsForwarding:
1611*0b57cec5SDimitry Andric     return true;
1612*0b57cec5SDimitry Andric 
1613*0b57cec5SDimitry Andric   case NoDep:
1614*0b57cec5SDimitry Andric   case Unknown:
1615*0b57cec5SDimitry Andric   case BackwardVectorizable:
1616*0b57cec5SDimitry Andric   case Backward:
1617*0b57cec5SDimitry Andric   case BackwardVectorizableButPreventsForwarding:
1618*0b57cec5SDimitry Andric     return false;
1619*0b57cec5SDimitry Andric   }
1620*0b57cec5SDimitry Andric   llvm_unreachable("unexpected DepType!");
1621*0b57cec5SDimitry Andric }
1622*0b57cec5SDimitry Andric 
1623*0b57cec5SDimitry Andric bool MemoryDepChecker::couldPreventStoreLoadForward(uint64_t Distance,
1624*0b57cec5SDimitry Andric                                                     uint64_t TypeByteSize) {
1625*0b57cec5SDimitry Andric   // If loads occur at a distance that is not a multiple of a feasible vector
1626*0b57cec5SDimitry Andric   // factor store-load forwarding does not take place.
1627*0b57cec5SDimitry Andric   // Positive dependences might cause troubles because vectorizing them might
1628*0b57cec5SDimitry Andric   // prevent store-load forwarding making vectorized code run a lot slower.
1629*0b57cec5SDimitry Andric   //   a[i] = a[i-3] ^ a[i-8];
1630*0b57cec5SDimitry Andric   //   The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
1631*0b57cec5SDimitry Andric   //   hence on your typical architecture store-load forwarding does not take
1632*0b57cec5SDimitry Andric   //   place. Vectorizing in such cases does not make sense.
1633*0b57cec5SDimitry Andric   // Store-load forwarding distance.
1634*0b57cec5SDimitry Andric 
1635*0b57cec5SDimitry Andric   // After this many iterations store-to-load forwarding conflicts should not
1636*0b57cec5SDimitry Andric   // cause any slowdowns.
1637*0b57cec5SDimitry Andric   const uint64_t NumItersForStoreLoadThroughMemory = 8 * TypeByteSize;
1638*0b57cec5SDimitry Andric   // Maximum vector factor.
1639*0b57cec5SDimitry Andric   uint64_t MaxVFWithoutSLForwardIssues = std::min(
1640*0b57cec5SDimitry Andric       VectorizerParams::MaxVectorWidth * TypeByteSize, MaxSafeDepDistBytes);
1641*0b57cec5SDimitry Andric 
1642*0b57cec5SDimitry Andric   // Compute the smallest VF at which the store and load would be misaligned.
1643*0b57cec5SDimitry Andric   for (uint64_t VF = 2 * TypeByteSize; VF <= MaxVFWithoutSLForwardIssues;
1644*0b57cec5SDimitry Andric        VF *= 2) {
1645*0b57cec5SDimitry Andric     // If the number of vector iteration between the store and the load are
1646*0b57cec5SDimitry Andric     // small we could incur conflicts.
1647*0b57cec5SDimitry Andric     if (Distance % VF && Distance / VF < NumItersForStoreLoadThroughMemory) {
1648e8d8bef9SDimitry Andric       MaxVFWithoutSLForwardIssues = (VF >> 1);
1649*0b57cec5SDimitry Andric       break;
1650*0b57cec5SDimitry Andric     }
1651*0b57cec5SDimitry Andric   }
1652*0b57cec5SDimitry Andric 
1653*0b57cec5SDimitry Andric   if (MaxVFWithoutSLForwardIssues < 2 * TypeByteSize) {
1654*0b57cec5SDimitry Andric     LLVM_DEBUG(
1655*0b57cec5SDimitry Andric         dbgs() << "LAA: Distance " << Distance
1656*0b57cec5SDimitry Andric                << " that could cause a store-load forwarding conflict\n");
1657*0b57cec5SDimitry Andric     return true;
1658*0b57cec5SDimitry Andric   }
1659*0b57cec5SDimitry Andric 
1660*0b57cec5SDimitry Andric   if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
1661*0b57cec5SDimitry Andric       MaxVFWithoutSLForwardIssues !=
1662*0b57cec5SDimitry Andric           VectorizerParams::MaxVectorWidth * TypeByteSize)
1663*0b57cec5SDimitry Andric     MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
1664*0b57cec5SDimitry Andric   return false;
1665*0b57cec5SDimitry Andric }
1666*0b57cec5SDimitry Andric 
1667*0b57cec5SDimitry Andric void MemoryDepChecker::mergeInStatus(VectorizationSafetyStatus S) {
1668*0b57cec5SDimitry Andric   if (Status < S)
1669*0b57cec5SDimitry Andric     Status = S;
1670*0b57cec5SDimitry Andric }
1671*0b57cec5SDimitry Andric 
1672*0b57cec5SDimitry Andric /// Given a non-constant (unknown) dependence-distance \p Dist between two
1673*0b57cec5SDimitry Andric /// memory accesses, that have the same stride whose absolute value is given
1674*0b57cec5SDimitry Andric /// in \p Stride, and that have the same type size \p TypeByteSize,
1675*0b57cec5SDimitry Andric /// in a loop whose takenCount is \p BackedgeTakenCount, check if it is
1676*0b57cec5SDimitry Andric /// possible to prove statically that the dependence distance is larger
1677*0b57cec5SDimitry Andric /// than the range that the accesses will travel through the execution of
1678*0b57cec5SDimitry Andric /// the loop. If so, return true; false otherwise. This is useful for
1679*0b57cec5SDimitry Andric /// example in loops such as the following (PR31098):
1680*0b57cec5SDimitry Andric ///     for (i = 0; i < D; ++i) {
1681*0b57cec5SDimitry Andric ///                = out[i];
1682*0b57cec5SDimitry Andric ///       out[i+D] =
1683*0b57cec5SDimitry Andric ///     }
1684*0b57cec5SDimitry Andric static bool isSafeDependenceDistance(const DataLayout &DL, ScalarEvolution &SE,
1685*0b57cec5SDimitry Andric                                      const SCEV &BackedgeTakenCount,
1686*0b57cec5SDimitry Andric                                      const SCEV &Dist, uint64_t Stride,
1687*0b57cec5SDimitry Andric                                      uint64_t TypeByteSize) {
1688*0b57cec5SDimitry Andric 
1689*0b57cec5SDimitry Andric   // If we can prove that
1690*0b57cec5SDimitry Andric   //      (**) |Dist| > BackedgeTakenCount * Step
1691*0b57cec5SDimitry Andric   // where Step is the absolute stride of the memory accesses in bytes,
1692*0b57cec5SDimitry Andric   // then there is no dependence.
1693*0b57cec5SDimitry Andric   //
1694*0b57cec5SDimitry Andric   // Rationale:
1695*0b57cec5SDimitry Andric   // We basically want to check if the absolute distance (|Dist/Step|)
1696*0b57cec5SDimitry Andric   // is >= the loop iteration count (or > BackedgeTakenCount).
1697*0b57cec5SDimitry Andric   // This is equivalent to the Strong SIV Test (Practical Dependence Testing,
1698*0b57cec5SDimitry Andric   // Section 4.2.1); Note, that for vectorization it is sufficient to prove
1699*0b57cec5SDimitry Andric   // that the dependence distance is >= VF; This is checked elsewhere.
1700*0b57cec5SDimitry Andric   // But in some cases we can prune unknown dependence distances early, and
1701*0b57cec5SDimitry Andric   // even before selecting the VF, and without a runtime test, by comparing
1702*0b57cec5SDimitry Andric   // the distance against the loop iteration count. Since the vectorized code
1703*0b57cec5SDimitry Andric   // will be executed only if LoopCount >= VF, proving distance >= LoopCount
1704*0b57cec5SDimitry Andric   // also guarantees that distance >= VF.
1705*0b57cec5SDimitry Andric   //
1706*0b57cec5SDimitry Andric   const uint64_t ByteStride = Stride * TypeByteSize;
1707*0b57cec5SDimitry Andric   const SCEV *Step = SE.getConstant(BackedgeTakenCount.getType(), ByteStride);
1708*0b57cec5SDimitry Andric   const SCEV *Product = SE.getMulExpr(&BackedgeTakenCount, Step);
1709*0b57cec5SDimitry Andric 
1710*0b57cec5SDimitry Andric   const SCEV *CastedDist = &Dist;
1711*0b57cec5SDimitry Andric   const SCEV *CastedProduct = Product;
171281ad6265SDimitry Andric   uint64_t DistTypeSizeBits = DL.getTypeSizeInBits(Dist.getType());
171381ad6265SDimitry Andric   uint64_t ProductTypeSizeBits = DL.getTypeSizeInBits(Product->getType());
1714*0b57cec5SDimitry Andric 
1715*0b57cec5SDimitry Andric   // The dependence distance can be positive/negative, so we sign extend Dist;
1716*0b57cec5SDimitry Andric   // The multiplication of the absolute stride in bytes and the
1717*0b57cec5SDimitry Andric   // backedgeTakenCount is non-negative, so we zero extend Product.
171881ad6265SDimitry Andric   if (DistTypeSizeBits > ProductTypeSizeBits)
1719*0b57cec5SDimitry Andric     CastedProduct = SE.getZeroExtendExpr(Product, Dist.getType());
1720*0b57cec5SDimitry Andric   else
1721*0b57cec5SDimitry Andric     CastedDist = SE.getNoopOrSignExtend(&Dist, Product->getType());
1722*0b57cec5SDimitry Andric 
1723*0b57cec5SDimitry Andric   // Is  Dist - (BackedgeTakenCount * Step) > 0 ?
1724*0b57cec5SDimitry Andric   // (If so, then we have proven (**) because |Dist| >= Dist)
1725*0b57cec5SDimitry Andric   const SCEV *Minus = SE.getMinusSCEV(CastedDist, CastedProduct);
1726*0b57cec5SDimitry Andric   if (SE.isKnownPositive(Minus))
1727*0b57cec5SDimitry Andric     return true;
1728*0b57cec5SDimitry Andric 
1729*0b57cec5SDimitry Andric   // Second try: Is  -Dist - (BackedgeTakenCount * Step) > 0 ?
1730*0b57cec5SDimitry Andric   // (If so, then we have proven (**) because |Dist| >= -1*Dist)
1731*0b57cec5SDimitry Andric   const SCEV *NegDist = SE.getNegativeSCEV(CastedDist);
1732*0b57cec5SDimitry Andric   Minus = SE.getMinusSCEV(NegDist, CastedProduct);
1733*0b57cec5SDimitry Andric   if (SE.isKnownPositive(Minus))
1734*0b57cec5SDimitry Andric     return true;
1735*0b57cec5SDimitry Andric 
1736*0b57cec5SDimitry Andric   return false;
1737*0b57cec5SDimitry Andric }
1738*0b57cec5SDimitry Andric 
1739*0b57cec5SDimitry Andric /// Check the dependence for two accesses with the same stride \p Stride.
1740*0b57cec5SDimitry Andric /// \p Distance is the positive distance and \p TypeByteSize is type size in
1741*0b57cec5SDimitry Andric /// bytes.
1742*0b57cec5SDimitry Andric ///
1743*0b57cec5SDimitry Andric /// \returns true if they are independent.
1744*0b57cec5SDimitry Andric static bool areStridedAccessesIndependent(uint64_t Distance, uint64_t Stride,
1745*0b57cec5SDimitry Andric                                           uint64_t TypeByteSize) {
1746*0b57cec5SDimitry Andric   assert(Stride > 1 && "The stride must be greater than 1");
1747*0b57cec5SDimitry Andric   assert(TypeByteSize > 0 && "The type size in byte must be non-zero");
1748*0b57cec5SDimitry Andric   assert(Distance > 0 && "The distance must be non-zero");
1749*0b57cec5SDimitry Andric 
1750*0b57cec5SDimitry Andric   // Skip if the distance is not multiple of type byte size.
1751*0b57cec5SDimitry Andric   if (Distance % TypeByteSize)
1752*0b57cec5SDimitry Andric     return false;
1753*0b57cec5SDimitry Andric 
1754*0b57cec5SDimitry Andric   uint64_t ScaledDist = Distance / TypeByteSize;
1755*0b57cec5SDimitry Andric 
1756*0b57cec5SDimitry Andric   // No dependence if the scaled distance is not multiple of the stride.
1757*0b57cec5SDimitry Andric   // E.g.
1758*0b57cec5SDimitry Andric   //      for (i = 0; i < 1024 ; i += 4)
1759*0b57cec5SDimitry Andric   //        A[i+2] = A[i] + 1;
1760*0b57cec5SDimitry Andric   //
1761*0b57cec5SDimitry Andric   // Two accesses in memory (scaled distance is 2, stride is 4):
1762*0b57cec5SDimitry Andric   //     | A[0] |      |      |      | A[4] |      |      |      |
1763*0b57cec5SDimitry Andric   //     |      |      | A[2] |      |      |      | A[6] |      |
1764*0b57cec5SDimitry Andric   //
1765*0b57cec5SDimitry Andric   // E.g.
1766*0b57cec5SDimitry Andric   //      for (i = 0; i < 1024 ; i += 3)
1767*0b57cec5SDimitry Andric   //        A[i+4] = A[i] + 1;
1768*0b57cec5SDimitry Andric   //
1769*0b57cec5SDimitry Andric   // Two accesses in memory (scaled distance is 4, stride is 3):
1770*0b57cec5SDimitry Andric   //     | A[0] |      |      | A[3] |      |      | A[6] |      |      |
1771*0b57cec5SDimitry Andric   //     |      |      |      |      | A[4] |      |      | A[7] |      |
1772*0b57cec5SDimitry Andric   return ScaledDist % Stride;
1773*0b57cec5SDimitry Andric }
1774*0b57cec5SDimitry Andric 
1775*0b57cec5SDimitry Andric MemoryDepChecker::Dependence::DepType
1776*0b57cec5SDimitry Andric MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
1777*0b57cec5SDimitry Andric                               const MemAccessInfo &B, unsigned BIdx,
1778*0b57cec5SDimitry Andric                               const ValueToValueMap &Strides) {
1779*0b57cec5SDimitry Andric   assert (AIdx < BIdx && "Must pass arguments in program order");
1780*0b57cec5SDimitry Andric 
1781*0b57cec5SDimitry Andric   Value *APtr = A.getPointer();
1782*0b57cec5SDimitry Andric   Value *BPtr = B.getPointer();
1783*0b57cec5SDimitry Andric   bool AIsWrite = A.getInt();
1784*0b57cec5SDimitry Andric   bool BIsWrite = B.getInt();
178581ad6265SDimitry Andric   Type *ATy = getLoadStoreType(InstMap[AIdx]);
178681ad6265SDimitry Andric   Type *BTy = getLoadStoreType(InstMap[BIdx]);
1787*0b57cec5SDimitry Andric 
1788*0b57cec5SDimitry Andric   // Two reads are independent.
1789*0b57cec5SDimitry Andric   if (!AIsWrite && !BIsWrite)
1790*0b57cec5SDimitry Andric     return Dependence::NoDep;
1791*0b57cec5SDimitry Andric 
1792*0b57cec5SDimitry Andric   // We cannot check pointers in different address spaces.
1793*0b57cec5SDimitry Andric   if (APtr->getType()->getPointerAddressSpace() !=
1794*0b57cec5SDimitry Andric       BPtr->getType()->getPointerAddressSpace())
1795*0b57cec5SDimitry Andric     return Dependence::Unknown;
1796*0b57cec5SDimitry Andric 
1797349cc55cSDimitry Andric   int64_t StrideAPtr =
1798349cc55cSDimitry Andric       getPtrStride(PSE, ATy, APtr, InnermostLoop, Strides, true);
1799349cc55cSDimitry Andric   int64_t StrideBPtr =
1800349cc55cSDimitry Andric       getPtrStride(PSE, BTy, BPtr, InnermostLoop, Strides, true);
1801*0b57cec5SDimitry Andric 
1802*0b57cec5SDimitry Andric   const SCEV *Src = PSE.getSCEV(APtr);
1803*0b57cec5SDimitry Andric   const SCEV *Sink = PSE.getSCEV(BPtr);
1804*0b57cec5SDimitry Andric 
1805*0b57cec5SDimitry Andric   // If the induction step is negative we have to invert source and sink of the
1806*0b57cec5SDimitry Andric   // dependence.
1807*0b57cec5SDimitry Andric   if (StrideAPtr < 0) {
1808*0b57cec5SDimitry Andric     std::swap(APtr, BPtr);
1809349cc55cSDimitry Andric     std::swap(ATy, BTy);
1810*0b57cec5SDimitry Andric     std::swap(Src, Sink);
1811*0b57cec5SDimitry Andric     std::swap(AIsWrite, BIsWrite);
1812*0b57cec5SDimitry Andric     std::swap(AIdx, BIdx);
1813*0b57cec5SDimitry Andric     std::swap(StrideAPtr, StrideBPtr);
1814*0b57cec5SDimitry Andric   }
1815*0b57cec5SDimitry Andric 
1816*0b57cec5SDimitry Andric   const SCEV *Dist = PSE.getSE()->getMinusSCEV(Sink, Src);
1817*0b57cec5SDimitry Andric 
1818*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
1819*0b57cec5SDimitry Andric                     << "(Induction step: " << StrideAPtr << ")\n");
1820*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
1821*0b57cec5SDimitry Andric                     << *InstMap[BIdx] << ": " << *Dist << "\n");
1822*0b57cec5SDimitry Andric 
1823*0b57cec5SDimitry Andric   // Need accesses with constant stride. We don't want to vectorize
1824*0b57cec5SDimitry Andric   // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
1825*0b57cec5SDimitry Andric   // the address space.
1826*0b57cec5SDimitry Andric   if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
1827*0b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Pointer access with non-constant stride\n");
1828*0b57cec5SDimitry Andric     return Dependence::Unknown;
1829*0b57cec5SDimitry Andric   }
1830*0b57cec5SDimitry Andric 
1831*0b57cec5SDimitry Andric   auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
1832*0b57cec5SDimitry Andric   uint64_t TypeByteSize = DL.getTypeAllocSize(ATy);
18330eae32dcSDimitry Andric   bool HasSameSize =
18340eae32dcSDimitry Andric       DL.getTypeStoreSizeInBits(ATy) == DL.getTypeStoreSizeInBits(BTy);
1835*0b57cec5SDimitry Andric   uint64_t Stride = std::abs(StrideAPtr);
1836*0b57cec5SDimitry Andric   const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
1837*0b57cec5SDimitry Andric   if (!C) {
18380eae32dcSDimitry Andric     if (!isa<SCEVCouldNotCompute>(Dist) && HasSameSize &&
1839*0b57cec5SDimitry Andric         isSafeDependenceDistance(DL, *(PSE.getSE()),
1840*0b57cec5SDimitry Andric                                  *(PSE.getBackedgeTakenCount()), *Dist, Stride,
1841*0b57cec5SDimitry Andric                                  TypeByteSize))
1842*0b57cec5SDimitry Andric       return Dependence::NoDep;
1843*0b57cec5SDimitry Andric 
1844*0b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
1845*0b57cec5SDimitry Andric     FoundNonConstantDistanceDependence = true;
1846*0b57cec5SDimitry Andric     return Dependence::Unknown;
1847*0b57cec5SDimitry Andric   }
1848*0b57cec5SDimitry Andric 
1849*0b57cec5SDimitry Andric   const APInt &Val = C->getAPInt();
1850*0b57cec5SDimitry Andric   int64_t Distance = Val.getSExtValue();
1851*0b57cec5SDimitry Andric 
1852*0b57cec5SDimitry Andric   // Attempt to prove strided accesses independent.
18530eae32dcSDimitry Andric   if (std::abs(Distance) > 0 && Stride > 1 && HasSameSize &&
1854*0b57cec5SDimitry Andric       areStridedAccessesIndependent(std::abs(Distance), Stride, TypeByteSize)) {
1855*0b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Strided accesses are independent\n");
1856*0b57cec5SDimitry Andric     return Dependence::NoDep;
1857*0b57cec5SDimitry Andric   }
1858*0b57cec5SDimitry Andric 
1859*0b57cec5SDimitry Andric   // Negative distances are not plausible dependencies.
1860*0b57cec5SDimitry Andric   if (Val.isNegative()) {
1861*0b57cec5SDimitry Andric     bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
1862*0b57cec5SDimitry Andric     if (IsTrueDataDependence && EnableForwardingConflictDetection &&
1863*0b57cec5SDimitry Andric         (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
18640eae32dcSDimitry Andric          !HasSameSize)) {
1865*0b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "LAA: Forward but may prevent st->ld forwarding\n");
1866*0b57cec5SDimitry Andric       return Dependence::ForwardButPreventsForwarding;
1867*0b57cec5SDimitry Andric     }
1868*0b57cec5SDimitry Andric 
1869*0b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Dependence is negative\n");
1870*0b57cec5SDimitry Andric     return Dependence::Forward;
1871*0b57cec5SDimitry Andric   }
1872*0b57cec5SDimitry Andric 
1873*0b57cec5SDimitry Andric   // Write to the same location with the same size.
1874*0b57cec5SDimitry Andric   if (Val == 0) {
18750eae32dcSDimitry Andric     if (HasSameSize)
1876*0b57cec5SDimitry Andric       return Dependence::Forward;
1877*0b57cec5SDimitry Andric     LLVM_DEBUG(
18780eae32dcSDimitry Andric         dbgs() << "LAA: Zero dependence difference but different type sizes\n");
1879*0b57cec5SDimitry Andric     return Dependence::Unknown;
1880*0b57cec5SDimitry Andric   }
1881*0b57cec5SDimitry Andric 
1882*0b57cec5SDimitry Andric   assert(Val.isStrictlyPositive() && "Expect a positive value");
1883*0b57cec5SDimitry Andric 
18840eae32dcSDimitry Andric   if (!HasSameSize) {
18850eae32dcSDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: ReadWrite-Write positive dependency with "
18860eae32dcSDimitry Andric                          "different type sizes\n");
1887*0b57cec5SDimitry Andric     return Dependence::Unknown;
1888*0b57cec5SDimitry Andric   }
1889*0b57cec5SDimitry Andric 
1890*0b57cec5SDimitry Andric   // Bail out early if passed-in parameters make vectorization not feasible.
1891*0b57cec5SDimitry Andric   unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
1892*0b57cec5SDimitry Andric                            VectorizerParams::VectorizationFactor : 1);
1893*0b57cec5SDimitry Andric   unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
1894*0b57cec5SDimitry Andric                            VectorizerParams::VectorizationInterleave : 1);
1895*0b57cec5SDimitry Andric   // The minimum number of iterations for a vectorized/unrolled version.
1896*0b57cec5SDimitry Andric   unsigned MinNumIter = std::max(ForcedFactor * ForcedUnroll, 2U);
1897*0b57cec5SDimitry Andric 
1898*0b57cec5SDimitry Andric   // It's not vectorizable if the distance is smaller than the minimum distance
1899*0b57cec5SDimitry Andric   // needed for a vectroized/unrolled version. Vectorizing one iteration in
1900*0b57cec5SDimitry Andric   // front needs TypeByteSize * Stride. Vectorizing the last iteration needs
1901*0b57cec5SDimitry Andric   // TypeByteSize (No need to plus the last gap distance).
1902*0b57cec5SDimitry Andric   //
1903*0b57cec5SDimitry Andric   // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1904*0b57cec5SDimitry Andric   //      foo(int *A) {
1905*0b57cec5SDimitry Andric   //        int *B = (int *)((char *)A + 14);
1906*0b57cec5SDimitry Andric   //        for (i = 0 ; i < 1024 ; i += 2)
1907*0b57cec5SDimitry Andric   //          B[i] = A[i] + 1;
1908*0b57cec5SDimitry Andric   //      }
1909*0b57cec5SDimitry Andric   //
1910*0b57cec5SDimitry Andric   // Two accesses in memory (stride is 2):
1911*0b57cec5SDimitry Andric   //     | A[0] |      | A[2] |      | A[4] |      | A[6] |      |
1912*0b57cec5SDimitry Andric   //                              | B[0] |      | B[2] |      | B[4] |
1913*0b57cec5SDimitry Andric   //
1914*0b57cec5SDimitry Andric   // Distance needs for vectorizing iterations except the last iteration:
1915*0b57cec5SDimitry Andric   // 4 * 2 * (MinNumIter - 1). Distance needs for the last iteration: 4.
1916*0b57cec5SDimitry Andric   // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4.
1917*0b57cec5SDimitry Andric   //
1918*0b57cec5SDimitry Andric   // If MinNumIter is 2, it is vectorizable as the minimum distance needed is
1919*0b57cec5SDimitry Andric   // 12, which is less than distance.
1920*0b57cec5SDimitry Andric   //
1921*0b57cec5SDimitry Andric   // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4),
1922*0b57cec5SDimitry Andric   // the minimum distance needed is 28, which is greater than distance. It is
1923*0b57cec5SDimitry Andric   // not safe to do vectorization.
1924*0b57cec5SDimitry Andric   uint64_t MinDistanceNeeded =
1925*0b57cec5SDimitry Andric       TypeByteSize * Stride * (MinNumIter - 1) + TypeByteSize;
1926*0b57cec5SDimitry Andric   if (MinDistanceNeeded > static_cast<uint64_t>(Distance)) {
1927*0b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Failure because of positive distance "
1928*0b57cec5SDimitry Andric                       << Distance << '\n');
1929*0b57cec5SDimitry Andric     return Dependence::Backward;
1930*0b57cec5SDimitry Andric   }
1931*0b57cec5SDimitry Andric 
1932*0b57cec5SDimitry Andric   // Unsafe if the minimum distance needed is greater than max safe distance.
1933*0b57cec5SDimitry Andric   if (MinDistanceNeeded > MaxSafeDepDistBytes) {
1934*0b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Failure because it needs at least "
1935*0b57cec5SDimitry Andric                       << MinDistanceNeeded << " size in bytes");
1936*0b57cec5SDimitry Andric     return Dependence::Backward;
1937*0b57cec5SDimitry Andric   }
1938*0b57cec5SDimitry Andric 
1939*0b57cec5SDimitry Andric   // Positive distance bigger than max vectorization factor.
1940*0b57cec5SDimitry Andric   // FIXME: Should use max factor instead of max distance in bytes, which could
1941*0b57cec5SDimitry Andric   // not handle different types.
1942*0b57cec5SDimitry Andric   // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1943*0b57cec5SDimitry Andric   //      void foo (int *A, char *B) {
1944*0b57cec5SDimitry Andric   //        for (unsigned i = 0; i < 1024; i++) {
1945*0b57cec5SDimitry Andric   //          A[i+2] = A[i] + 1;
1946*0b57cec5SDimitry Andric   //          B[i+2] = B[i] + 1;
1947*0b57cec5SDimitry Andric   //        }
1948*0b57cec5SDimitry Andric   //      }
1949*0b57cec5SDimitry Andric   //
1950*0b57cec5SDimitry Andric   // This case is currently unsafe according to the max safe distance. If we
1951*0b57cec5SDimitry Andric   // analyze the two accesses on array B, the max safe dependence distance
1952*0b57cec5SDimitry Andric   // is 2. Then we analyze the accesses on array A, the minimum distance needed
1953*0b57cec5SDimitry Andric   // is 8, which is less than 2 and forbidden vectorization, But actually
1954*0b57cec5SDimitry Andric   // both A and B could be vectorized by 2 iterations.
1955*0b57cec5SDimitry Andric   MaxSafeDepDistBytes =
1956*0b57cec5SDimitry Andric       std::min(static_cast<uint64_t>(Distance), MaxSafeDepDistBytes);
1957*0b57cec5SDimitry Andric 
1958*0b57cec5SDimitry Andric   bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
1959*0b57cec5SDimitry Andric   if (IsTrueDataDependence && EnableForwardingConflictDetection &&
1960*0b57cec5SDimitry Andric       couldPreventStoreLoadForward(Distance, TypeByteSize))
1961*0b57cec5SDimitry Andric     return Dependence::BackwardVectorizableButPreventsForwarding;
1962*0b57cec5SDimitry Andric 
1963*0b57cec5SDimitry Andric   uint64_t MaxVF = MaxSafeDepDistBytes / (TypeByteSize * Stride);
1964*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue()
1965*0b57cec5SDimitry Andric                     << " with max VF = " << MaxVF << '\n');
1966*0b57cec5SDimitry Andric   uint64_t MaxVFInBits = MaxVF * TypeByteSize * 8;
1967e8d8bef9SDimitry Andric   MaxSafeVectorWidthInBits = std::min(MaxSafeVectorWidthInBits, MaxVFInBits);
1968*0b57cec5SDimitry Andric   return Dependence::BackwardVectorizable;
1969*0b57cec5SDimitry Andric }
1970*0b57cec5SDimitry Andric 
1971*0b57cec5SDimitry Andric bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets,
1972*0b57cec5SDimitry Andric                                    MemAccessInfoList &CheckDeps,
1973*0b57cec5SDimitry Andric                                    const ValueToValueMap &Strides) {
1974*0b57cec5SDimitry Andric 
1975*0b57cec5SDimitry Andric   MaxSafeDepDistBytes = -1;
1976*0b57cec5SDimitry Andric   SmallPtrSet<MemAccessInfo, 8> Visited;
1977*0b57cec5SDimitry Andric   for (MemAccessInfo CurAccess : CheckDeps) {
1978*0b57cec5SDimitry Andric     if (Visited.count(CurAccess))
1979*0b57cec5SDimitry Andric       continue;
1980*0b57cec5SDimitry Andric 
1981*0b57cec5SDimitry Andric     // Get the relevant memory access set.
1982*0b57cec5SDimitry Andric     EquivalenceClasses<MemAccessInfo>::iterator I =
1983*0b57cec5SDimitry Andric       AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
1984*0b57cec5SDimitry Andric 
1985*0b57cec5SDimitry Andric     // Check accesses within this set.
1986*0b57cec5SDimitry Andric     EquivalenceClasses<MemAccessInfo>::member_iterator AI =
1987*0b57cec5SDimitry Andric         AccessSets.member_begin(I);
1988*0b57cec5SDimitry Andric     EquivalenceClasses<MemAccessInfo>::member_iterator AE =
1989*0b57cec5SDimitry Andric         AccessSets.member_end();
1990*0b57cec5SDimitry Andric 
1991*0b57cec5SDimitry Andric     // Check every access pair.
1992*0b57cec5SDimitry Andric     while (AI != AE) {
1993*0b57cec5SDimitry Andric       Visited.insert(*AI);
19948bcb0991SDimitry Andric       bool AIIsWrite = AI->getInt();
19958bcb0991SDimitry Andric       // Check loads only against next equivalent class, but stores also against
19968bcb0991SDimitry Andric       // other stores in the same equivalence class - to the same address.
19978bcb0991SDimitry Andric       EquivalenceClasses<MemAccessInfo>::member_iterator OI =
19988bcb0991SDimitry Andric           (AIIsWrite ? AI : std::next(AI));
1999*0b57cec5SDimitry Andric       while (OI != AE) {
2000*0b57cec5SDimitry Andric         // Check every accessing instruction pair in program order.
2001*0b57cec5SDimitry Andric         for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
2002*0b57cec5SDimitry Andric              I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
20038bcb0991SDimitry Andric           // Scan all accesses of another equivalence class, but only the next
20048bcb0991SDimitry Andric           // accesses of the same equivalent class.
20058bcb0991SDimitry Andric           for (std::vector<unsigned>::iterator
20068bcb0991SDimitry Andric                    I2 = (OI == AI ? std::next(I1) : Accesses[*OI].begin()),
20078bcb0991SDimitry Andric                    I2E = (OI == AI ? I1E : Accesses[*OI].end());
20088bcb0991SDimitry Andric                I2 != I2E; ++I2) {
2009*0b57cec5SDimitry Andric             auto A = std::make_pair(&*AI, *I1);
2010*0b57cec5SDimitry Andric             auto B = std::make_pair(&*OI, *I2);
2011*0b57cec5SDimitry Andric 
2012*0b57cec5SDimitry Andric             assert(*I1 != *I2);
2013*0b57cec5SDimitry Andric             if (*I1 > *I2)
2014*0b57cec5SDimitry Andric               std::swap(A, B);
2015*0b57cec5SDimitry Andric 
2016*0b57cec5SDimitry Andric             Dependence::DepType Type =
2017*0b57cec5SDimitry Andric                 isDependent(*A.first, A.second, *B.first, B.second, Strides);
2018*0b57cec5SDimitry Andric             mergeInStatus(Dependence::isSafeForVectorization(Type));
2019*0b57cec5SDimitry Andric 
2020*0b57cec5SDimitry Andric             // Gather dependences unless we accumulated MaxDependences
2021*0b57cec5SDimitry Andric             // dependences.  In that case return as soon as we find the first
2022*0b57cec5SDimitry Andric             // unsafe dependence.  This puts a limit on this quadratic
2023*0b57cec5SDimitry Andric             // algorithm.
2024*0b57cec5SDimitry Andric             if (RecordDependences) {
2025*0b57cec5SDimitry Andric               if (Type != Dependence::NoDep)
2026*0b57cec5SDimitry Andric                 Dependences.push_back(Dependence(A.second, B.second, Type));
2027*0b57cec5SDimitry Andric 
2028*0b57cec5SDimitry Andric               if (Dependences.size() >= MaxDependences) {
2029*0b57cec5SDimitry Andric                 RecordDependences = false;
2030*0b57cec5SDimitry Andric                 Dependences.clear();
2031*0b57cec5SDimitry Andric                 LLVM_DEBUG(dbgs()
2032*0b57cec5SDimitry Andric                            << "Too many dependences, stopped recording\n");
2033*0b57cec5SDimitry Andric               }
2034*0b57cec5SDimitry Andric             }
2035*0b57cec5SDimitry Andric             if (!RecordDependences && !isSafeForVectorization())
2036*0b57cec5SDimitry Andric               return false;
2037*0b57cec5SDimitry Andric           }
2038*0b57cec5SDimitry Andric         ++OI;
2039*0b57cec5SDimitry Andric       }
2040*0b57cec5SDimitry Andric       AI++;
2041*0b57cec5SDimitry Andric     }
2042*0b57cec5SDimitry Andric   }
2043*0b57cec5SDimitry Andric 
2044*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Total Dependences: " << Dependences.size() << "\n");
2045*0b57cec5SDimitry Andric   return isSafeForVectorization();
2046*0b57cec5SDimitry Andric }
2047*0b57cec5SDimitry Andric 
2048*0b57cec5SDimitry Andric SmallVector<Instruction *, 4>
2049*0b57cec5SDimitry Andric MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const {
2050*0b57cec5SDimitry Andric   MemAccessInfo Access(Ptr, isWrite);
2051*0b57cec5SDimitry Andric   auto &IndexVector = Accesses.find(Access)->second;
2052*0b57cec5SDimitry Andric 
2053*0b57cec5SDimitry Andric   SmallVector<Instruction *, 4> Insts;
2054*0b57cec5SDimitry Andric   transform(IndexVector,
2055*0b57cec5SDimitry Andric                  std::back_inserter(Insts),
2056*0b57cec5SDimitry Andric                  [&](unsigned Idx) { return this->InstMap[Idx]; });
2057*0b57cec5SDimitry Andric   return Insts;
2058*0b57cec5SDimitry Andric }
2059*0b57cec5SDimitry Andric 
2060*0b57cec5SDimitry Andric const char *MemoryDepChecker::Dependence::DepName[] = {
2061*0b57cec5SDimitry Andric     "NoDep", "Unknown", "Forward", "ForwardButPreventsForwarding", "Backward",
2062*0b57cec5SDimitry Andric     "BackwardVectorizable", "BackwardVectorizableButPreventsForwarding"};
2063*0b57cec5SDimitry Andric 
2064*0b57cec5SDimitry Andric void MemoryDepChecker::Dependence::print(
2065*0b57cec5SDimitry Andric     raw_ostream &OS, unsigned Depth,
2066*0b57cec5SDimitry Andric     const SmallVectorImpl<Instruction *> &Instrs) const {
2067*0b57cec5SDimitry Andric   OS.indent(Depth) << DepName[Type] << ":\n";
2068*0b57cec5SDimitry Andric   OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
2069*0b57cec5SDimitry Andric   OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
2070*0b57cec5SDimitry Andric }
2071*0b57cec5SDimitry Andric 
2072*0b57cec5SDimitry Andric bool LoopAccessInfo::canAnalyzeLoop() {
2073*0b57cec5SDimitry Andric   // We need to have a loop header.
2074*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: Found a loop in "
2075*0b57cec5SDimitry Andric                     << TheLoop->getHeader()->getParent()->getName() << ": "
2076*0b57cec5SDimitry Andric                     << TheLoop->getHeader()->getName() << '\n');
2077*0b57cec5SDimitry Andric 
2078*0b57cec5SDimitry Andric   // We can only analyze innermost loops.
2079e8d8bef9SDimitry Andric   if (!TheLoop->isInnermost()) {
2080*0b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
2081*0b57cec5SDimitry Andric     recordAnalysis("NotInnerMostLoop") << "loop is not the innermost loop";
2082*0b57cec5SDimitry Andric     return false;
2083*0b57cec5SDimitry Andric   }
2084*0b57cec5SDimitry Andric 
2085*0b57cec5SDimitry Andric   // We must have a single backedge.
2086*0b57cec5SDimitry Andric   if (TheLoop->getNumBackEdges() != 1) {
2087*0b57cec5SDimitry Andric     LLVM_DEBUG(
2088*0b57cec5SDimitry Andric         dbgs() << "LAA: loop control flow is not understood by analyzer\n");
2089*0b57cec5SDimitry Andric     recordAnalysis("CFGNotUnderstood")
2090*0b57cec5SDimitry Andric         << "loop control flow is not understood by analyzer";
2091*0b57cec5SDimitry Andric     return false;
2092*0b57cec5SDimitry Andric   }
2093*0b57cec5SDimitry Andric 
2094*0b57cec5SDimitry Andric   // ScalarEvolution needs to be able to find the exit count.
2095*0b57cec5SDimitry Andric   const SCEV *ExitCount = PSE->getBackedgeTakenCount();
2096e8d8bef9SDimitry Andric   if (isa<SCEVCouldNotCompute>(ExitCount)) {
2097*0b57cec5SDimitry Andric     recordAnalysis("CantComputeNumberOfIterations")
2098*0b57cec5SDimitry Andric         << "could not determine number of loop iterations";
2099*0b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
2100*0b57cec5SDimitry Andric     return false;
2101*0b57cec5SDimitry Andric   }
2102*0b57cec5SDimitry Andric 
2103*0b57cec5SDimitry Andric   return true;
2104*0b57cec5SDimitry Andric }
2105*0b57cec5SDimitry Andric 
21065ffd83dbSDimitry Andric void LoopAccessInfo::analyzeLoop(AAResults *AA, LoopInfo *LI,
2107*0b57cec5SDimitry Andric                                  const TargetLibraryInfo *TLI,
2108*0b57cec5SDimitry Andric                                  DominatorTree *DT) {
2109*0b57cec5SDimitry Andric   // Holds the Load and Store instructions.
2110*0b57cec5SDimitry Andric   SmallVector<LoadInst *, 16> Loads;
2111*0b57cec5SDimitry Andric   SmallVector<StoreInst *, 16> Stores;
2112*0b57cec5SDimitry Andric 
2113*0b57cec5SDimitry Andric   // Holds all the different accesses in the loop.
2114*0b57cec5SDimitry Andric   unsigned NumReads = 0;
2115*0b57cec5SDimitry Andric   unsigned NumReadWrites = 0;
2116*0b57cec5SDimitry Andric 
2117*0b57cec5SDimitry Andric   bool HasComplexMemInst = false;
2118*0b57cec5SDimitry Andric 
2119*0b57cec5SDimitry Andric   // A runtime check is only legal to insert if there are no convergent calls.
2120*0b57cec5SDimitry Andric   HasConvergentOp = false;
2121*0b57cec5SDimitry Andric 
2122*0b57cec5SDimitry Andric   PtrRtChecking->Pointers.clear();
2123*0b57cec5SDimitry Andric   PtrRtChecking->Need = false;
2124*0b57cec5SDimitry Andric 
2125*0b57cec5SDimitry Andric   const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
2126*0b57cec5SDimitry Andric 
21275ffd83dbSDimitry Andric   const bool EnableMemAccessVersioningOfLoop =
21285ffd83dbSDimitry Andric       EnableMemAccessVersioning &&
21295ffd83dbSDimitry Andric       !TheLoop->getHeader()->getParent()->hasOptSize();
21305ffd83dbSDimitry Andric 
2131*0b57cec5SDimitry Andric   // For each block.
2132*0b57cec5SDimitry Andric   for (BasicBlock *BB : TheLoop->blocks()) {
2133*0b57cec5SDimitry Andric     // Scan the BB and collect legal loads and stores. Also detect any
2134*0b57cec5SDimitry Andric     // convergent instructions.
2135*0b57cec5SDimitry Andric     for (Instruction &I : *BB) {
2136*0b57cec5SDimitry Andric       if (auto *Call = dyn_cast<CallBase>(&I)) {
2137*0b57cec5SDimitry Andric         if (Call->isConvergent())
2138*0b57cec5SDimitry Andric           HasConvergentOp = true;
2139*0b57cec5SDimitry Andric       }
2140*0b57cec5SDimitry Andric 
2141*0b57cec5SDimitry Andric       // With both a non-vectorizable memory instruction and a convergent
2142*0b57cec5SDimitry Andric       // operation, found in this loop, no reason to continue the search.
2143*0b57cec5SDimitry Andric       if (HasComplexMemInst && HasConvergentOp) {
2144*0b57cec5SDimitry Andric         CanVecMem = false;
2145*0b57cec5SDimitry Andric         return;
2146*0b57cec5SDimitry Andric       }
2147*0b57cec5SDimitry Andric 
2148*0b57cec5SDimitry Andric       // Avoid hitting recordAnalysis multiple times.
2149*0b57cec5SDimitry Andric       if (HasComplexMemInst)
2150*0b57cec5SDimitry Andric         continue;
2151*0b57cec5SDimitry Andric 
2152*0b57cec5SDimitry Andric       // If this is a load, save it. If this instruction can read from memory
2153*0b57cec5SDimitry Andric       // but is not a load, then we quit. Notice that we don't handle function
2154*0b57cec5SDimitry Andric       // calls that read or write.
2155*0b57cec5SDimitry Andric       if (I.mayReadFromMemory()) {
2156*0b57cec5SDimitry Andric         // Many math library functions read the rounding mode. We will only
2157*0b57cec5SDimitry Andric         // vectorize a loop if it contains known function calls that don't set
2158*0b57cec5SDimitry Andric         // the flag. Therefore, it is safe to ignore this read from memory.
2159*0b57cec5SDimitry Andric         auto *Call = dyn_cast<CallInst>(&I);
2160*0b57cec5SDimitry Andric         if (Call && getVectorIntrinsicIDForCall(Call, TLI))
2161*0b57cec5SDimitry Andric           continue;
2162*0b57cec5SDimitry Andric 
2163*0b57cec5SDimitry Andric         // If the function has an explicit vectorized counterpart, we can safely
2164*0b57cec5SDimitry Andric         // assume that it can be vectorized.
2165*0b57cec5SDimitry Andric         if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
21665ffd83dbSDimitry Andric             !VFDatabase::getMappings(*Call).empty())
2167*0b57cec5SDimitry Andric           continue;
2168*0b57cec5SDimitry Andric 
2169*0b57cec5SDimitry Andric         auto *Ld = dyn_cast<LoadInst>(&I);
2170*0b57cec5SDimitry Andric         if (!Ld) {
2171*0b57cec5SDimitry Andric           recordAnalysis("CantVectorizeInstruction", Ld)
2172*0b57cec5SDimitry Andric             << "instruction cannot be vectorized";
2173*0b57cec5SDimitry Andric           HasComplexMemInst = true;
2174*0b57cec5SDimitry Andric           continue;
2175*0b57cec5SDimitry Andric         }
2176*0b57cec5SDimitry Andric         if (!Ld->isSimple() && !IsAnnotatedParallel) {
2177*0b57cec5SDimitry Andric           recordAnalysis("NonSimpleLoad", Ld)
2178*0b57cec5SDimitry Andric               << "read with atomic ordering or volatile read";
2179*0b57cec5SDimitry Andric           LLVM_DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
2180*0b57cec5SDimitry Andric           HasComplexMemInst = true;
2181*0b57cec5SDimitry Andric           continue;
2182*0b57cec5SDimitry Andric         }
2183*0b57cec5SDimitry Andric         NumLoads++;
2184*0b57cec5SDimitry Andric         Loads.push_back(Ld);
2185*0b57cec5SDimitry Andric         DepChecker->addAccess(Ld);
21865ffd83dbSDimitry Andric         if (EnableMemAccessVersioningOfLoop)
2187*0b57cec5SDimitry Andric           collectStridedAccess(Ld);
2188*0b57cec5SDimitry Andric         continue;
2189*0b57cec5SDimitry Andric       }
2190*0b57cec5SDimitry Andric 
2191*0b57cec5SDimitry Andric       // Save 'store' instructions. Abort if other instructions write to memory.
2192*0b57cec5SDimitry Andric       if (I.mayWriteToMemory()) {
2193*0b57cec5SDimitry Andric         auto *St = dyn_cast<StoreInst>(&I);
2194*0b57cec5SDimitry Andric         if (!St) {
2195*0b57cec5SDimitry Andric           recordAnalysis("CantVectorizeInstruction", St)
2196*0b57cec5SDimitry Andric               << "instruction cannot be vectorized";
2197*0b57cec5SDimitry Andric           HasComplexMemInst = true;
2198*0b57cec5SDimitry Andric           continue;
2199*0b57cec5SDimitry Andric         }
2200*0b57cec5SDimitry Andric         if (!St->isSimple() && !IsAnnotatedParallel) {
2201*0b57cec5SDimitry Andric           recordAnalysis("NonSimpleStore", St)
2202*0b57cec5SDimitry Andric               << "write with atomic ordering or volatile write";
2203*0b57cec5SDimitry Andric           LLVM_DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
2204*0b57cec5SDimitry Andric           HasComplexMemInst = true;
2205*0b57cec5SDimitry Andric           continue;
2206*0b57cec5SDimitry Andric         }
2207*0b57cec5SDimitry Andric         NumStores++;
2208*0b57cec5SDimitry Andric         Stores.push_back(St);
2209*0b57cec5SDimitry Andric         DepChecker->addAccess(St);
22105ffd83dbSDimitry Andric         if (EnableMemAccessVersioningOfLoop)
2211*0b57cec5SDimitry Andric           collectStridedAccess(St);
2212*0b57cec5SDimitry Andric       }
2213*0b57cec5SDimitry Andric     } // Next instr.
2214*0b57cec5SDimitry Andric   } // Next block.
2215*0b57cec5SDimitry Andric 
2216*0b57cec5SDimitry Andric   if (HasComplexMemInst) {
2217*0b57cec5SDimitry Andric     CanVecMem = false;
2218*0b57cec5SDimitry Andric     return;
2219*0b57cec5SDimitry Andric   }
2220*0b57cec5SDimitry Andric 
2221*0b57cec5SDimitry Andric   // Now we have two lists that hold the loads and the stores.
2222*0b57cec5SDimitry Andric   // Next, we find the pointers that they use.
2223*0b57cec5SDimitry Andric 
2224*0b57cec5SDimitry Andric   // Check if we see any stores. If there are no stores, then we don't
2225*0b57cec5SDimitry Andric   // care if the pointers are *restrict*.
2226*0b57cec5SDimitry Andric   if (!Stores.size()) {
2227*0b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
2228*0b57cec5SDimitry Andric     CanVecMem = true;
2229*0b57cec5SDimitry Andric     return;
2230*0b57cec5SDimitry Andric   }
2231*0b57cec5SDimitry Andric 
2232*0b57cec5SDimitry Andric   MemoryDepChecker::DepCandidates DependentAccesses;
2233e8d8bef9SDimitry Andric   AccessAnalysis Accesses(TheLoop, AA, LI, DependentAccesses, *PSE);
2234*0b57cec5SDimitry Andric 
2235e8d8bef9SDimitry Andric   // Holds the analyzed pointers. We don't want to call getUnderlyingObjects
2236*0b57cec5SDimitry Andric   // multiple times on the same object. If the ptr is accessed twice, once
2237*0b57cec5SDimitry Andric   // for read and once for write, it will only appear once (on the write
2238*0b57cec5SDimitry Andric   // list). This is okay, since we are going to check for conflicts between
2239*0b57cec5SDimitry Andric   // writes and between reads and writes, but not between reads and reads.
224081ad6265SDimitry Andric   SmallSet<std::pair<Value *, Type *>, 16> Seen;
2241*0b57cec5SDimitry Andric 
2242*0b57cec5SDimitry Andric   // Record uniform store addresses to identify if we have multiple stores
2243*0b57cec5SDimitry Andric   // to the same address.
224481ad6265SDimitry Andric   SmallPtrSet<Value *, 16> UniformStores;
2245*0b57cec5SDimitry Andric 
2246*0b57cec5SDimitry Andric   for (StoreInst *ST : Stores) {
2247*0b57cec5SDimitry Andric     Value *Ptr = ST->getPointerOperand();
2248*0b57cec5SDimitry Andric 
224981ad6265SDimitry Andric     if (isUniform(Ptr)) {
225081ad6265SDimitry Andric       // Record store instructions to loop invariant addresses
225181ad6265SDimitry Andric       StoresToInvariantAddresses.push_back(ST);
2252*0b57cec5SDimitry Andric       HasDependenceInvolvingLoopInvariantAddress |=
2253*0b57cec5SDimitry Andric           !UniformStores.insert(Ptr).second;
225481ad6265SDimitry Andric     }
2255*0b57cec5SDimitry Andric 
2256*0b57cec5SDimitry Andric     // If we did *not* see this pointer before, insert it to  the read-write
2257*0b57cec5SDimitry Andric     // list. At this phase it is only a 'write' list.
225881ad6265SDimitry Andric     Type *AccessTy = getLoadStoreType(ST);
225981ad6265SDimitry Andric     if (Seen.insert({Ptr, AccessTy}).second) {
2260*0b57cec5SDimitry Andric       ++NumReadWrites;
2261*0b57cec5SDimitry Andric 
2262*0b57cec5SDimitry Andric       MemoryLocation Loc = MemoryLocation::get(ST);
2263*0b57cec5SDimitry Andric       // The TBAA metadata could have a control dependency on the predication
2264*0b57cec5SDimitry Andric       // condition, so we cannot rely on it when determining whether or not we
2265*0b57cec5SDimitry Andric       // need runtime pointer checks.
2266*0b57cec5SDimitry Andric       if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
2267*0b57cec5SDimitry Andric         Loc.AATags.TBAA = nullptr;
2268*0b57cec5SDimitry Andric 
2269349cc55cSDimitry Andric       visitPointers(const_cast<Value *>(Loc.Ptr), *TheLoop,
227081ad6265SDimitry Andric                     [&Accesses, AccessTy, Loc](Value *Ptr) {
2271349cc55cSDimitry Andric                       MemoryLocation NewLoc = Loc.getWithNewPtr(Ptr);
227281ad6265SDimitry Andric                       Accesses.addStore(NewLoc, AccessTy);
2273349cc55cSDimitry Andric                     });
2274*0b57cec5SDimitry Andric     }
2275*0b57cec5SDimitry Andric   }
2276*0b57cec5SDimitry Andric 
2277*0b57cec5SDimitry Andric   if (IsAnnotatedParallel) {
2278*0b57cec5SDimitry Andric     LLVM_DEBUG(
2279*0b57cec5SDimitry Andric         dbgs() << "LAA: A loop annotated parallel, ignore memory dependency "
2280*0b57cec5SDimitry Andric                << "checks.\n");
2281*0b57cec5SDimitry Andric     CanVecMem = true;
2282*0b57cec5SDimitry Andric     return;
2283*0b57cec5SDimitry Andric   }
2284*0b57cec5SDimitry Andric 
2285*0b57cec5SDimitry Andric   for (LoadInst *LD : Loads) {
2286*0b57cec5SDimitry Andric     Value *Ptr = LD->getPointerOperand();
2287*0b57cec5SDimitry Andric     // If we did *not* see this pointer before, insert it to the
2288*0b57cec5SDimitry Andric     // read list. If we *did* see it before, then it is already in
2289*0b57cec5SDimitry Andric     // the read-write list. This allows us to vectorize expressions
2290*0b57cec5SDimitry Andric     // such as A[i] += x;  Because the address of A[i] is a read-write
2291*0b57cec5SDimitry Andric     // pointer. This only works if the index of A[i] is consecutive.
2292*0b57cec5SDimitry Andric     // If the address of i is unknown (for example A[B[i]]) then we may
2293*0b57cec5SDimitry Andric     // read a few words, modify, and write a few words, and some of the
2294*0b57cec5SDimitry Andric     // words may be written to the same address.
2295*0b57cec5SDimitry Andric     bool IsReadOnlyPtr = false;
229681ad6265SDimitry Andric     Type *AccessTy = getLoadStoreType(LD);
229781ad6265SDimitry Andric     if (Seen.insert({Ptr, AccessTy}).second ||
2298349cc55cSDimitry Andric         !getPtrStride(*PSE, LD->getType(), Ptr, TheLoop, SymbolicStrides)) {
2299*0b57cec5SDimitry Andric       ++NumReads;
2300*0b57cec5SDimitry Andric       IsReadOnlyPtr = true;
2301*0b57cec5SDimitry Andric     }
2302*0b57cec5SDimitry Andric 
2303*0b57cec5SDimitry Andric     // See if there is an unsafe dependency between a load to a uniform address and
2304*0b57cec5SDimitry Andric     // store to the same uniform address.
2305*0b57cec5SDimitry Andric     if (UniformStores.count(Ptr)) {
2306*0b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "LAA: Found an unsafe dependency between a uniform "
2307*0b57cec5SDimitry Andric                            "load and uniform store to the same address!\n");
2308*0b57cec5SDimitry Andric       HasDependenceInvolvingLoopInvariantAddress = true;
2309*0b57cec5SDimitry Andric     }
2310*0b57cec5SDimitry Andric 
2311*0b57cec5SDimitry Andric     MemoryLocation Loc = MemoryLocation::get(LD);
2312*0b57cec5SDimitry Andric     // The TBAA metadata could have a control dependency on the predication
2313*0b57cec5SDimitry Andric     // condition, so we cannot rely on it when determining whether or not we
2314*0b57cec5SDimitry Andric     // need runtime pointer checks.
2315*0b57cec5SDimitry Andric     if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
2316*0b57cec5SDimitry Andric       Loc.AATags.TBAA = nullptr;
2317*0b57cec5SDimitry Andric 
2318349cc55cSDimitry Andric     visitPointers(const_cast<Value *>(Loc.Ptr), *TheLoop,
231981ad6265SDimitry Andric                   [&Accesses, AccessTy, Loc, IsReadOnlyPtr](Value *Ptr) {
2320349cc55cSDimitry Andric                     MemoryLocation NewLoc = Loc.getWithNewPtr(Ptr);
232181ad6265SDimitry Andric                     Accesses.addLoad(NewLoc, AccessTy, IsReadOnlyPtr);
2322349cc55cSDimitry Andric                   });
2323*0b57cec5SDimitry Andric   }
2324*0b57cec5SDimitry Andric 
2325*0b57cec5SDimitry Andric   // If we write (or read-write) to a single destination and there are no
2326*0b57cec5SDimitry Andric   // other reads in this loop then is it safe to vectorize.
2327*0b57cec5SDimitry Andric   if (NumReadWrites == 1 && NumReads == 0) {
2328*0b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
2329*0b57cec5SDimitry Andric     CanVecMem = true;
2330*0b57cec5SDimitry Andric     return;
2331*0b57cec5SDimitry Andric   }
2332*0b57cec5SDimitry Andric 
2333*0b57cec5SDimitry Andric   // Build dependence sets and check whether we need a runtime pointer bounds
2334*0b57cec5SDimitry Andric   // check.
2335*0b57cec5SDimitry Andric   Accesses.buildDependenceSets();
2336*0b57cec5SDimitry Andric 
2337*0b57cec5SDimitry Andric   // Find pointers with computable bounds. We are going to use this information
2338*0b57cec5SDimitry Andric   // to place a runtime bound check.
233981ad6265SDimitry Andric   Value *UncomputablePtr = nullptr;
234081ad6265SDimitry Andric   bool CanDoRTIfNeeded =
234181ad6265SDimitry Andric       Accesses.canCheckPtrAtRT(*PtrRtChecking, PSE->getSE(), TheLoop,
234281ad6265SDimitry Andric                                SymbolicStrides, UncomputablePtr, false);
2343*0b57cec5SDimitry Andric   if (!CanDoRTIfNeeded) {
234481ad6265SDimitry Andric     auto *I = dyn_cast_or_null<Instruction>(UncomputablePtr);
234581ad6265SDimitry Andric     recordAnalysis("CantIdentifyArrayBounds", I)
234681ad6265SDimitry Andric         << "cannot identify array bounds";
2347*0b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: We can't vectorize because we can't find "
2348*0b57cec5SDimitry Andric                       << "the array bounds.\n");
2349*0b57cec5SDimitry Andric     CanVecMem = false;
2350*0b57cec5SDimitry Andric     return;
2351*0b57cec5SDimitry Andric   }
2352*0b57cec5SDimitry Andric 
2353*0b57cec5SDimitry Andric   LLVM_DEBUG(
2354*0b57cec5SDimitry Andric     dbgs() << "LAA: May be able to perform a memory runtime check if needed.\n");
2355*0b57cec5SDimitry Andric 
2356*0b57cec5SDimitry Andric   CanVecMem = true;
2357*0b57cec5SDimitry Andric   if (Accesses.isDependencyCheckNeeded()) {
2358*0b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
2359*0b57cec5SDimitry Andric     CanVecMem = DepChecker->areDepsSafe(
2360*0b57cec5SDimitry Andric         DependentAccesses, Accesses.getDependenciesToCheck(), SymbolicStrides);
2361*0b57cec5SDimitry Andric     MaxSafeDepDistBytes = DepChecker->getMaxSafeDepDistBytes();
2362*0b57cec5SDimitry Andric 
2363*0b57cec5SDimitry Andric     if (!CanVecMem && DepChecker->shouldRetryWithRuntimeCheck()) {
2364*0b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
2365*0b57cec5SDimitry Andric 
2366*0b57cec5SDimitry Andric       // Clear the dependency checks. We assume they are not needed.
2367*0b57cec5SDimitry Andric       Accesses.resetDepChecks(*DepChecker);
2368*0b57cec5SDimitry Andric 
2369*0b57cec5SDimitry Andric       PtrRtChecking->reset();
2370*0b57cec5SDimitry Andric       PtrRtChecking->Need = true;
2371*0b57cec5SDimitry Andric 
2372*0b57cec5SDimitry Andric       auto *SE = PSE->getSE();
237381ad6265SDimitry Andric       UncomputablePtr = nullptr;
237481ad6265SDimitry Andric       CanDoRTIfNeeded = Accesses.canCheckPtrAtRT(
237581ad6265SDimitry Andric           *PtrRtChecking, SE, TheLoop, SymbolicStrides, UncomputablePtr, true);
2376*0b57cec5SDimitry Andric 
2377*0b57cec5SDimitry Andric       // Check that we found the bounds for the pointer.
2378*0b57cec5SDimitry Andric       if (!CanDoRTIfNeeded) {
237981ad6265SDimitry Andric         auto *I = dyn_cast_or_null<Instruction>(UncomputablePtr);
238081ad6265SDimitry Andric         recordAnalysis("CantCheckMemDepsAtRunTime", I)
2381*0b57cec5SDimitry Andric             << "cannot check memory dependencies at runtime";
2382*0b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
2383*0b57cec5SDimitry Andric         CanVecMem = false;
2384*0b57cec5SDimitry Andric         return;
2385*0b57cec5SDimitry Andric       }
2386*0b57cec5SDimitry Andric 
2387*0b57cec5SDimitry Andric       CanVecMem = true;
2388*0b57cec5SDimitry Andric     }
2389*0b57cec5SDimitry Andric   }
2390*0b57cec5SDimitry Andric 
2391*0b57cec5SDimitry Andric   if (HasConvergentOp) {
2392*0b57cec5SDimitry Andric     recordAnalysis("CantInsertRuntimeCheckWithConvergent")
2393*0b57cec5SDimitry Andric       << "cannot add control dependency to convergent operation";
2394*0b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LAA: We can't vectorize because a runtime check "
2395*0b57cec5SDimitry Andric                          "would be needed with a convergent operation\n");
2396*0b57cec5SDimitry Andric     CanVecMem = false;
2397*0b57cec5SDimitry Andric     return;
2398*0b57cec5SDimitry Andric   }
2399*0b57cec5SDimitry Andric 
2400*0b57cec5SDimitry Andric   if (CanVecMem)
2401*0b57cec5SDimitry Andric     LLVM_DEBUG(
2402*0b57cec5SDimitry Andric         dbgs() << "LAA: No unsafe dependent memory operations in loop.  We"
2403*0b57cec5SDimitry Andric                << (PtrRtChecking->Need ? "" : " don't")
2404*0b57cec5SDimitry Andric                << " need runtime memory checks.\n");
240581ad6265SDimitry Andric   else
240681ad6265SDimitry Andric     emitUnsafeDependenceRemark();
240781ad6265SDimitry Andric }
240881ad6265SDimitry Andric 
240981ad6265SDimitry Andric void LoopAccessInfo::emitUnsafeDependenceRemark() {
241081ad6265SDimitry Andric   auto Deps = getDepChecker().getDependences();
241181ad6265SDimitry Andric   if (!Deps)
241281ad6265SDimitry Andric     return;
241381ad6265SDimitry Andric   auto Found = std::find_if(
241481ad6265SDimitry Andric       Deps->begin(), Deps->end(), [](const MemoryDepChecker::Dependence &D) {
241581ad6265SDimitry Andric         return MemoryDepChecker::Dependence::isSafeForVectorization(D.Type) !=
241681ad6265SDimitry Andric                MemoryDepChecker::VectorizationSafetyStatus::Safe;
241781ad6265SDimitry Andric       });
241881ad6265SDimitry Andric   if (Found == Deps->end())
241981ad6265SDimitry Andric     return;
242081ad6265SDimitry Andric   MemoryDepChecker::Dependence Dep = *Found;
242181ad6265SDimitry Andric 
242281ad6265SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
242381ad6265SDimitry Andric 
242481ad6265SDimitry Andric   // Emit remark for first unsafe dependence
242581ad6265SDimitry Andric   OptimizationRemarkAnalysis &R =
242681ad6265SDimitry Andric       recordAnalysis("UnsafeDep", Dep.getDestination(*this))
2427*0b57cec5SDimitry Andric       << "unsafe dependent memory operations in loop. Use "
2428*0b57cec5SDimitry Andric          "#pragma loop distribute(enable) to allow loop distribution "
2429*0b57cec5SDimitry Andric          "to attempt to isolate the offending operations into a separate "
2430*0b57cec5SDimitry Andric          "loop";
243181ad6265SDimitry Andric 
243281ad6265SDimitry Andric   switch (Dep.Type) {
243381ad6265SDimitry Andric   case MemoryDepChecker::Dependence::NoDep:
243481ad6265SDimitry Andric   case MemoryDepChecker::Dependence::Forward:
243581ad6265SDimitry Andric   case MemoryDepChecker::Dependence::BackwardVectorizable:
243681ad6265SDimitry Andric     llvm_unreachable("Unexpected dependence");
243781ad6265SDimitry Andric   case MemoryDepChecker::Dependence::Backward:
243881ad6265SDimitry Andric     R << "\nBackward loop carried data dependence.";
243981ad6265SDimitry Andric     break;
244081ad6265SDimitry Andric   case MemoryDepChecker::Dependence::ForwardButPreventsForwarding:
244181ad6265SDimitry Andric     R << "\nForward loop carried data dependence that prevents "
244281ad6265SDimitry Andric          "store-to-load forwarding.";
244381ad6265SDimitry Andric     break;
244481ad6265SDimitry Andric   case MemoryDepChecker::Dependence::BackwardVectorizableButPreventsForwarding:
244581ad6265SDimitry Andric     R << "\nBackward loop carried data dependence that prevents "
244681ad6265SDimitry Andric          "store-to-load forwarding.";
244781ad6265SDimitry Andric     break;
244881ad6265SDimitry Andric   case MemoryDepChecker::Dependence::Unknown:
244981ad6265SDimitry Andric     R << "\nUnknown data dependence.";
245081ad6265SDimitry Andric     break;
245181ad6265SDimitry Andric   }
245281ad6265SDimitry Andric 
245381ad6265SDimitry Andric   if (Instruction *I = Dep.getSource(*this)) {
245481ad6265SDimitry Andric     DebugLoc SourceLoc = I->getDebugLoc();
245581ad6265SDimitry Andric     if (auto *DD = dyn_cast_or_null<Instruction>(getPointerOperand(I)))
245681ad6265SDimitry Andric       SourceLoc = DD->getDebugLoc();
245781ad6265SDimitry Andric     if (SourceLoc)
245881ad6265SDimitry Andric       R << " Memory location is the same as accessed at "
245981ad6265SDimitry Andric         << ore::NV("Location", SourceLoc);
2460*0b57cec5SDimitry Andric   }
2461*0b57cec5SDimitry Andric }
2462*0b57cec5SDimitry Andric 
2463*0b57cec5SDimitry Andric bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
2464*0b57cec5SDimitry Andric                                            DominatorTree *DT)  {
2465*0b57cec5SDimitry Andric   assert(TheLoop->contains(BB) && "Unknown block used");
2466*0b57cec5SDimitry Andric 
2467*0b57cec5SDimitry Andric   // Blocks that do not dominate the latch need predication.
2468*0b57cec5SDimitry Andric   BasicBlock* Latch = TheLoop->getLoopLatch();
2469*0b57cec5SDimitry Andric   return !DT->dominates(BB, Latch);
2470*0b57cec5SDimitry Andric }
2471*0b57cec5SDimitry Andric 
2472*0b57cec5SDimitry Andric OptimizationRemarkAnalysis &LoopAccessInfo::recordAnalysis(StringRef RemarkName,
2473*0b57cec5SDimitry Andric                                                            Instruction *I) {
2474*0b57cec5SDimitry Andric   assert(!Report && "Multiple reports generated");
2475*0b57cec5SDimitry Andric 
2476*0b57cec5SDimitry Andric   Value *CodeRegion = TheLoop->getHeader();
2477*0b57cec5SDimitry Andric   DebugLoc DL = TheLoop->getStartLoc();
2478*0b57cec5SDimitry Andric 
2479*0b57cec5SDimitry Andric   if (I) {
2480*0b57cec5SDimitry Andric     CodeRegion = I->getParent();
2481*0b57cec5SDimitry Andric     // If there is no debug location attached to the instruction, revert back to
2482*0b57cec5SDimitry Andric     // using the loop's.
2483*0b57cec5SDimitry Andric     if (I->getDebugLoc())
2484*0b57cec5SDimitry Andric       DL = I->getDebugLoc();
2485*0b57cec5SDimitry Andric   }
2486*0b57cec5SDimitry Andric 
24878bcb0991SDimitry Andric   Report = std::make_unique<OptimizationRemarkAnalysis>(DEBUG_TYPE, RemarkName, DL,
2488*0b57cec5SDimitry Andric                                                    CodeRegion);
2489*0b57cec5SDimitry Andric   return *Report;
2490*0b57cec5SDimitry Andric }
2491*0b57cec5SDimitry Andric 
2492*0b57cec5SDimitry Andric bool LoopAccessInfo::isUniform(Value *V) const {
2493*0b57cec5SDimitry Andric   auto *SE = PSE->getSE();
2494*0b57cec5SDimitry Andric   // Since we rely on SCEV for uniformity, if the type is not SCEVable, it is
2495*0b57cec5SDimitry Andric   // never considered uniform.
2496*0b57cec5SDimitry Andric   // TODO: Is this really what we want? Even without FP SCEV, we may want some
2497*0b57cec5SDimitry Andric   // trivially loop-invariant FP values to be considered uniform.
2498*0b57cec5SDimitry Andric   if (!SE->isSCEVable(V->getType()))
2499*0b57cec5SDimitry Andric     return false;
2500*0b57cec5SDimitry Andric   return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
2501*0b57cec5SDimitry Andric }
2502*0b57cec5SDimitry Andric 
2503*0b57cec5SDimitry Andric void LoopAccessInfo::collectStridedAccess(Value *MemAccess) {
2504e8d8bef9SDimitry Andric   Value *Ptr = getLoadStorePointerOperand(MemAccess);
2505e8d8bef9SDimitry Andric   if (!Ptr)
2506*0b57cec5SDimitry Andric     return;
2507*0b57cec5SDimitry Andric 
2508*0b57cec5SDimitry Andric   Value *Stride = getStrideFromPointer(Ptr, PSE->getSE(), TheLoop);
2509*0b57cec5SDimitry Andric   if (!Stride)
2510*0b57cec5SDimitry Andric     return;
2511*0b57cec5SDimitry Andric 
2512*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: Found a strided access that is a candidate for "
2513*0b57cec5SDimitry Andric                        "versioning:");
2514*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "  Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
2515*0b57cec5SDimitry Andric 
2516*0b57cec5SDimitry Andric   // Avoid adding the "Stride == 1" predicate when we know that
2517*0b57cec5SDimitry Andric   // Stride >= Trip-Count. Such a predicate will effectively optimize a single
2518*0b57cec5SDimitry Andric   // or zero iteration loop, as Trip-Count <= Stride == 1.
2519*0b57cec5SDimitry Andric   //
2520*0b57cec5SDimitry Andric   // TODO: We are currently not making a very informed decision on when it is
2521*0b57cec5SDimitry Andric   // beneficial to apply stride versioning. It might make more sense that the
2522*0b57cec5SDimitry Andric   // users of this analysis (such as the vectorizer) will trigger it, based on
2523*0b57cec5SDimitry Andric   // their specific cost considerations; For example, in cases where stride
2524*0b57cec5SDimitry Andric   // versioning does  not help resolving memory accesses/dependences, the
2525*0b57cec5SDimitry Andric   // vectorizer should evaluate the cost of the runtime test, and the benefit
2526*0b57cec5SDimitry Andric   // of various possible stride specializations, considering the alternatives
2527*0b57cec5SDimitry Andric   // of using gather/scatters (if available).
2528*0b57cec5SDimitry Andric 
2529*0b57cec5SDimitry Andric   const SCEV *StrideExpr = PSE->getSCEV(Stride);
2530*0b57cec5SDimitry Andric   const SCEV *BETakenCount = PSE->getBackedgeTakenCount();
2531*0b57cec5SDimitry Andric 
2532*0b57cec5SDimitry Andric   // Match the types so we can compare the stride and the BETakenCount.
2533*0b57cec5SDimitry Andric   // The Stride can be positive/negative, so we sign extend Stride;
2534*0b57cec5SDimitry Andric   // The backedgeTakenCount is non-negative, so we zero extend BETakenCount.
2535*0b57cec5SDimitry Andric   const DataLayout &DL = TheLoop->getHeader()->getModule()->getDataLayout();
253681ad6265SDimitry Andric   uint64_t StrideTypeSizeBits = DL.getTypeSizeInBits(StrideExpr->getType());
253781ad6265SDimitry Andric   uint64_t BETypeSizeBits = DL.getTypeSizeInBits(BETakenCount->getType());
2538*0b57cec5SDimitry Andric   const SCEV *CastedStride = StrideExpr;
2539*0b57cec5SDimitry Andric   const SCEV *CastedBECount = BETakenCount;
2540*0b57cec5SDimitry Andric   ScalarEvolution *SE = PSE->getSE();
254181ad6265SDimitry Andric   if (BETypeSizeBits >= StrideTypeSizeBits)
2542*0b57cec5SDimitry Andric     CastedStride = SE->getNoopOrSignExtend(StrideExpr, BETakenCount->getType());
2543*0b57cec5SDimitry Andric   else
2544*0b57cec5SDimitry Andric     CastedBECount = SE->getZeroExtendExpr(BETakenCount, StrideExpr->getType());
2545*0b57cec5SDimitry Andric   const SCEV *StrideMinusBETaken = SE->getMinusSCEV(CastedStride, CastedBECount);
2546*0b57cec5SDimitry Andric   // Since TripCount == BackEdgeTakenCount + 1, checking:
2547*0b57cec5SDimitry Andric   // "Stride >= TripCount" is equivalent to checking:
2548*0b57cec5SDimitry Andric   // Stride - BETakenCount > 0
2549*0b57cec5SDimitry Andric   if (SE->isKnownPositive(StrideMinusBETaken)) {
2550*0b57cec5SDimitry Andric     LLVM_DEBUG(
2551*0b57cec5SDimitry Andric         dbgs() << "LAA: Stride>=TripCount; No point in versioning as the "
2552*0b57cec5SDimitry Andric                   "Stride==1 predicate will imply that the loop executes "
2553*0b57cec5SDimitry Andric                   "at most once.\n");
2554*0b57cec5SDimitry Andric     return;
2555*0b57cec5SDimitry Andric   }
255681ad6265SDimitry Andric   LLVM_DEBUG(dbgs() << "LAA: Found a strided access that we can version.\n");
2557*0b57cec5SDimitry Andric 
2558*0b57cec5SDimitry Andric   SymbolicStrides[Ptr] = Stride;
2559*0b57cec5SDimitry Andric   StrideSet.insert(Stride);
2560*0b57cec5SDimitry Andric }
2561*0b57cec5SDimitry Andric 
2562*0b57cec5SDimitry Andric LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
25635ffd83dbSDimitry Andric                                const TargetLibraryInfo *TLI, AAResults *AA,
2564*0b57cec5SDimitry Andric                                DominatorTree *DT, LoopInfo *LI)
25658bcb0991SDimitry Andric     : PSE(std::make_unique<PredicatedScalarEvolution>(*SE, *L)),
256681ad6265SDimitry Andric       PtrRtChecking(nullptr),
256704eeddc0SDimitry Andric       DepChecker(std::make_unique<MemoryDepChecker>(*PSE, L)), TheLoop(L) {
256881ad6265SDimitry Andric   PtrRtChecking = std::make_unique<RuntimePointerChecking>(*DepChecker, SE);
256981ad6265SDimitry Andric   if (canAnalyzeLoop()) {
2570*0b57cec5SDimitry Andric     analyzeLoop(AA, LI, TLI, DT);
2571*0b57cec5SDimitry Andric   }
257281ad6265SDimitry Andric }
2573*0b57cec5SDimitry Andric 
2574*0b57cec5SDimitry Andric void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
2575*0b57cec5SDimitry Andric   if (CanVecMem) {
2576*0b57cec5SDimitry Andric     OS.indent(Depth) << "Memory dependences are safe";
2577*0b57cec5SDimitry Andric     if (MaxSafeDepDistBytes != -1ULL)
2578*0b57cec5SDimitry Andric       OS << " with a maximum dependence distance of " << MaxSafeDepDistBytes
2579*0b57cec5SDimitry Andric          << " bytes";
2580*0b57cec5SDimitry Andric     if (PtrRtChecking->Need)
2581*0b57cec5SDimitry Andric       OS << " with run-time checks";
2582*0b57cec5SDimitry Andric     OS << "\n";
2583*0b57cec5SDimitry Andric   }
2584*0b57cec5SDimitry Andric 
2585*0b57cec5SDimitry Andric   if (HasConvergentOp)
2586*0b57cec5SDimitry Andric     OS.indent(Depth) << "Has convergent operation in loop\n";
2587*0b57cec5SDimitry Andric 
2588*0b57cec5SDimitry Andric   if (Report)
2589*0b57cec5SDimitry Andric     OS.indent(Depth) << "Report: " << Report->getMsg() << "\n";
2590*0b57cec5SDimitry Andric 
2591*0b57cec5SDimitry Andric   if (auto *Dependences = DepChecker->getDependences()) {
2592*0b57cec5SDimitry Andric     OS.indent(Depth) << "Dependences:\n";
2593fcaf7f86SDimitry Andric     for (const auto &Dep : *Dependences) {
2594*0b57cec5SDimitry Andric       Dep.print(OS, Depth + 2, DepChecker->getMemoryInstructions());
2595*0b57cec5SDimitry Andric       OS << "\n";
2596*0b57cec5SDimitry Andric     }
2597*0b57cec5SDimitry Andric   } else
2598*0b57cec5SDimitry Andric     OS.indent(Depth) << "Too many dependences, not recorded\n";
2599*0b57cec5SDimitry Andric 
2600*0b57cec5SDimitry Andric   // List the pair of accesses need run-time checks to prove independence.
2601*0b57cec5SDimitry Andric   PtrRtChecking->print(OS, Depth);
2602*0b57cec5SDimitry Andric   OS << "\n";
2603*0b57cec5SDimitry Andric 
2604*0b57cec5SDimitry Andric   OS.indent(Depth) << "Non vectorizable stores to invariant address were "
2605*0b57cec5SDimitry Andric                    << (HasDependenceInvolvingLoopInvariantAddress ? "" : "not ")
2606*0b57cec5SDimitry Andric                    << "found in loop.\n";
2607*0b57cec5SDimitry Andric 
2608*0b57cec5SDimitry Andric   OS.indent(Depth) << "SCEV assumptions:\n";
260981ad6265SDimitry Andric   PSE->getPredicate().print(OS, Depth);
2610*0b57cec5SDimitry Andric 
2611*0b57cec5SDimitry Andric   OS << "\n";
2612*0b57cec5SDimitry Andric 
2613*0b57cec5SDimitry Andric   OS.indent(Depth) << "Expressions re-written:\n";
2614*0b57cec5SDimitry Andric   PSE->print(OS, Depth);
2615*0b57cec5SDimitry Andric }
2616*0b57cec5SDimitry Andric 
2617480093f4SDimitry Andric LoopAccessLegacyAnalysis::LoopAccessLegacyAnalysis() : FunctionPass(ID) {
2618480093f4SDimitry Andric   initializeLoopAccessLegacyAnalysisPass(*PassRegistry::getPassRegistry());
2619480093f4SDimitry Andric }
2620480093f4SDimitry Andric 
2621*0b57cec5SDimitry Andric const LoopAccessInfo &LoopAccessLegacyAnalysis::getInfo(Loop *L) {
2622*0b57cec5SDimitry Andric   auto &LAI = LoopAccessInfoMap[L];
2623*0b57cec5SDimitry Andric 
2624*0b57cec5SDimitry Andric   if (!LAI)
26258bcb0991SDimitry Andric     LAI = std::make_unique<LoopAccessInfo>(L, SE, TLI, AA, DT, LI);
2626*0b57cec5SDimitry Andric 
262781ad6265SDimitry Andric   return *LAI;
2628*0b57cec5SDimitry Andric }
2629*0b57cec5SDimitry Andric 
2630*0b57cec5SDimitry Andric void LoopAccessLegacyAnalysis::print(raw_ostream &OS, const Module *M) const {
2631*0b57cec5SDimitry Andric   LoopAccessLegacyAnalysis &LAA = *const_cast<LoopAccessLegacyAnalysis *>(this);
2632*0b57cec5SDimitry Andric 
2633*0b57cec5SDimitry Andric   for (Loop *TopLevelLoop : *LI)
2634*0b57cec5SDimitry Andric     for (Loop *L : depth_first(TopLevelLoop)) {
2635*0b57cec5SDimitry Andric       OS.indent(2) << L->getHeader()->getName() << ":\n";
2636*0b57cec5SDimitry Andric       auto &LAI = LAA.getInfo(L);
2637*0b57cec5SDimitry Andric       LAI.print(OS, 4);
2638*0b57cec5SDimitry Andric     }
2639*0b57cec5SDimitry Andric }
2640*0b57cec5SDimitry Andric 
2641*0b57cec5SDimitry Andric bool LoopAccessLegacyAnalysis::runOnFunction(Function &F) {
2642*0b57cec5SDimitry Andric   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2643*0b57cec5SDimitry Andric   auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
26448bcb0991SDimitry Andric   TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
2645*0b57cec5SDimitry Andric   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2646*0b57cec5SDimitry Andric   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2647*0b57cec5SDimitry Andric   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2648*0b57cec5SDimitry Andric 
2649*0b57cec5SDimitry Andric   return false;
2650*0b57cec5SDimitry Andric }
2651*0b57cec5SDimitry Andric 
2652*0b57cec5SDimitry Andric void LoopAccessLegacyAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
2653fe6060f1SDimitry Andric   AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
2654fe6060f1SDimitry Andric   AU.addRequiredTransitive<AAResultsWrapperPass>();
2655fe6060f1SDimitry Andric   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
2656fe6060f1SDimitry Andric   AU.addRequiredTransitive<LoopInfoWrapperPass>();
2657*0b57cec5SDimitry Andric 
2658*0b57cec5SDimitry Andric   AU.setPreservesAll();
2659*0b57cec5SDimitry Andric }
2660*0b57cec5SDimitry Andric 
2661*0b57cec5SDimitry Andric char LoopAccessLegacyAnalysis::ID = 0;
2662*0b57cec5SDimitry Andric static const char laa_name[] = "Loop Access Analysis";
2663*0b57cec5SDimitry Andric #define LAA_NAME "loop-accesses"
2664*0b57cec5SDimitry Andric 
2665*0b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(LoopAccessLegacyAnalysis, LAA_NAME, laa_name, false, true)
2666*0b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
2667*0b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
2668*0b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2669*0b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
2670*0b57cec5SDimitry Andric INITIALIZE_PASS_END(LoopAccessLegacyAnalysis, LAA_NAME, laa_name, false, true)
2671*0b57cec5SDimitry Andric 
2672*0b57cec5SDimitry Andric AnalysisKey LoopAccessAnalysis::Key;
2673*0b57cec5SDimitry Andric 
2674*0b57cec5SDimitry Andric LoopAccessInfo LoopAccessAnalysis::run(Loop &L, LoopAnalysisManager &AM,
2675*0b57cec5SDimitry Andric                                        LoopStandardAnalysisResults &AR) {
2676*0b57cec5SDimitry Andric   return LoopAccessInfo(&L, &AR.SE, &AR.TLI, &AR.AA, &AR.DT, &AR.LI);
2677*0b57cec5SDimitry Andric }
2678*0b57cec5SDimitry Andric 
2679*0b57cec5SDimitry Andric namespace llvm {
2680*0b57cec5SDimitry Andric 
2681*0b57cec5SDimitry Andric   Pass *createLAAPass() {
2682*0b57cec5SDimitry Andric     return new LoopAccessLegacyAnalysis();
2683*0b57cec5SDimitry Andric   }
2684*0b57cec5SDimitry Andric 
2685*0b57cec5SDimitry Andric } // end namespace llvm
2686