xref: /aosp_15_r20/external/llvm/lib/Analysis/LoopAccessAnalysis.cpp (revision 9880d6810fe72a1726cb53787c6711e909410d58)
1*9880d681SAndroid Build Coastguard Worker //===- LoopAccessAnalysis.cpp - Loop Access Analysis Implementation --------==//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker //                     The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker //
10*9880d681SAndroid Build Coastguard Worker // The implementation for the loop memory dependence that was originally
11*9880d681SAndroid Build Coastguard Worker // developed for the loop vectorizer.
12*9880d681SAndroid Build Coastguard Worker //
13*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
14*9880d681SAndroid Build Coastguard Worker 
15*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/LoopAccessAnalysis.h"
16*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/LoopInfo.h"
17*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/LoopPassManager.h"
18*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ScalarEvolutionExpander.h"
19*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/TargetLibraryInfo.h"
20*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ValueTracking.h"
21*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/VectorUtils.h"
22*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DiagnosticInfo.h"
23*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Dominators.h"
24*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IRBuilder.h"
25*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/PassManager.h"
26*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Debug.h"
27*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/raw_ostream.h"
28*9880d681SAndroid Build Coastguard Worker using namespace llvm;
29*9880d681SAndroid Build Coastguard Worker 
30*9880d681SAndroid Build Coastguard Worker #define DEBUG_TYPE "loop-accesses"
31*9880d681SAndroid Build Coastguard Worker 
32*9880d681SAndroid Build Coastguard Worker static cl::opt<unsigned, true>
33*9880d681SAndroid Build Coastguard Worker VectorizationFactor("force-vector-width", cl::Hidden,
34*9880d681SAndroid Build Coastguard Worker                     cl::desc("Sets the SIMD width. Zero is autoselect."),
35*9880d681SAndroid Build Coastguard Worker                     cl::location(VectorizerParams::VectorizationFactor));
36*9880d681SAndroid Build Coastguard Worker unsigned VectorizerParams::VectorizationFactor;
37*9880d681SAndroid Build Coastguard Worker 
38*9880d681SAndroid Build Coastguard Worker static cl::opt<unsigned, true>
39*9880d681SAndroid Build Coastguard Worker VectorizationInterleave("force-vector-interleave", cl::Hidden,
40*9880d681SAndroid Build Coastguard Worker                         cl::desc("Sets the vectorization interleave count. "
41*9880d681SAndroid Build Coastguard Worker                                  "Zero is autoselect."),
42*9880d681SAndroid Build Coastguard Worker                         cl::location(
43*9880d681SAndroid Build Coastguard Worker                             VectorizerParams::VectorizationInterleave));
44*9880d681SAndroid Build Coastguard Worker unsigned VectorizerParams::VectorizationInterleave;
45*9880d681SAndroid Build Coastguard Worker 
46*9880d681SAndroid Build Coastguard Worker static cl::opt<unsigned, true> RuntimeMemoryCheckThreshold(
47*9880d681SAndroid Build Coastguard Worker     "runtime-memory-check-threshold", cl::Hidden,
48*9880d681SAndroid Build Coastguard Worker     cl::desc("When performing memory disambiguation checks at runtime do not "
49*9880d681SAndroid Build Coastguard Worker              "generate more than this number of comparisons (default = 8)."),
50*9880d681SAndroid Build Coastguard Worker     cl::location(VectorizerParams::RuntimeMemoryCheckThreshold), cl::init(8));
51*9880d681SAndroid Build Coastguard Worker unsigned VectorizerParams::RuntimeMemoryCheckThreshold;
52*9880d681SAndroid Build Coastguard Worker 
53*9880d681SAndroid Build Coastguard Worker /// \brief The maximum iterations used to merge memory checks
54*9880d681SAndroid Build Coastguard Worker static cl::opt<unsigned> MemoryCheckMergeThreshold(
55*9880d681SAndroid Build Coastguard Worker     "memory-check-merge-threshold", cl::Hidden,
56*9880d681SAndroid Build Coastguard Worker     cl::desc("Maximum number of comparisons done when trying to merge "
57*9880d681SAndroid Build Coastguard Worker              "runtime memory checks. (default = 100)"),
58*9880d681SAndroid Build Coastguard Worker     cl::init(100));
59*9880d681SAndroid Build Coastguard Worker 
60*9880d681SAndroid Build Coastguard Worker /// Maximum SIMD width.
61*9880d681SAndroid Build Coastguard Worker const unsigned VectorizerParams::MaxVectorWidth = 64;
62*9880d681SAndroid Build Coastguard Worker 
63*9880d681SAndroid Build Coastguard Worker /// \brief We collect dependences up to this threshold.
64*9880d681SAndroid Build Coastguard Worker static cl::opt<unsigned>
65*9880d681SAndroid Build Coastguard Worker     MaxDependences("max-dependences", cl::Hidden,
66*9880d681SAndroid Build Coastguard Worker                    cl::desc("Maximum number of dependences collected by "
67*9880d681SAndroid Build Coastguard Worker                             "loop-access analysis (default = 100)"),
68*9880d681SAndroid Build Coastguard Worker                    cl::init(100));
69*9880d681SAndroid Build Coastguard Worker 
70*9880d681SAndroid Build Coastguard Worker /// This enables versioning on the strides of symbolically striding memory
71*9880d681SAndroid Build Coastguard Worker /// accesses in code like the following.
72*9880d681SAndroid Build Coastguard Worker ///   for (i = 0; i < N; ++i)
73*9880d681SAndroid Build Coastguard Worker ///     A[i * Stride1] += B[i * Stride2] ...
74*9880d681SAndroid Build Coastguard Worker ///
75*9880d681SAndroid Build Coastguard Worker /// Will be roughly translated to
76*9880d681SAndroid Build Coastguard Worker ///    if (Stride1 == 1 && Stride2 == 1) {
77*9880d681SAndroid Build Coastguard Worker ///      for (i = 0; i < N; i+=4)
78*9880d681SAndroid Build Coastguard Worker ///       A[i:i+3] += ...
79*9880d681SAndroid Build Coastguard Worker ///    } else
80*9880d681SAndroid Build Coastguard Worker ///      ...
81*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> EnableMemAccessVersioning(
82*9880d681SAndroid Build Coastguard Worker     "enable-mem-access-versioning", cl::init(true), cl::Hidden,
83*9880d681SAndroid Build Coastguard Worker     cl::desc("Enable symbolic stride memory access versioning"));
84*9880d681SAndroid Build Coastguard Worker 
85*9880d681SAndroid Build Coastguard Worker /// \brief Enable store-to-load forwarding conflict detection. This option can
86*9880d681SAndroid Build Coastguard Worker /// be disabled for correctness testing.
87*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> EnableForwardingConflictDetection(
88*9880d681SAndroid Build Coastguard Worker     "store-to-load-forwarding-conflict-detection", cl::Hidden,
89*9880d681SAndroid Build Coastguard Worker     cl::desc("Enable conflict detection in loop-access analysis"),
90*9880d681SAndroid Build Coastguard Worker     cl::init(true));
91*9880d681SAndroid Build Coastguard Worker 
isInterleaveForced()92*9880d681SAndroid Build Coastguard Worker bool VectorizerParams::isInterleaveForced() {
93*9880d681SAndroid Build Coastguard Worker   return ::VectorizationInterleave.getNumOccurrences() > 0;
94*9880d681SAndroid Build Coastguard Worker }
95*9880d681SAndroid Build Coastguard Worker 
emitAnalysis(const LoopAccessReport & Message,const Function * TheFunction,const Loop * TheLoop,const char * PassName)96*9880d681SAndroid Build Coastguard Worker void LoopAccessReport::emitAnalysis(const LoopAccessReport &Message,
97*9880d681SAndroid Build Coastguard Worker                                     const Function *TheFunction,
98*9880d681SAndroid Build Coastguard Worker                                     const Loop *TheLoop,
99*9880d681SAndroid Build Coastguard Worker                                     const char *PassName) {
100*9880d681SAndroid Build Coastguard Worker   DebugLoc DL = TheLoop->getStartLoc();
101*9880d681SAndroid Build Coastguard Worker   if (const Instruction *I = Message.getInstr())
102*9880d681SAndroid Build Coastguard Worker     DL = I->getDebugLoc();
103*9880d681SAndroid Build Coastguard Worker   emitOptimizationRemarkAnalysis(TheFunction->getContext(), PassName,
104*9880d681SAndroid Build Coastguard Worker                                  *TheFunction, DL, Message.str());
105*9880d681SAndroid Build Coastguard Worker }
106*9880d681SAndroid Build Coastguard Worker 
stripIntegerCast(Value * V)107*9880d681SAndroid Build Coastguard Worker Value *llvm::stripIntegerCast(Value *V) {
108*9880d681SAndroid Build Coastguard Worker   if (auto *CI = dyn_cast<CastInst>(V))
109*9880d681SAndroid Build Coastguard Worker     if (CI->getOperand(0)->getType()->isIntegerTy())
110*9880d681SAndroid Build Coastguard Worker       return CI->getOperand(0);
111*9880d681SAndroid Build Coastguard Worker   return V;
112*9880d681SAndroid Build Coastguard Worker }
113*9880d681SAndroid Build Coastguard Worker 
replaceSymbolicStrideSCEV(PredicatedScalarEvolution & PSE,const ValueToValueMap & PtrToStride,Value * Ptr,Value * OrigPtr)114*9880d681SAndroid Build Coastguard Worker const SCEV *llvm::replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE,
115*9880d681SAndroid Build Coastguard Worker                                             const ValueToValueMap &PtrToStride,
116*9880d681SAndroid Build Coastguard Worker                                             Value *Ptr, Value *OrigPtr) {
117*9880d681SAndroid Build Coastguard Worker   const SCEV *OrigSCEV = PSE.getSCEV(Ptr);
118*9880d681SAndroid Build Coastguard Worker 
119*9880d681SAndroid Build Coastguard Worker   // If there is an entry in the map return the SCEV of the pointer with the
120*9880d681SAndroid Build Coastguard Worker   // symbolic stride replaced by one.
121*9880d681SAndroid Build Coastguard Worker   ValueToValueMap::const_iterator SI =
122*9880d681SAndroid Build Coastguard Worker       PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
123*9880d681SAndroid Build Coastguard Worker   if (SI != PtrToStride.end()) {
124*9880d681SAndroid Build Coastguard Worker     Value *StrideVal = SI->second;
125*9880d681SAndroid Build Coastguard Worker 
126*9880d681SAndroid Build Coastguard Worker     // Strip casts.
127*9880d681SAndroid Build Coastguard Worker     StrideVal = stripIntegerCast(StrideVal);
128*9880d681SAndroid Build Coastguard Worker 
129*9880d681SAndroid Build Coastguard Worker     // Replace symbolic stride by one.
130*9880d681SAndroid Build Coastguard Worker     Value *One = ConstantInt::get(StrideVal->getType(), 1);
131*9880d681SAndroid Build Coastguard Worker     ValueToValueMap RewriteMap;
132*9880d681SAndroid Build Coastguard Worker     RewriteMap[StrideVal] = One;
133*9880d681SAndroid Build Coastguard Worker 
134*9880d681SAndroid Build Coastguard Worker     ScalarEvolution *SE = PSE.getSE();
135*9880d681SAndroid Build Coastguard Worker     const auto *U = cast<SCEVUnknown>(SE->getSCEV(StrideVal));
136*9880d681SAndroid Build Coastguard Worker     const auto *CT =
137*9880d681SAndroid Build Coastguard Worker         static_cast<const SCEVConstant *>(SE->getOne(StrideVal->getType()));
138*9880d681SAndroid Build Coastguard Worker 
139*9880d681SAndroid Build Coastguard Worker     PSE.addPredicate(*SE->getEqualPredicate(U, CT));
140*9880d681SAndroid Build Coastguard Worker     auto *Expr = PSE.getSCEV(Ptr);
141*9880d681SAndroid Build Coastguard Worker 
142*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV << " by: " << *Expr
143*9880d681SAndroid Build Coastguard Worker                  << "\n");
144*9880d681SAndroid Build Coastguard Worker     return Expr;
145*9880d681SAndroid Build Coastguard Worker   }
146*9880d681SAndroid Build Coastguard Worker 
147*9880d681SAndroid Build Coastguard Worker   // Otherwise, just return the SCEV of the original pointer.
148*9880d681SAndroid Build Coastguard Worker   return OrigSCEV;
149*9880d681SAndroid Build Coastguard Worker }
150*9880d681SAndroid Build Coastguard Worker 
insert(Loop * Lp,Value * Ptr,bool WritePtr,unsigned DepSetId,unsigned ASId,const ValueToValueMap & Strides,PredicatedScalarEvolution & PSE)151*9880d681SAndroid Build Coastguard Worker void RuntimePointerChecking::insert(Loop *Lp, Value *Ptr, bool WritePtr,
152*9880d681SAndroid Build Coastguard Worker                                     unsigned DepSetId, unsigned ASId,
153*9880d681SAndroid Build Coastguard Worker                                     const ValueToValueMap &Strides,
154*9880d681SAndroid Build Coastguard Worker                                     PredicatedScalarEvolution &PSE) {
155*9880d681SAndroid Build Coastguard Worker   // Get the stride replaced scev.
156*9880d681SAndroid Build Coastguard Worker   const SCEV *Sc = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
157*9880d681SAndroid Build Coastguard Worker   ScalarEvolution *SE = PSE.getSE();
158*9880d681SAndroid Build Coastguard Worker 
159*9880d681SAndroid Build Coastguard Worker   const SCEV *ScStart;
160*9880d681SAndroid Build Coastguard Worker   const SCEV *ScEnd;
161*9880d681SAndroid Build Coastguard Worker 
162*9880d681SAndroid Build Coastguard Worker   if (SE->isLoopInvariant(Sc, Lp))
163*9880d681SAndroid Build Coastguard Worker     ScStart = ScEnd = Sc;
164*9880d681SAndroid Build Coastguard Worker   else {
165*9880d681SAndroid Build Coastguard Worker     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
166*9880d681SAndroid Build Coastguard Worker     assert(AR && "Invalid addrec expression");
167*9880d681SAndroid Build Coastguard Worker     const SCEV *Ex = PSE.getBackedgeTakenCount();
168*9880d681SAndroid Build Coastguard Worker 
169*9880d681SAndroid Build Coastguard Worker     ScStart = AR->getStart();
170*9880d681SAndroid Build Coastguard Worker     ScEnd = AR->evaluateAtIteration(Ex, *SE);
171*9880d681SAndroid Build Coastguard Worker     const SCEV *Step = AR->getStepRecurrence(*SE);
172*9880d681SAndroid Build Coastguard Worker 
173*9880d681SAndroid Build Coastguard Worker     // For expressions with negative step, the upper bound is ScStart and the
174*9880d681SAndroid Build Coastguard Worker     // lower bound is ScEnd.
175*9880d681SAndroid Build Coastguard Worker     if (const auto *CStep = dyn_cast<SCEVConstant>(Step)) {
176*9880d681SAndroid Build Coastguard Worker       if (CStep->getValue()->isNegative())
177*9880d681SAndroid Build Coastguard Worker         std::swap(ScStart, ScEnd);
178*9880d681SAndroid Build Coastguard Worker     } else {
179*9880d681SAndroid Build Coastguard Worker       // Fallback case: the step is not constant, but the we can still
180*9880d681SAndroid Build Coastguard Worker       // get the upper and lower bounds of the interval by using min/max
181*9880d681SAndroid Build Coastguard Worker       // expressions.
182*9880d681SAndroid Build Coastguard Worker       ScStart = SE->getUMinExpr(ScStart, ScEnd);
183*9880d681SAndroid Build Coastguard Worker       ScEnd = SE->getUMaxExpr(AR->getStart(), ScEnd);
184*9880d681SAndroid Build Coastguard Worker     }
185*9880d681SAndroid Build Coastguard Worker   }
186*9880d681SAndroid Build Coastguard Worker 
187*9880d681SAndroid Build Coastguard Worker   Pointers.emplace_back(Ptr, ScStart, ScEnd, WritePtr, DepSetId, ASId, Sc);
188*9880d681SAndroid Build Coastguard Worker }
189*9880d681SAndroid Build Coastguard Worker 
190*9880d681SAndroid Build Coastguard Worker SmallVector<RuntimePointerChecking::PointerCheck, 4>
generateChecks() const191*9880d681SAndroid Build Coastguard Worker RuntimePointerChecking::generateChecks() const {
192*9880d681SAndroid Build Coastguard Worker   SmallVector<PointerCheck, 4> Checks;
193*9880d681SAndroid Build Coastguard Worker 
194*9880d681SAndroid Build Coastguard Worker   for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
195*9880d681SAndroid Build Coastguard Worker     for (unsigned J = I + 1; J < CheckingGroups.size(); ++J) {
196*9880d681SAndroid Build Coastguard Worker       const RuntimePointerChecking::CheckingPtrGroup &CGI = CheckingGroups[I];
197*9880d681SAndroid Build Coastguard Worker       const RuntimePointerChecking::CheckingPtrGroup &CGJ = CheckingGroups[J];
198*9880d681SAndroid Build Coastguard Worker 
199*9880d681SAndroid Build Coastguard Worker       if (needsChecking(CGI, CGJ))
200*9880d681SAndroid Build Coastguard Worker         Checks.push_back(std::make_pair(&CGI, &CGJ));
201*9880d681SAndroid Build Coastguard Worker     }
202*9880d681SAndroid Build Coastguard Worker   }
203*9880d681SAndroid Build Coastguard Worker   return Checks;
204*9880d681SAndroid Build Coastguard Worker }
205*9880d681SAndroid Build Coastguard Worker 
generateChecks(MemoryDepChecker::DepCandidates & DepCands,bool UseDependencies)206*9880d681SAndroid Build Coastguard Worker void RuntimePointerChecking::generateChecks(
207*9880d681SAndroid Build Coastguard Worker     MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
208*9880d681SAndroid Build Coastguard Worker   assert(Checks.empty() && "Checks is not empty");
209*9880d681SAndroid Build Coastguard Worker   groupChecks(DepCands, UseDependencies);
210*9880d681SAndroid Build Coastguard Worker   Checks = generateChecks();
211*9880d681SAndroid Build Coastguard Worker }
212*9880d681SAndroid Build Coastguard Worker 
needsChecking(const CheckingPtrGroup & M,const CheckingPtrGroup & N) const213*9880d681SAndroid Build Coastguard Worker bool RuntimePointerChecking::needsChecking(const CheckingPtrGroup &M,
214*9880d681SAndroid Build Coastguard Worker                                            const CheckingPtrGroup &N) const {
215*9880d681SAndroid Build Coastguard Worker   for (unsigned I = 0, EI = M.Members.size(); EI != I; ++I)
216*9880d681SAndroid Build Coastguard Worker     for (unsigned J = 0, EJ = N.Members.size(); EJ != J; ++J)
217*9880d681SAndroid Build Coastguard Worker       if (needsChecking(M.Members[I], N.Members[J]))
218*9880d681SAndroid Build Coastguard Worker         return true;
219*9880d681SAndroid Build Coastguard Worker   return false;
220*9880d681SAndroid Build Coastguard Worker }
221*9880d681SAndroid Build Coastguard Worker 
222*9880d681SAndroid Build Coastguard Worker /// Compare \p I and \p J and return the minimum.
223*9880d681SAndroid Build Coastguard Worker /// Return nullptr in case we couldn't find an answer.
getMinFromExprs(const SCEV * I,const SCEV * J,ScalarEvolution * SE)224*9880d681SAndroid Build Coastguard Worker static const SCEV *getMinFromExprs(const SCEV *I, const SCEV *J,
225*9880d681SAndroid Build Coastguard Worker                                    ScalarEvolution *SE) {
226*9880d681SAndroid Build Coastguard Worker   const SCEV *Diff = SE->getMinusSCEV(J, I);
227*9880d681SAndroid Build Coastguard Worker   const SCEVConstant *C = dyn_cast<const SCEVConstant>(Diff);
228*9880d681SAndroid Build Coastguard Worker 
229*9880d681SAndroid Build Coastguard Worker   if (!C)
230*9880d681SAndroid Build Coastguard Worker     return nullptr;
231*9880d681SAndroid Build Coastguard Worker   if (C->getValue()->isNegative())
232*9880d681SAndroid Build Coastguard Worker     return J;
233*9880d681SAndroid Build Coastguard Worker   return I;
234*9880d681SAndroid Build Coastguard Worker }
235*9880d681SAndroid Build Coastguard Worker 
addPointer(unsigned Index)236*9880d681SAndroid Build Coastguard Worker bool RuntimePointerChecking::CheckingPtrGroup::addPointer(unsigned Index) {
237*9880d681SAndroid Build Coastguard Worker   const SCEV *Start = RtCheck.Pointers[Index].Start;
238*9880d681SAndroid Build Coastguard Worker   const SCEV *End = RtCheck.Pointers[Index].End;
239*9880d681SAndroid Build Coastguard Worker 
240*9880d681SAndroid Build Coastguard Worker   // Compare the starts and ends with the known minimum and maximum
241*9880d681SAndroid Build Coastguard Worker   // of this set. We need to know how we compare against the min/max
242*9880d681SAndroid Build Coastguard Worker   // of the set in order to be able to emit memchecks.
243*9880d681SAndroid Build Coastguard Worker   const SCEV *Min0 = getMinFromExprs(Start, Low, RtCheck.SE);
244*9880d681SAndroid Build Coastguard Worker   if (!Min0)
245*9880d681SAndroid Build Coastguard Worker     return false;
246*9880d681SAndroid Build Coastguard Worker 
247*9880d681SAndroid Build Coastguard Worker   const SCEV *Min1 = getMinFromExprs(End, High, RtCheck.SE);
248*9880d681SAndroid Build Coastguard Worker   if (!Min1)
249*9880d681SAndroid Build Coastguard Worker     return false;
250*9880d681SAndroid Build Coastguard Worker 
251*9880d681SAndroid Build Coastguard Worker   // Update the low bound  expression if we've found a new min value.
252*9880d681SAndroid Build Coastguard Worker   if (Min0 == Start)
253*9880d681SAndroid Build Coastguard Worker     Low = Start;
254*9880d681SAndroid Build Coastguard Worker 
255*9880d681SAndroid Build Coastguard Worker   // Update the high bound expression if we've found a new max value.
256*9880d681SAndroid Build Coastguard Worker   if (Min1 != End)
257*9880d681SAndroid Build Coastguard Worker     High = End;
258*9880d681SAndroid Build Coastguard Worker 
259*9880d681SAndroid Build Coastguard Worker   Members.push_back(Index);
260*9880d681SAndroid Build Coastguard Worker   return true;
261*9880d681SAndroid Build Coastguard Worker }
262*9880d681SAndroid Build Coastguard Worker 
groupChecks(MemoryDepChecker::DepCandidates & DepCands,bool UseDependencies)263*9880d681SAndroid Build Coastguard Worker void RuntimePointerChecking::groupChecks(
264*9880d681SAndroid Build Coastguard Worker     MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
265*9880d681SAndroid Build Coastguard Worker   // We build the groups from dependency candidates equivalence classes
266*9880d681SAndroid Build Coastguard Worker   // because:
267*9880d681SAndroid Build Coastguard Worker   //    - We know that pointers in the same equivalence class share
268*9880d681SAndroid Build Coastguard Worker   //      the same underlying object and therefore there is a chance
269*9880d681SAndroid Build Coastguard Worker   //      that we can compare pointers
270*9880d681SAndroid Build Coastguard Worker   //    - We wouldn't be able to merge two pointers for which we need
271*9880d681SAndroid Build Coastguard Worker   //      to emit a memcheck. The classes in DepCands are already
272*9880d681SAndroid Build Coastguard Worker   //      conveniently built such that no two pointers in the same
273*9880d681SAndroid Build Coastguard Worker   //      class need checking against each other.
274*9880d681SAndroid Build Coastguard Worker 
275*9880d681SAndroid Build Coastguard Worker   // We use the following (greedy) algorithm to construct the groups
276*9880d681SAndroid Build Coastguard Worker   // For every pointer in the equivalence class:
277*9880d681SAndroid Build Coastguard Worker   //   For each existing group:
278*9880d681SAndroid Build Coastguard Worker   //   - if the difference between this pointer and the min/max bounds
279*9880d681SAndroid Build Coastguard Worker   //     of the group is a constant, then make the pointer part of the
280*9880d681SAndroid Build Coastguard Worker   //     group and update the min/max bounds of that group as required.
281*9880d681SAndroid Build Coastguard Worker 
282*9880d681SAndroid Build Coastguard Worker   CheckingGroups.clear();
283*9880d681SAndroid Build Coastguard Worker 
284*9880d681SAndroid Build Coastguard Worker   // If we need to check two pointers to the same underlying object
285*9880d681SAndroid Build Coastguard Worker   // with a non-constant difference, we shouldn't perform any pointer
286*9880d681SAndroid Build Coastguard Worker   // grouping with those pointers. This is because we can easily get
287*9880d681SAndroid Build Coastguard Worker   // into cases where the resulting check would return false, even when
288*9880d681SAndroid Build Coastguard Worker   // the accesses are safe.
289*9880d681SAndroid Build Coastguard Worker   //
290*9880d681SAndroid Build Coastguard Worker   // The following example shows this:
291*9880d681SAndroid Build Coastguard Worker   // for (i = 0; i < 1000; ++i)
292*9880d681SAndroid Build Coastguard Worker   //   a[5000 + i * m] = a[i] + a[i + 9000]
293*9880d681SAndroid Build Coastguard Worker   //
294*9880d681SAndroid Build Coastguard Worker   // Here grouping gives a check of (5000, 5000 + 1000 * m) against
295*9880d681SAndroid Build Coastguard Worker   // (0, 10000) which is always false. However, if m is 1, there is no
296*9880d681SAndroid Build Coastguard Worker   // dependence. Not grouping the checks for a[i] and a[i + 9000] allows
297*9880d681SAndroid Build Coastguard Worker   // us to perform an accurate check in this case.
298*9880d681SAndroid Build Coastguard Worker   //
299*9880d681SAndroid Build Coastguard Worker   // The above case requires that we have an UnknownDependence between
300*9880d681SAndroid Build Coastguard Worker   // accesses to the same underlying object. This cannot happen unless
301*9880d681SAndroid Build Coastguard Worker   // ShouldRetryWithRuntimeCheck is set, and therefore UseDependencies
302*9880d681SAndroid Build Coastguard Worker   // is also false. In this case we will use the fallback path and create
303*9880d681SAndroid Build Coastguard Worker   // separate checking groups for all pointers.
304*9880d681SAndroid Build Coastguard Worker 
305*9880d681SAndroid Build Coastguard Worker   // If we don't have the dependency partitions, construct a new
306*9880d681SAndroid Build Coastguard Worker   // checking pointer group for each pointer. This is also required
307*9880d681SAndroid Build Coastguard Worker   // for correctness, because in this case we can have checking between
308*9880d681SAndroid Build Coastguard Worker   // pointers to the same underlying object.
309*9880d681SAndroid Build Coastguard Worker   if (!UseDependencies) {
310*9880d681SAndroid Build Coastguard Worker     for (unsigned I = 0; I < Pointers.size(); ++I)
311*9880d681SAndroid Build Coastguard Worker       CheckingGroups.push_back(CheckingPtrGroup(I, *this));
312*9880d681SAndroid Build Coastguard Worker     return;
313*9880d681SAndroid Build Coastguard Worker   }
314*9880d681SAndroid Build Coastguard Worker 
315*9880d681SAndroid Build Coastguard Worker   unsigned TotalComparisons = 0;
316*9880d681SAndroid Build Coastguard Worker 
317*9880d681SAndroid Build Coastguard Worker   DenseMap<Value *, unsigned> PositionMap;
318*9880d681SAndroid Build Coastguard Worker   for (unsigned Index = 0; Index < Pointers.size(); ++Index)
319*9880d681SAndroid Build Coastguard Worker     PositionMap[Pointers[Index].PointerValue] = Index;
320*9880d681SAndroid Build Coastguard Worker 
321*9880d681SAndroid Build Coastguard Worker   // We need to keep track of what pointers we've already seen so we
322*9880d681SAndroid Build Coastguard Worker   // don't process them twice.
323*9880d681SAndroid Build Coastguard Worker   SmallSet<unsigned, 2> Seen;
324*9880d681SAndroid Build Coastguard Worker 
325*9880d681SAndroid Build Coastguard Worker   // Go through all equivalence classes, get the "pointer check groups"
326*9880d681SAndroid Build Coastguard Worker   // and add them to the overall solution. We use the order in which accesses
327*9880d681SAndroid Build Coastguard Worker   // appear in 'Pointers' to enforce determinism.
328*9880d681SAndroid Build Coastguard Worker   for (unsigned I = 0; I < Pointers.size(); ++I) {
329*9880d681SAndroid Build Coastguard Worker     // We've seen this pointer before, and therefore already processed
330*9880d681SAndroid Build Coastguard Worker     // its equivalence class.
331*9880d681SAndroid Build Coastguard Worker     if (Seen.count(I))
332*9880d681SAndroid Build Coastguard Worker       continue;
333*9880d681SAndroid Build Coastguard Worker 
334*9880d681SAndroid Build Coastguard Worker     MemoryDepChecker::MemAccessInfo Access(Pointers[I].PointerValue,
335*9880d681SAndroid Build Coastguard Worker                                            Pointers[I].IsWritePtr);
336*9880d681SAndroid Build Coastguard Worker 
337*9880d681SAndroid Build Coastguard Worker     SmallVector<CheckingPtrGroup, 2> Groups;
338*9880d681SAndroid Build Coastguard Worker     auto LeaderI = DepCands.findValue(DepCands.getLeaderValue(Access));
339*9880d681SAndroid Build Coastguard Worker 
340*9880d681SAndroid Build Coastguard Worker     // Because DepCands is constructed by visiting accesses in the order in
341*9880d681SAndroid Build Coastguard Worker     // which they appear in alias sets (which is deterministic) and the
342*9880d681SAndroid Build Coastguard Worker     // iteration order within an equivalence class member is only dependent on
343*9880d681SAndroid Build Coastguard Worker     // the order in which unions and insertions are performed on the
344*9880d681SAndroid Build Coastguard Worker     // equivalence class, the iteration order is deterministic.
345*9880d681SAndroid Build Coastguard Worker     for (auto MI = DepCands.member_begin(LeaderI), ME = DepCands.member_end();
346*9880d681SAndroid Build Coastguard Worker          MI != ME; ++MI) {
347*9880d681SAndroid Build Coastguard Worker       unsigned Pointer = PositionMap[MI->getPointer()];
348*9880d681SAndroid Build Coastguard Worker       bool Merged = false;
349*9880d681SAndroid Build Coastguard Worker       // Mark this pointer as seen.
350*9880d681SAndroid Build Coastguard Worker       Seen.insert(Pointer);
351*9880d681SAndroid Build Coastguard Worker 
352*9880d681SAndroid Build Coastguard Worker       // Go through all the existing sets and see if we can find one
353*9880d681SAndroid Build Coastguard Worker       // which can include this pointer.
354*9880d681SAndroid Build Coastguard Worker       for (CheckingPtrGroup &Group : Groups) {
355*9880d681SAndroid Build Coastguard Worker         // Don't perform more than a certain amount of comparisons.
356*9880d681SAndroid Build Coastguard Worker         // This should limit the cost of grouping the pointers to something
357*9880d681SAndroid Build Coastguard Worker         // reasonable.  If we do end up hitting this threshold, the algorithm
358*9880d681SAndroid Build Coastguard Worker         // will create separate groups for all remaining pointers.
359*9880d681SAndroid Build Coastguard Worker         if (TotalComparisons > MemoryCheckMergeThreshold)
360*9880d681SAndroid Build Coastguard Worker           break;
361*9880d681SAndroid Build Coastguard Worker 
362*9880d681SAndroid Build Coastguard Worker         TotalComparisons++;
363*9880d681SAndroid Build Coastguard Worker 
364*9880d681SAndroid Build Coastguard Worker         if (Group.addPointer(Pointer)) {
365*9880d681SAndroid Build Coastguard Worker           Merged = true;
366*9880d681SAndroid Build Coastguard Worker           break;
367*9880d681SAndroid Build Coastguard Worker         }
368*9880d681SAndroid Build Coastguard Worker       }
369*9880d681SAndroid Build Coastguard Worker 
370*9880d681SAndroid Build Coastguard Worker       if (!Merged)
371*9880d681SAndroid Build Coastguard Worker         // We couldn't add this pointer to any existing set or the threshold
372*9880d681SAndroid Build Coastguard Worker         // for the number of comparisons has been reached. Create a new group
373*9880d681SAndroid Build Coastguard Worker         // to hold the current pointer.
374*9880d681SAndroid Build Coastguard Worker         Groups.push_back(CheckingPtrGroup(Pointer, *this));
375*9880d681SAndroid Build Coastguard Worker     }
376*9880d681SAndroid Build Coastguard Worker 
377*9880d681SAndroid Build Coastguard Worker     // We've computed the grouped checks for this partition.
378*9880d681SAndroid Build Coastguard Worker     // Save the results and continue with the next one.
379*9880d681SAndroid Build Coastguard Worker     std::copy(Groups.begin(), Groups.end(), std::back_inserter(CheckingGroups));
380*9880d681SAndroid Build Coastguard Worker   }
381*9880d681SAndroid Build Coastguard Worker }
382*9880d681SAndroid Build Coastguard Worker 
arePointersInSamePartition(const SmallVectorImpl<int> & PtrToPartition,unsigned PtrIdx1,unsigned PtrIdx2)383*9880d681SAndroid Build Coastguard Worker bool RuntimePointerChecking::arePointersInSamePartition(
384*9880d681SAndroid Build Coastguard Worker     const SmallVectorImpl<int> &PtrToPartition, unsigned PtrIdx1,
385*9880d681SAndroid Build Coastguard Worker     unsigned PtrIdx2) {
386*9880d681SAndroid Build Coastguard Worker   return (PtrToPartition[PtrIdx1] != -1 &&
387*9880d681SAndroid Build Coastguard Worker           PtrToPartition[PtrIdx1] == PtrToPartition[PtrIdx2]);
388*9880d681SAndroid Build Coastguard Worker }
389*9880d681SAndroid Build Coastguard Worker 
needsChecking(unsigned I,unsigned J) const390*9880d681SAndroid Build Coastguard Worker bool RuntimePointerChecking::needsChecking(unsigned I, unsigned J) const {
391*9880d681SAndroid Build Coastguard Worker   const PointerInfo &PointerI = Pointers[I];
392*9880d681SAndroid Build Coastguard Worker   const PointerInfo &PointerJ = Pointers[J];
393*9880d681SAndroid Build Coastguard Worker 
394*9880d681SAndroid Build Coastguard Worker   // No need to check if two readonly pointers intersect.
395*9880d681SAndroid Build Coastguard Worker   if (!PointerI.IsWritePtr && !PointerJ.IsWritePtr)
396*9880d681SAndroid Build Coastguard Worker     return false;
397*9880d681SAndroid Build Coastguard Worker 
398*9880d681SAndroid Build Coastguard Worker   // Only need to check pointers between two different dependency sets.
399*9880d681SAndroid Build Coastguard Worker   if (PointerI.DependencySetId == PointerJ.DependencySetId)
400*9880d681SAndroid Build Coastguard Worker     return false;
401*9880d681SAndroid Build Coastguard Worker 
402*9880d681SAndroid Build Coastguard Worker   // Only need to check pointers in the same alias set.
403*9880d681SAndroid Build Coastguard Worker   if (PointerI.AliasSetId != PointerJ.AliasSetId)
404*9880d681SAndroid Build Coastguard Worker     return false;
405*9880d681SAndroid Build Coastguard Worker 
406*9880d681SAndroid Build Coastguard Worker   return true;
407*9880d681SAndroid Build Coastguard Worker }
408*9880d681SAndroid Build Coastguard Worker 
printChecks(raw_ostream & OS,const SmallVectorImpl<PointerCheck> & Checks,unsigned Depth) const409*9880d681SAndroid Build Coastguard Worker void RuntimePointerChecking::printChecks(
410*9880d681SAndroid Build Coastguard Worker     raw_ostream &OS, const SmallVectorImpl<PointerCheck> &Checks,
411*9880d681SAndroid Build Coastguard Worker     unsigned Depth) const {
412*9880d681SAndroid Build Coastguard Worker   unsigned N = 0;
413*9880d681SAndroid Build Coastguard Worker   for (const auto &Check : Checks) {
414*9880d681SAndroid Build Coastguard Worker     const auto &First = Check.first->Members, &Second = Check.second->Members;
415*9880d681SAndroid Build Coastguard Worker 
416*9880d681SAndroid Build Coastguard Worker     OS.indent(Depth) << "Check " << N++ << ":\n";
417*9880d681SAndroid Build Coastguard Worker 
418*9880d681SAndroid Build Coastguard Worker     OS.indent(Depth + 2) << "Comparing group (" << Check.first << "):\n";
419*9880d681SAndroid Build Coastguard Worker     for (unsigned K = 0; K < First.size(); ++K)
420*9880d681SAndroid Build Coastguard Worker       OS.indent(Depth + 2) << *Pointers[First[K]].PointerValue << "\n";
421*9880d681SAndroid Build Coastguard Worker 
422*9880d681SAndroid Build Coastguard Worker     OS.indent(Depth + 2) << "Against group (" << Check.second << "):\n";
423*9880d681SAndroid Build Coastguard Worker     for (unsigned K = 0; K < Second.size(); ++K)
424*9880d681SAndroid Build Coastguard Worker       OS.indent(Depth + 2) << *Pointers[Second[K]].PointerValue << "\n";
425*9880d681SAndroid Build Coastguard Worker   }
426*9880d681SAndroid Build Coastguard Worker }
427*9880d681SAndroid Build Coastguard Worker 
print(raw_ostream & OS,unsigned Depth) const428*9880d681SAndroid Build Coastguard Worker void RuntimePointerChecking::print(raw_ostream &OS, unsigned Depth) const {
429*9880d681SAndroid Build Coastguard Worker 
430*9880d681SAndroid Build Coastguard Worker   OS.indent(Depth) << "Run-time memory checks:\n";
431*9880d681SAndroid Build Coastguard Worker   printChecks(OS, Checks, Depth);
432*9880d681SAndroid Build Coastguard Worker 
433*9880d681SAndroid Build Coastguard Worker   OS.indent(Depth) << "Grouped accesses:\n";
434*9880d681SAndroid Build Coastguard Worker   for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
435*9880d681SAndroid Build Coastguard Worker     const auto &CG = CheckingGroups[I];
436*9880d681SAndroid Build Coastguard Worker 
437*9880d681SAndroid Build Coastguard Worker     OS.indent(Depth + 2) << "Group " << &CG << ":\n";
438*9880d681SAndroid Build Coastguard Worker     OS.indent(Depth + 4) << "(Low: " << *CG.Low << " High: " << *CG.High
439*9880d681SAndroid Build Coastguard Worker                          << ")\n";
440*9880d681SAndroid Build Coastguard Worker     for (unsigned J = 0; J < CG.Members.size(); ++J) {
441*9880d681SAndroid Build Coastguard Worker       OS.indent(Depth + 6) << "Member: " << *Pointers[CG.Members[J]].Expr
442*9880d681SAndroid Build Coastguard Worker                            << "\n";
443*9880d681SAndroid Build Coastguard Worker     }
444*9880d681SAndroid Build Coastguard Worker   }
445*9880d681SAndroid Build Coastguard Worker }
446*9880d681SAndroid Build Coastguard Worker 
447*9880d681SAndroid Build Coastguard Worker namespace {
448*9880d681SAndroid Build Coastguard Worker /// \brief Analyses memory accesses in a loop.
449*9880d681SAndroid Build Coastguard Worker ///
450*9880d681SAndroid Build Coastguard Worker /// Checks whether run time pointer checks are needed and builds sets for data
451*9880d681SAndroid Build Coastguard Worker /// dependence checking.
452*9880d681SAndroid Build Coastguard Worker class AccessAnalysis {
453*9880d681SAndroid Build Coastguard Worker public:
454*9880d681SAndroid Build Coastguard Worker   /// \brief Read or write access location.
455*9880d681SAndroid Build Coastguard Worker   typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
456*9880d681SAndroid Build Coastguard Worker   typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
457*9880d681SAndroid Build Coastguard Worker 
AccessAnalysis(const DataLayout & Dl,AliasAnalysis * AA,LoopInfo * LI,MemoryDepChecker::DepCandidates & DA,PredicatedScalarEvolution & PSE)458*9880d681SAndroid Build Coastguard Worker   AccessAnalysis(const DataLayout &Dl, AliasAnalysis *AA, LoopInfo *LI,
459*9880d681SAndroid Build Coastguard Worker                  MemoryDepChecker::DepCandidates &DA,
460*9880d681SAndroid Build Coastguard Worker                  PredicatedScalarEvolution &PSE)
461*9880d681SAndroid Build Coastguard Worker       : DL(Dl), AST(*AA), LI(LI), DepCands(DA), IsRTCheckAnalysisNeeded(false),
462*9880d681SAndroid Build Coastguard Worker         PSE(PSE) {}
463*9880d681SAndroid Build Coastguard Worker 
464*9880d681SAndroid Build Coastguard Worker   /// \brief Register a load  and whether it is only read from.
addLoad(MemoryLocation & Loc,bool IsReadOnly)465*9880d681SAndroid Build Coastguard Worker   void addLoad(MemoryLocation &Loc, bool IsReadOnly) {
466*9880d681SAndroid Build Coastguard Worker     Value *Ptr = const_cast<Value*>(Loc.Ptr);
467*9880d681SAndroid Build Coastguard Worker     AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
468*9880d681SAndroid Build Coastguard Worker     Accesses.insert(MemAccessInfo(Ptr, false));
469*9880d681SAndroid Build Coastguard Worker     if (IsReadOnly)
470*9880d681SAndroid Build Coastguard Worker       ReadOnlyPtr.insert(Ptr);
471*9880d681SAndroid Build Coastguard Worker   }
472*9880d681SAndroid Build Coastguard Worker 
473*9880d681SAndroid Build Coastguard Worker   /// \brief Register a store.
addStore(MemoryLocation & Loc)474*9880d681SAndroid Build Coastguard Worker   void addStore(MemoryLocation &Loc) {
475*9880d681SAndroid Build Coastguard Worker     Value *Ptr = const_cast<Value*>(Loc.Ptr);
476*9880d681SAndroid Build Coastguard Worker     AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
477*9880d681SAndroid Build Coastguard Worker     Accesses.insert(MemAccessInfo(Ptr, true));
478*9880d681SAndroid Build Coastguard Worker   }
479*9880d681SAndroid Build Coastguard Worker 
480*9880d681SAndroid Build Coastguard Worker   /// \brief Check whether we can check the pointers at runtime for
481*9880d681SAndroid Build Coastguard Worker   /// non-intersection.
482*9880d681SAndroid Build Coastguard Worker   ///
483*9880d681SAndroid Build Coastguard Worker   /// Returns true if we need no check or if we do and we can generate them
484*9880d681SAndroid Build Coastguard Worker   /// (i.e. the pointers have computable bounds).
485*9880d681SAndroid Build Coastguard Worker   bool canCheckPtrAtRT(RuntimePointerChecking &RtCheck, ScalarEvolution *SE,
486*9880d681SAndroid Build Coastguard Worker                        Loop *TheLoop, const ValueToValueMap &Strides,
487*9880d681SAndroid Build Coastguard Worker                        bool ShouldCheckWrap = false);
488*9880d681SAndroid Build Coastguard Worker 
489*9880d681SAndroid Build Coastguard Worker   /// \brief Goes over all memory accesses, checks whether a RT check is needed
490*9880d681SAndroid Build Coastguard Worker   /// and builds sets of dependent accesses.
buildDependenceSets()491*9880d681SAndroid Build Coastguard Worker   void buildDependenceSets() {
492*9880d681SAndroid Build Coastguard Worker     processMemAccesses();
493*9880d681SAndroid Build Coastguard Worker   }
494*9880d681SAndroid Build Coastguard Worker 
495*9880d681SAndroid Build Coastguard Worker   /// \brief Initial processing of memory accesses determined that we need to
496*9880d681SAndroid Build Coastguard Worker   /// perform dependency checking.
497*9880d681SAndroid Build Coastguard Worker   ///
498*9880d681SAndroid Build Coastguard Worker   /// Note that this can later be cleared if we retry memcheck analysis without
499*9880d681SAndroid Build Coastguard Worker   /// dependency checking (i.e. ShouldRetryWithRuntimeCheck).
isDependencyCheckNeeded()500*9880d681SAndroid Build Coastguard Worker   bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
501*9880d681SAndroid Build Coastguard Worker 
502*9880d681SAndroid Build Coastguard Worker   /// We decided that no dependence analysis would be used.  Reset the state.
resetDepChecks(MemoryDepChecker & DepChecker)503*9880d681SAndroid Build Coastguard Worker   void resetDepChecks(MemoryDepChecker &DepChecker) {
504*9880d681SAndroid Build Coastguard Worker     CheckDeps.clear();
505*9880d681SAndroid Build Coastguard Worker     DepChecker.clearDependences();
506*9880d681SAndroid Build Coastguard Worker   }
507*9880d681SAndroid Build Coastguard Worker 
getDependenciesToCheck()508*9880d681SAndroid Build Coastguard Worker   MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
509*9880d681SAndroid Build Coastguard Worker 
510*9880d681SAndroid Build Coastguard Worker private:
511*9880d681SAndroid Build Coastguard Worker   typedef SetVector<MemAccessInfo> PtrAccessSet;
512*9880d681SAndroid Build Coastguard Worker 
513*9880d681SAndroid Build Coastguard Worker   /// \brief Go over all memory access and check whether runtime pointer checks
514*9880d681SAndroid Build Coastguard Worker   /// are needed and build sets of dependency check candidates.
515*9880d681SAndroid Build Coastguard Worker   void processMemAccesses();
516*9880d681SAndroid Build Coastguard Worker 
517*9880d681SAndroid Build Coastguard Worker   /// Set of all accesses.
518*9880d681SAndroid Build Coastguard Worker   PtrAccessSet Accesses;
519*9880d681SAndroid Build Coastguard Worker 
520*9880d681SAndroid Build Coastguard Worker   const DataLayout &DL;
521*9880d681SAndroid Build Coastguard Worker 
522*9880d681SAndroid Build Coastguard Worker   /// Set of accesses that need a further dependence check.
523*9880d681SAndroid Build Coastguard Worker   MemAccessInfoSet CheckDeps;
524*9880d681SAndroid Build Coastguard Worker 
525*9880d681SAndroid Build Coastguard Worker   /// Set of pointers that are read only.
526*9880d681SAndroid Build Coastguard Worker   SmallPtrSet<Value*, 16> ReadOnlyPtr;
527*9880d681SAndroid Build Coastguard Worker 
528*9880d681SAndroid Build Coastguard Worker   /// An alias set tracker to partition the access set by underlying object and
529*9880d681SAndroid Build Coastguard Worker   //intrinsic property (such as TBAA metadata).
530*9880d681SAndroid Build Coastguard Worker   AliasSetTracker AST;
531*9880d681SAndroid Build Coastguard Worker 
532*9880d681SAndroid Build Coastguard Worker   LoopInfo *LI;
533*9880d681SAndroid Build Coastguard Worker 
534*9880d681SAndroid Build Coastguard Worker   /// Sets of potentially dependent accesses - members of one set share an
535*9880d681SAndroid Build Coastguard Worker   /// underlying pointer. The set "CheckDeps" identfies which sets really need a
536*9880d681SAndroid Build Coastguard Worker   /// dependence check.
537*9880d681SAndroid Build Coastguard Worker   MemoryDepChecker::DepCandidates &DepCands;
538*9880d681SAndroid Build Coastguard Worker 
539*9880d681SAndroid Build Coastguard Worker   /// \brief Initial processing of memory accesses determined that we may need
540*9880d681SAndroid Build Coastguard Worker   /// to add memchecks.  Perform the analysis to determine the necessary checks.
541*9880d681SAndroid Build Coastguard Worker   ///
542*9880d681SAndroid Build Coastguard Worker   /// Note that, this is different from isDependencyCheckNeeded.  When we retry
543*9880d681SAndroid Build Coastguard Worker   /// memcheck analysis without dependency checking
544*9880d681SAndroid Build Coastguard Worker   /// (i.e. ShouldRetryWithRuntimeCheck), isDependencyCheckNeeded is cleared
545*9880d681SAndroid Build Coastguard Worker   /// while this remains set if we have potentially dependent accesses.
546*9880d681SAndroid Build Coastguard Worker   bool IsRTCheckAnalysisNeeded;
547*9880d681SAndroid Build Coastguard Worker 
548*9880d681SAndroid Build Coastguard Worker   /// The SCEV predicate containing all the SCEV-related assumptions.
549*9880d681SAndroid Build Coastguard Worker   PredicatedScalarEvolution &PSE;
550*9880d681SAndroid Build Coastguard Worker };
551*9880d681SAndroid Build Coastguard Worker 
552*9880d681SAndroid Build Coastguard Worker } // end anonymous namespace
553*9880d681SAndroid Build Coastguard Worker 
554*9880d681SAndroid Build Coastguard Worker /// \brief Check whether a pointer can participate in a runtime bounds check.
hasComputableBounds(PredicatedScalarEvolution & PSE,const ValueToValueMap & Strides,Value * Ptr,Loop * L)555*9880d681SAndroid Build Coastguard Worker static bool hasComputableBounds(PredicatedScalarEvolution &PSE,
556*9880d681SAndroid Build Coastguard Worker                                 const ValueToValueMap &Strides, Value *Ptr,
557*9880d681SAndroid Build Coastguard Worker                                 Loop *L) {
558*9880d681SAndroid Build Coastguard Worker   const SCEV *PtrScev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
559*9880d681SAndroid Build Coastguard Worker 
560*9880d681SAndroid Build Coastguard Worker   // The bounds for loop-invariant pointer is trivial.
561*9880d681SAndroid Build Coastguard Worker   if (PSE.getSE()->isLoopInvariant(PtrScev, L))
562*9880d681SAndroid Build Coastguard Worker     return true;
563*9880d681SAndroid Build Coastguard Worker 
564*9880d681SAndroid Build Coastguard Worker   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
565*9880d681SAndroid Build Coastguard Worker   if (!AR)
566*9880d681SAndroid Build Coastguard Worker     return false;
567*9880d681SAndroid Build Coastguard Worker 
568*9880d681SAndroid Build Coastguard Worker   return AR->isAffine();
569*9880d681SAndroid Build Coastguard Worker }
570*9880d681SAndroid Build Coastguard Worker 
571*9880d681SAndroid Build Coastguard Worker /// \brief Check whether a pointer address cannot wrap.
isNoWrap(PredicatedScalarEvolution & PSE,const ValueToValueMap & Strides,Value * Ptr,Loop * L)572*9880d681SAndroid Build Coastguard Worker static bool isNoWrap(PredicatedScalarEvolution &PSE,
573*9880d681SAndroid Build Coastguard Worker                      const ValueToValueMap &Strides, Value *Ptr, Loop *L) {
574*9880d681SAndroid Build Coastguard Worker   const SCEV *PtrScev = PSE.getSCEV(Ptr);
575*9880d681SAndroid Build Coastguard Worker   if (PSE.getSE()->isLoopInvariant(PtrScev, L))
576*9880d681SAndroid Build Coastguard Worker     return true;
577*9880d681SAndroid Build Coastguard Worker 
578*9880d681SAndroid Build Coastguard Worker   int64_t Stride = getPtrStride(PSE, Ptr, L, Strides);
579*9880d681SAndroid Build Coastguard Worker   return Stride == 1;
580*9880d681SAndroid Build Coastguard Worker }
581*9880d681SAndroid Build Coastguard Worker 
canCheckPtrAtRT(RuntimePointerChecking & RtCheck,ScalarEvolution * SE,Loop * TheLoop,const ValueToValueMap & StridesMap,bool ShouldCheckWrap)582*9880d681SAndroid Build Coastguard Worker bool AccessAnalysis::canCheckPtrAtRT(RuntimePointerChecking &RtCheck,
583*9880d681SAndroid Build Coastguard Worker                                      ScalarEvolution *SE, Loop *TheLoop,
584*9880d681SAndroid Build Coastguard Worker                                      const ValueToValueMap &StridesMap,
585*9880d681SAndroid Build Coastguard Worker                                      bool ShouldCheckWrap) {
586*9880d681SAndroid Build Coastguard Worker   // Find pointers with computable bounds. We are going to use this information
587*9880d681SAndroid Build Coastguard Worker   // to place a runtime bound check.
588*9880d681SAndroid Build Coastguard Worker   bool CanDoRT = true;
589*9880d681SAndroid Build Coastguard Worker 
590*9880d681SAndroid Build Coastguard Worker   bool NeedRTCheck = false;
591*9880d681SAndroid Build Coastguard Worker   if (!IsRTCheckAnalysisNeeded) return true;
592*9880d681SAndroid Build Coastguard Worker 
593*9880d681SAndroid Build Coastguard Worker   bool IsDepCheckNeeded = isDependencyCheckNeeded();
594*9880d681SAndroid Build Coastguard Worker 
595*9880d681SAndroid Build Coastguard Worker   // We assign a consecutive id to access from different alias sets.
596*9880d681SAndroid Build Coastguard Worker   // Accesses between different groups doesn't need to be checked.
597*9880d681SAndroid Build Coastguard Worker   unsigned ASId = 1;
598*9880d681SAndroid Build Coastguard Worker   for (auto &AS : AST) {
599*9880d681SAndroid Build Coastguard Worker     int NumReadPtrChecks = 0;
600*9880d681SAndroid Build Coastguard Worker     int NumWritePtrChecks = 0;
601*9880d681SAndroid Build Coastguard Worker 
602*9880d681SAndroid Build Coastguard Worker     // We assign consecutive id to access from different dependence sets.
603*9880d681SAndroid Build Coastguard Worker     // Accesses within the same set don't need a runtime check.
604*9880d681SAndroid Build Coastguard Worker     unsigned RunningDepId = 1;
605*9880d681SAndroid Build Coastguard Worker     DenseMap<Value *, unsigned> DepSetId;
606*9880d681SAndroid Build Coastguard Worker 
607*9880d681SAndroid Build Coastguard Worker     for (auto A : AS) {
608*9880d681SAndroid Build Coastguard Worker       Value *Ptr = A.getValue();
609*9880d681SAndroid Build Coastguard Worker       bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
610*9880d681SAndroid Build Coastguard Worker       MemAccessInfo Access(Ptr, IsWrite);
611*9880d681SAndroid Build Coastguard Worker 
612*9880d681SAndroid Build Coastguard Worker       if (IsWrite)
613*9880d681SAndroid Build Coastguard Worker         ++NumWritePtrChecks;
614*9880d681SAndroid Build Coastguard Worker       else
615*9880d681SAndroid Build Coastguard Worker         ++NumReadPtrChecks;
616*9880d681SAndroid Build Coastguard Worker 
617*9880d681SAndroid Build Coastguard Worker       if (hasComputableBounds(PSE, StridesMap, Ptr, TheLoop) &&
618*9880d681SAndroid Build Coastguard Worker           // When we run after a failing dependency check we have to make sure
619*9880d681SAndroid Build Coastguard Worker           // we don't have wrapping pointers.
620*9880d681SAndroid Build Coastguard Worker           (!ShouldCheckWrap || isNoWrap(PSE, StridesMap, Ptr, TheLoop))) {
621*9880d681SAndroid Build Coastguard Worker         // The id of the dependence set.
622*9880d681SAndroid Build Coastguard Worker         unsigned DepId;
623*9880d681SAndroid Build Coastguard Worker 
624*9880d681SAndroid Build Coastguard Worker         if (IsDepCheckNeeded) {
625*9880d681SAndroid Build Coastguard Worker           Value *Leader = DepCands.getLeaderValue(Access).getPointer();
626*9880d681SAndroid Build Coastguard Worker           unsigned &LeaderId = DepSetId[Leader];
627*9880d681SAndroid Build Coastguard Worker           if (!LeaderId)
628*9880d681SAndroid Build Coastguard Worker             LeaderId = RunningDepId++;
629*9880d681SAndroid Build Coastguard Worker           DepId = LeaderId;
630*9880d681SAndroid Build Coastguard Worker         } else
631*9880d681SAndroid Build Coastguard Worker           // Each access has its own dependence set.
632*9880d681SAndroid Build Coastguard Worker           DepId = RunningDepId++;
633*9880d681SAndroid Build Coastguard Worker 
634*9880d681SAndroid Build Coastguard Worker         RtCheck.insert(TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap, PSE);
635*9880d681SAndroid Build Coastguard Worker 
636*9880d681SAndroid Build Coastguard Worker         DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
637*9880d681SAndroid Build Coastguard Worker       } else {
638*9880d681SAndroid Build Coastguard Worker         DEBUG(dbgs() << "LAA: Can't find bounds for ptr:" << *Ptr << '\n');
639*9880d681SAndroid Build Coastguard Worker         CanDoRT = false;
640*9880d681SAndroid Build Coastguard Worker       }
641*9880d681SAndroid Build Coastguard Worker     }
642*9880d681SAndroid Build Coastguard Worker 
643*9880d681SAndroid Build Coastguard Worker     // If we have at least two writes or one write and a read then we need to
644*9880d681SAndroid Build Coastguard Worker     // check them.  But there is no need to checks if there is only one
645*9880d681SAndroid Build Coastguard Worker     // dependence set for this alias set.
646*9880d681SAndroid Build Coastguard Worker     //
647*9880d681SAndroid Build Coastguard Worker     // Note that this function computes CanDoRT and NeedRTCheck independently.
648*9880d681SAndroid Build Coastguard Worker     // For example CanDoRT=false, NeedRTCheck=false means that we have a pointer
649*9880d681SAndroid Build Coastguard Worker     // for which we couldn't find the bounds but we don't actually need to emit
650*9880d681SAndroid Build Coastguard Worker     // any checks so it does not matter.
651*9880d681SAndroid Build Coastguard Worker     if (!(IsDepCheckNeeded && CanDoRT && RunningDepId == 2))
652*9880d681SAndroid Build Coastguard Worker       NeedRTCheck |= (NumWritePtrChecks >= 2 || (NumReadPtrChecks >= 1 &&
653*9880d681SAndroid Build Coastguard Worker                                                  NumWritePtrChecks >= 1));
654*9880d681SAndroid Build Coastguard Worker 
655*9880d681SAndroid Build Coastguard Worker     ++ASId;
656*9880d681SAndroid Build Coastguard Worker   }
657*9880d681SAndroid Build Coastguard Worker 
658*9880d681SAndroid Build Coastguard Worker   // If the pointers that we would use for the bounds comparison have different
659*9880d681SAndroid Build Coastguard Worker   // address spaces, assume the values aren't directly comparable, so we can't
660*9880d681SAndroid Build Coastguard Worker   // use them for the runtime check. We also have to assume they could
661*9880d681SAndroid Build Coastguard Worker   // overlap. In the future there should be metadata for whether address spaces
662*9880d681SAndroid Build Coastguard Worker   // are disjoint.
663*9880d681SAndroid Build Coastguard Worker   unsigned NumPointers = RtCheck.Pointers.size();
664*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0; i < NumPointers; ++i) {
665*9880d681SAndroid Build Coastguard Worker     for (unsigned j = i + 1; j < NumPointers; ++j) {
666*9880d681SAndroid Build Coastguard Worker       // Only need to check pointers between two different dependency sets.
667*9880d681SAndroid Build Coastguard Worker       if (RtCheck.Pointers[i].DependencySetId ==
668*9880d681SAndroid Build Coastguard Worker           RtCheck.Pointers[j].DependencySetId)
669*9880d681SAndroid Build Coastguard Worker        continue;
670*9880d681SAndroid Build Coastguard Worker       // Only need to check pointers in the same alias set.
671*9880d681SAndroid Build Coastguard Worker       if (RtCheck.Pointers[i].AliasSetId != RtCheck.Pointers[j].AliasSetId)
672*9880d681SAndroid Build Coastguard Worker         continue;
673*9880d681SAndroid Build Coastguard Worker 
674*9880d681SAndroid Build Coastguard Worker       Value *PtrI = RtCheck.Pointers[i].PointerValue;
675*9880d681SAndroid Build Coastguard Worker       Value *PtrJ = RtCheck.Pointers[j].PointerValue;
676*9880d681SAndroid Build Coastguard Worker 
677*9880d681SAndroid Build Coastguard Worker       unsigned ASi = PtrI->getType()->getPointerAddressSpace();
678*9880d681SAndroid Build Coastguard Worker       unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
679*9880d681SAndroid Build Coastguard Worker       if (ASi != ASj) {
680*9880d681SAndroid Build Coastguard Worker         DEBUG(dbgs() << "LAA: Runtime check would require comparison between"
681*9880d681SAndroid Build Coastguard Worker                        " different address spaces\n");
682*9880d681SAndroid Build Coastguard Worker         return false;
683*9880d681SAndroid Build Coastguard Worker       }
684*9880d681SAndroid Build Coastguard Worker     }
685*9880d681SAndroid Build Coastguard Worker   }
686*9880d681SAndroid Build Coastguard Worker 
687*9880d681SAndroid Build Coastguard Worker   if (NeedRTCheck && CanDoRT)
688*9880d681SAndroid Build Coastguard Worker     RtCheck.generateChecks(DepCands, IsDepCheckNeeded);
689*9880d681SAndroid Build Coastguard Worker 
690*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "LAA: We need to do " << RtCheck.getNumberOfChecks()
691*9880d681SAndroid Build Coastguard Worker                << " pointer comparisons.\n");
692*9880d681SAndroid Build Coastguard Worker 
693*9880d681SAndroid Build Coastguard Worker   RtCheck.Need = NeedRTCheck;
694*9880d681SAndroid Build Coastguard Worker 
695*9880d681SAndroid Build Coastguard Worker   bool CanDoRTIfNeeded = !NeedRTCheck || CanDoRT;
696*9880d681SAndroid Build Coastguard Worker   if (!CanDoRTIfNeeded)
697*9880d681SAndroid Build Coastguard Worker     RtCheck.reset();
698*9880d681SAndroid Build Coastguard Worker   return CanDoRTIfNeeded;
699*9880d681SAndroid Build Coastguard Worker }
700*9880d681SAndroid Build Coastguard Worker 
processMemAccesses()701*9880d681SAndroid Build Coastguard Worker void AccessAnalysis::processMemAccesses() {
702*9880d681SAndroid Build Coastguard Worker   // We process the set twice: first we process read-write pointers, last we
703*9880d681SAndroid Build Coastguard Worker   // process read-only pointers. This allows us to skip dependence tests for
704*9880d681SAndroid Build Coastguard Worker   // read-only pointers.
705*9880d681SAndroid Build Coastguard Worker 
706*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
707*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "  AST: "; AST.dump());
708*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "LAA:   Accesses(" << Accesses.size() << "):\n");
709*9880d681SAndroid Build Coastguard Worker   DEBUG({
710*9880d681SAndroid Build Coastguard Worker     for (auto A : Accesses)
711*9880d681SAndroid Build Coastguard Worker       dbgs() << "\t" << *A.getPointer() << " (" <<
712*9880d681SAndroid Build Coastguard Worker                 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
713*9880d681SAndroid Build Coastguard Worker                                          "read-only" : "read")) << ")\n";
714*9880d681SAndroid Build Coastguard Worker   });
715*9880d681SAndroid Build Coastguard Worker 
716*9880d681SAndroid Build Coastguard Worker   // The AliasSetTracker has nicely partitioned our pointers by metadata
717*9880d681SAndroid Build Coastguard Worker   // compatibility and potential for underlying-object overlap. As a result, we
718*9880d681SAndroid Build Coastguard Worker   // only need to check for potential pointer dependencies within each alias
719*9880d681SAndroid Build Coastguard Worker   // set.
720*9880d681SAndroid Build Coastguard Worker   for (auto &AS : AST) {
721*9880d681SAndroid Build Coastguard Worker     // Note that both the alias-set tracker and the alias sets themselves used
722*9880d681SAndroid Build Coastguard Worker     // linked lists internally and so the iteration order here is deterministic
723*9880d681SAndroid Build Coastguard Worker     // (matching the original instruction order within each set).
724*9880d681SAndroid Build Coastguard Worker 
725*9880d681SAndroid Build Coastguard Worker     bool SetHasWrite = false;
726*9880d681SAndroid Build Coastguard Worker 
727*9880d681SAndroid Build Coastguard Worker     // Map of pointers to last access encountered.
728*9880d681SAndroid Build Coastguard Worker     typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
729*9880d681SAndroid Build Coastguard Worker     UnderlyingObjToAccessMap ObjToLastAccess;
730*9880d681SAndroid Build Coastguard Worker 
731*9880d681SAndroid Build Coastguard Worker     // Set of access to check after all writes have been processed.
732*9880d681SAndroid Build Coastguard Worker     PtrAccessSet DeferredAccesses;
733*9880d681SAndroid Build Coastguard Worker 
734*9880d681SAndroid Build Coastguard Worker     // Iterate over each alias set twice, once to process read/write pointers,
735*9880d681SAndroid Build Coastguard Worker     // and then to process read-only pointers.
736*9880d681SAndroid Build Coastguard Worker     for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
737*9880d681SAndroid Build Coastguard Worker       bool UseDeferred = SetIteration > 0;
738*9880d681SAndroid Build Coastguard Worker       PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
739*9880d681SAndroid Build Coastguard Worker 
740*9880d681SAndroid Build Coastguard Worker       for (auto AV : AS) {
741*9880d681SAndroid Build Coastguard Worker         Value *Ptr = AV.getValue();
742*9880d681SAndroid Build Coastguard Worker 
743*9880d681SAndroid Build Coastguard Worker         // For a single memory access in AliasSetTracker, Accesses may contain
744*9880d681SAndroid Build Coastguard Worker         // both read and write, and they both need to be handled for CheckDeps.
745*9880d681SAndroid Build Coastguard Worker         for (auto AC : S) {
746*9880d681SAndroid Build Coastguard Worker           if (AC.getPointer() != Ptr)
747*9880d681SAndroid Build Coastguard Worker             continue;
748*9880d681SAndroid Build Coastguard Worker 
749*9880d681SAndroid Build Coastguard Worker           bool IsWrite = AC.getInt();
750*9880d681SAndroid Build Coastguard Worker 
751*9880d681SAndroid Build Coastguard Worker           // If we're using the deferred access set, then it contains only
752*9880d681SAndroid Build Coastguard Worker           // reads.
753*9880d681SAndroid Build Coastguard Worker           bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
754*9880d681SAndroid Build Coastguard Worker           if (UseDeferred && !IsReadOnlyPtr)
755*9880d681SAndroid Build Coastguard Worker             continue;
756*9880d681SAndroid Build Coastguard Worker           // Otherwise, the pointer must be in the PtrAccessSet, either as a
757*9880d681SAndroid Build Coastguard Worker           // read or a write.
758*9880d681SAndroid Build Coastguard Worker           assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
759*9880d681SAndroid Build Coastguard Worker                   S.count(MemAccessInfo(Ptr, false))) &&
760*9880d681SAndroid Build Coastguard Worker                  "Alias-set pointer not in the access set?");
761*9880d681SAndroid Build Coastguard Worker 
762*9880d681SAndroid Build Coastguard Worker           MemAccessInfo Access(Ptr, IsWrite);
763*9880d681SAndroid Build Coastguard Worker           DepCands.insert(Access);
764*9880d681SAndroid Build Coastguard Worker 
765*9880d681SAndroid Build Coastguard Worker           // Memorize read-only pointers for later processing and skip them in
766*9880d681SAndroid Build Coastguard Worker           // the first round (they need to be checked after we have seen all
767*9880d681SAndroid Build Coastguard Worker           // write pointers). Note: we also mark pointer that are not
768*9880d681SAndroid Build Coastguard Worker           // consecutive as "read-only" pointers (so that we check
769*9880d681SAndroid Build Coastguard Worker           // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
770*9880d681SAndroid Build Coastguard Worker           if (!UseDeferred && IsReadOnlyPtr) {
771*9880d681SAndroid Build Coastguard Worker             DeferredAccesses.insert(Access);
772*9880d681SAndroid Build Coastguard Worker             continue;
773*9880d681SAndroid Build Coastguard Worker           }
774*9880d681SAndroid Build Coastguard Worker 
775*9880d681SAndroid Build Coastguard Worker           // If this is a write - check other reads and writes for conflicts. If
776*9880d681SAndroid Build Coastguard Worker           // this is a read only check other writes for conflicts (but only if
777*9880d681SAndroid Build Coastguard Worker           // there is no other write to the ptr - this is an optimization to
778*9880d681SAndroid Build Coastguard Worker           // catch "a[i] = a[i] + " without having to do a dependence check).
779*9880d681SAndroid Build Coastguard Worker           if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
780*9880d681SAndroid Build Coastguard Worker             CheckDeps.insert(Access);
781*9880d681SAndroid Build Coastguard Worker             IsRTCheckAnalysisNeeded = true;
782*9880d681SAndroid Build Coastguard Worker           }
783*9880d681SAndroid Build Coastguard Worker 
784*9880d681SAndroid Build Coastguard Worker           if (IsWrite)
785*9880d681SAndroid Build Coastguard Worker             SetHasWrite = true;
786*9880d681SAndroid Build Coastguard Worker 
787*9880d681SAndroid Build Coastguard Worker           // Create sets of pointers connected by a shared alias set and
788*9880d681SAndroid Build Coastguard Worker           // underlying object.
789*9880d681SAndroid Build Coastguard Worker           typedef SmallVector<Value *, 16> ValueVector;
790*9880d681SAndroid Build Coastguard Worker           ValueVector TempObjects;
791*9880d681SAndroid Build Coastguard Worker 
792*9880d681SAndroid Build Coastguard Worker           GetUnderlyingObjects(Ptr, TempObjects, DL, LI);
793*9880d681SAndroid Build Coastguard Worker           DEBUG(dbgs() << "Underlying objects for pointer " << *Ptr << "\n");
794*9880d681SAndroid Build Coastguard Worker           for (Value *UnderlyingObj : TempObjects) {
795*9880d681SAndroid Build Coastguard Worker             // nullptr never alias, don't join sets for pointer that have "null"
796*9880d681SAndroid Build Coastguard Worker             // in their UnderlyingObjects list.
797*9880d681SAndroid Build Coastguard Worker             if (isa<ConstantPointerNull>(UnderlyingObj))
798*9880d681SAndroid Build Coastguard Worker               continue;
799*9880d681SAndroid Build Coastguard Worker 
800*9880d681SAndroid Build Coastguard Worker             UnderlyingObjToAccessMap::iterator Prev =
801*9880d681SAndroid Build Coastguard Worker                 ObjToLastAccess.find(UnderlyingObj);
802*9880d681SAndroid Build Coastguard Worker             if (Prev != ObjToLastAccess.end())
803*9880d681SAndroid Build Coastguard Worker               DepCands.unionSets(Access, Prev->second);
804*9880d681SAndroid Build Coastguard Worker 
805*9880d681SAndroid Build Coastguard Worker             ObjToLastAccess[UnderlyingObj] = Access;
806*9880d681SAndroid Build Coastguard Worker             DEBUG(dbgs() << "  " << *UnderlyingObj << "\n");
807*9880d681SAndroid Build Coastguard Worker           }
808*9880d681SAndroid Build Coastguard Worker         }
809*9880d681SAndroid Build Coastguard Worker       }
810*9880d681SAndroid Build Coastguard Worker     }
811*9880d681SAndroid Build Coastguard Worker   }
812*9880d681SAndroid Build Coastguard Worker }
813*9880d681SAndroid Build Coastguard Worker 
isInBoundsGep(Value * Ptr)814*9880d681SAndroid Build Coastguard Worker static bool isInBoundsGep(Value *Ptr) {
815*9880d681SAndroid Build Coastguard Worker   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
816*9880d681SAndroid Build Coastguard Worker     return GEP->isInBounds();
817*9880d681SAndroid Build Coastguard Worker   return false;
818*9880d681SAndroid Build Coastguard Worker }
819*9880d681SAndroid Build Coastguard Worker 
820*9880d681SAndroid Build Coastguard Worker /// \brief Return true if an AddRec pointer \p Ptr is unsigned non-wrapping,
821*9880d681SAndroid Build Coastguard Worker /// i.e. monotonically increasing/decreasing.
isNoWrapAddRec(Value * Ptr,const SCEVAddRecExpr * AR,PredicatedScalarEvolution & PSE,const Loop * L)822*9880d681SAndroid Build Coastguard Worker static bool isNoWrapAddRec(Value *Ptr, const SCEVAddRecExpr *AR,
823*9880d681SAndroid Build Coastguard Worker                            PredicatedScalarEvolution &PSE, const Loop *L) {
824*9880d681SAndroid Build Coastguard Worker   // FIXME: This should probably only return true for NUW.
825*9880d681SAndroid Build Coastguard Worker   if (AR->getNoWrapFlags(SCEV::NoWrapMask))
826*9880d681SAndroid Build Coastguard Worker     return true;
827*9880d681SAndroid Build Coastguard Worker 
828*9880d681SAndroid Build Coastguard Worker   // Scalar evolution does not propagate the non-wrapping flags to values that
829*9880d681SAndroid Build Coastguard Worker   // are derived from a non-wrapping induction variable because non-wrapping
830*9880d681SAndroid Build Coastguard Worker   // could be flow-sensitive.
831*9880d681SAndroid Build Coastguard Worker   //
832*9880d681SAndroid Build Coastguard Worker   // Look through the potentially overflowing instruction to try to prove
833*9880d681SAndroid Build Coastguard Worker   // non-wrapping for the *specific* value of Ptr.
834*9880d681SAndroid Build Coastguard Worker 
835*9880d681SAndroid Build Coastguard Worker   // The arithmetic implied by an inbounds GEP can't overflow.
836*9880d681SAndroid Build Coastguard Worker   auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
837*9880d681SAndroid Build Coastguard Worker   if (!GEP || !GEP->isInBounds())
838*9880d681SAndroid Build Coastguard Worker     return false;
839*9880d681SAndroid Build Coastguard Worker 
840*9880d681SAndroid Build Coastguard Worker   // Make sure there is only one non-const index and analyze that.
841*9880d681SAndroid Build Coastguard Worker   Value *NonConstIndex = nullptr;
842*9880d681SAndroid Build Coastguard Worker   for (Value *Index : make_range(GEP->idx_begin(), GEP->idx_end()))
843*9880d681SAndroid Build Coastguard Worker     if (!isa<ConstantInt>(Index)) {
844*9880d681SAndroid Build Coastguard Worker       if (NonConstIndex)
845*9880d681SAndroid Build Coastguard Worker         return false;
846*9880d681SAndroid Build Coastguard Worker       NonConstIndex = Index;
847*9880d681SAndroid Build Coastguard Worker     }
848*9880d681SAndroid Build Coastguard Worker   if (!NonConstIndex)
849*9880d681SAndroid Build Coastguard Worker     // The recurrence is on the pointer, ignore for now.
850*9880d681SAndroid Build Coastguard Worker     return false;
851*9880d681SAndroid Build Coastguard Worker 
852*9880d681SAndroid Build Coastguard Worker   // The index in GEP is signed.  It is non-wrapping if it's derived from a NSW
853*9880d681SAndroid Build Coastguard Worker   // AddRec using a NSW operation.
854*9880d681SAndroid Build Coastguard Worker   if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(NonConstIndex))
855*9880d681SAndroid Build Coastguard Worker     if (OBO->hasNoSignedWrap() &&
856*9880d681SAndroid Build Coastguard Worker         // Assume constant for other the operand so that the AddRec can be
857*9880d681SAndroid Build Coastguard Worker         // easily found.
858*9880d681SAndroid Build Coastguard Worker         isa<ConstantInt>(OBO->getOperand(1))) {
859*9880d681SAndroid Build Coastguard Worker       auto *OpScev = PSE.getSCEV(OBO->getOperand(0));
860*9880d681SAndroid Build Coastguard Worker 
861*9880d681SAndroid Build Coastguard Worker       if (auto *OpAR = dyn_cast<SCEVAddRecExpr>(OpScev))
862*9880d681SAndroid Build Coastguard Worker         return OpAR->getLoop() == L && OpAR->getNoWrapFlags(SCEV::FlagNSW);
863*9880d681SAndroid Build Coastguard Worker     }
864*9880d681SAndroid Build Coastguard Worker 
865*9880d681SAndroid Build Coastguard Worker   return false;
866*9880d681SAndroid Build Coastguard Worker }
867*9880d681SAndroid Build Coastguard Worker 
868*9880d681SAndroid Build Coastguard Worker /// \brief Check whether the access through \p Ptr has a constant stride.
getPtrStride(PredicatedScalarEvolution & PSE,Value * Ptr,const Loop * Lp,const ValueToValueMap & StridesMap,bool Assume)869*9880d681SAndroid Build Coastguard Worker int64_t llvm::getPtrStride(PredicatedScalarEvolution &PSE, Value *Ptr,
870*9880d681SAndroid Build Coastguard Worker                            const Loop *Lp, const ValueToValueMap &StridesMap,
871*9880d681SAndroid Build Coastguard Worker                            bool Assume) {
872*9880d681SAndroid Build Coastguard Worker   Type *Ty = Ptr->getType();
873*9880d681SAndroid Build Coastguard Worker   assert(Ty->isPointerTy() && "Unexpected non-ptr");
874*9880d681SAndroid Build Coastguard Worker 
875*9880d681SAndroid Build Coastguard Worker   // Make sure that the pointer does not point to aggregate types.
876*9880d681SAndroid Build Coastguard Worker   auto *PtrTy = cast<PointerType>(Ty);
877*9880d681SAndroid Build Coastguard Worker   if (PtrTy->getElementType()->isAggregateType()) {
878*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type" << *Ptr
879*9880d681SAndroid Build Coastguard Worker                  << "\n");
880*9880d681SAndroid Build Coastguard Worker     return 0;
881*9880d681SAndroid Build Coastguard Worker   }
882*9880d681SAndroid Build Coastguard Worker 
883*9880d681SAndroid Build Coastguard Worker   const SCEV *PtrScev = replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr);
884*9880d681SAndroid Build Coastguard Worker 
885*9880d681SAndroid Build Coastguard Worker   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
886*9880d681SAndroid Build Coastguard Worker   if (Assume && !AR)
887*9880d681SAndroid Build Coastguard Worker     AR = PSE.getAsAddRec(Ptr);
888*9880d681SAndroid Build Coastguard Worker 
889*9880d681SAndroid Build Coastguard Worker   if (!AR) {
890*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer " << *Ptr
891*9880d681SAndroid Build Coastguard Worker                  << " SCEV: " << *PtrScev << "\n");
892*9880d681SAndroid Build Coastguard Worker     return 0;
893*9880d681SAndroid Build Coastguard Worker   }
894*9880d681SAndroid Build Coastguard Worker 
895*9880d681SAndroid Build Coastguard Worker   // The accesss function must stride over the innermost loop.
896*9880d681SAndroid Build Coastguard Worker   if (Lp != AR->getLoop()) {
897*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " <<
898*9880d681SAndroid Build Coastguard Worker           *Ptr << " SCEV: " << *AR << "\n");
899*9880d681SAndroid Build Coastguard Worker     return 0;
900*9880d681SAndroid Build Coastguard Worker   }
901*9880d681SAndroid Build Coastguard Worker 
902*9880d681SAndroid Build Coastguard Worker   // The address calculation must not wrap. Otherwise, a dependence could be
903*9880d681SAndroid Build Coastguard Worker   // inverted.
904*9880d681SAndroid Build Coastguard Worker   // An inbounds getelementptr that is a AddRec with a unit stride
905*9880d681SAndroid Build Coastguard Worker   // cannot wrap per definition. The unit stride requirement is checked later.
906*9880d681SAndroid Build Coastguard Worker   // An getelementptr without an inbounds attribute and unit stride would have
907*9880d681SAndroid Build Coastguard Worker   // to access the pointer value "0" which is undefined behavior in address
908*9880d681SAndroid Build Coastguard Worker   // space 0, therefore we can also vectorize this case.
909*9880d681SAndroid Build Coastguard Worker   bool IsInBoundsGEP = isInBoundsGep(Ptr);
910*9880d681SAndroid Build Coastguard Worker   bool IsNoWrapAddRec =
911*9880d681SAndroid Build Coastguard Worker       PSE.hasNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW) ||
912*9880d681SAndroid Build Coastguard Worker       isNoWrapAddRec(Ptr, AR, PSE, Lp);
913*9880d681SAndroid Build Coastguard Worker   bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
914*9880d681SAndroid Build Coastguard Worker   if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
915*9880d681SAndroid Build Coastguard Worker     if (Assume) {
916*9880d681SAndroid Build Coastguard Worker       PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
917*9880d681SAndroid Build Coastguard Worker       IsNoWrapAddRec = true;
918*9880d681SAndroid Build Coastguard Worker       DEBUG(dbgs() << "LAA: Pointer may wrap in the address space:\n"
919*9880d681SAndroid Build Coastguard Worker                    << "LAA:   Pointer: " << *Ptr << "\n"
920*9880d681SAndroid Build Coastguard Worker                    << "LAA:   SCEV: " << *AR << "\n"
921*9880d681SAndroid Build Coastguard Worker                    << "LAA:   Added an overflow assumption\n");
922*9880d681SAndroid Build Coastguard Worker     } else {
923*9880d681SAndroid Build Coastguard Worker       DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
924*9880d681SAndroid Build Coastguard Worker                    << *Ptr << " SCEV: " << *AR << "\n");
925*9880d681SAndroid Build Coastguard Worker       return 0;
926*9880d681SAndroid Build Coastguard Worker     }
927*9880d681SAndroid Build Coastguard Worker   }
928*9880d681SAndroid Build Coastguard Worker 
929*9880d681SAndroid Build Coastguard Worker   // Check the step is constant.
930*9880d681SAndroid Build Coastguard Worker   const SCEV *Step = AR->getStepRecurrence(*PSE.getSE());
931*9880d681SAndroid Build Coastguard Worker 
932*9880d681SAndroid Build Coastguard Worker   // Calculate the pointer stride and check if it is constant.
933*9880d681SAndroid Build Coastguard Worker   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
934*9880d681SAndroid Build Coastguard Worker   if (!C) {
935*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr <<
936*9880d681SAndroid Build Coastguard Worker           " SCEV: " << *AR << "\n");
937*9880d681SAndroid Build Coastguard Worker     return 0;
938*9880d681SAndroid Build Coastguard Worker   }
939*9880d681SAndroid Build Coastguard Worker 
940*9880d681SAndroid Build Coastguard Worker   auto &DL = Lp->getHeader()->getModule()->getDataLayout();
941*9880d681SAndroid Build Coastguard Worker   int64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
942*9880d681SAndroid Build Coastguard Worker   const APInt &APStepVal = C->getAPInt();
943*9880d681SAndroid Build Coastguard Worker 
944*9880d681SAndroid Build Coastguard Worker   // Huge step value - give up.
945*9880d681SAndroid Build Coastguard Worker   if (APStepVal.getBitWidth() > 64)
946*9880d681SAndroid Build Coastguard Worker     return 0;
947*9880d681SAndroid Build Coastguard Worker 
948*9880d681SAndroid Build Coastguard Worker   int64_t StepVal = APStepVal.getSExtValue();
949*9880d681SAndroid Build Coastguard Worker 
950*9880d681SAndroid Build Coastguard Worker   // Strided access.
951*9880d681SAndroid Build Coastguard Worker   int64_t Stride = StepVal / Size;
952*9880d681SAndroid Build Coastguard Worker   int64_t Rem = StepVal % Size;
953*9880d681SAndroid Build Coastguard Worker   if (Rem)
954*9880d681SAndroid Build Coastguard Worker     return 0;
955*9880d681SAndroid Build Coastguard Worker 
956*9880d681SAndroid Build Coastguard Worker   // If the SCEV could wrap but we have an inbounds gep with a unit stride we
957*9880d681SAndroid Build Coastguard Worker   // know we can't "wrap around the address space". In case of address space
958*9880d681SAndroid Build Coastguard Worker   // zero we know that this won't happen without triggering undefined behavior.
959*9880d681SAndroid Build Coastguard Worker   if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
960*9880d681SAndroid Build Coastguard Worker       Stride != 1 && Stride != -1) {
961*9880d681SAndroid Build Coastguard Worker     if (Assume) {
962*9880d681SAndroid Build Coastguard Worker       // We can avoid this case by adding a run-time check.
963*9880d681SAndroid Build Coastguard Worker       DEBUG(dbgs() << "LAA: Non unit strided pointer which is not either "
964*9880d681SAndroid Build Coastguard Worker                    << "inbouds or in address space 0 may wrap:\n"
965*9880d681SAndroid Build Coastguard Worker                    << "LAA:   Pointer: " << *Ptr << "\n"
966*9880d681SAndroid Build Coastguard Worker                    << "LAA:   SCEV: " << *AR << "\n"
967*9880d681SAndroid Build Coastguard Worker                    << "LAA:   Added an overflow assumption\n");
968*9880d681SAndroid Build Coastguard Worker       PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
969*9880d681SAndroid Build Coastguard Worker     } else
970*9880d681SAndroid Build Coastguard Worker       return 0;
971*9880d681SAndroid Build Coastguard Worker   }
972*9880d681SAndroid Build Coastguard Worker 
973*9880d681SAndroid Build Coastguard Worker   return Stride;
974*9880d681SAndroid Build Coastguard Worker }
975*9880d681SAndroid Build Coastguard Worker 
976*9880d681SAndroid Build Coastguard Worker /// Take the pointer operand from the Load/Store instruction.
977*9880d681SAndroid Build Coastguard Worker /// Returns NULL if this is not a valid Load/Store instruction.
getPointerOperand(Value * I)978*9880d681SAndroid Build Coastguard Worker static Value *getPointerOperand(Value *I) {
979*9880d681SAndroid Build Coastguard Worker   if (auto *LI = dyn_cast<LoadInst>(I))
980*9880d681SAndroid Build Coastguard Worker     return LI->getPointerOperand();
981*9880d681SAndroid Build Coastguard Worker   if (auto *SI = dyn_cast<StoreInst>(I))
982*9880d681SAndroid Build Coastguard Worker     return SI->getPointerOperand();
983*9880d681SAndroid Build Coastguard Worker   return nullptr;
984*9880d681SAndroid Build Coastguard Worker }
985*9880d681SAndroid Build Coastguard Worker 
986*9880d681SAndroid Build Coastguard Worker /// Take the address space operand from the Load/Store instruction.
987*9880d681SAndroid Build Coastguard Worker /// Returns -1 if this is not a valid Load/Store instruction.
getAddressSpaceOperand(Value * I)988*9880d681SAndroid Build Coastguard Worker static unsigned getAddressSpaceOperand(Value *I) {
989*9880d681SAndroid Build Coastguard Worker   if (LoadInst *L = dyn_cast<LoadInst>(I))
990*9880d681SAndroid Build Coastguard Worker     return L->getPointerAddressSpace();
991*9880d681SAndroid Build Coastguard Worker   if (StoreInst *S = dyn_cast<StoreInst>(I))
992*9880d681SAndroid Build Coastguard Worker     return S->getPointerAddressSpace();
993*9880d681SAndroid Build Coastguard Worker   return -1;
994*9880d681SAndroid Build Coastguard Worker }
995*9880d681SAndroid Build Coastguard Worker 
996*9880d681SAndroid Build Coastguard Worker /// Returns true if the memory operations \p A and \p B are consecutive.
isConsecutiveAccess(Value * A,Value * B,const DataLayout & DL,ScalarEvolution & SE,bool CheckType)997*9880d681SAndroid Build Coastguard Worker bool llvm::isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL,
998*9880d681SAndroid Build Coastguard Worker                                ScalarEvolution &SE, bool CheckType) {
999*9880d681SAndroid Build Coastguard Worker   Value *PtrA = getPointerOperand(A);
1000*9880d681SAndroid Build Coastguard Worker   Value *PtrB = getPointerOperand(B);
1001*9880d681SAndroid Build Coastguard Worker   unsigned ASA = getAddressSpaceOperand(A);
1002*9880d681SAndroid Build Coastguard Worker   unsigned ASB = getAddressSpaceOperand(B);
1003*9880d681SAndroid Build Coastguard Worker 
1004*9880d681SAndroid Build Coastguard Worker   // Check that the address spaces match and that the pointers are valid.
1005*9880d681SAndroid Build Coastguard Worker   if (!PtrA || !PtrB || (ASA != ASB))
1006*9880d681SAndroid Build Coastguard Worker     return false;
1007*9880d681SAndroid Build Coastguard Worker 
1008*9880d681SAndroid Build Coastguard Worker   // Make sure that A and B are different pointers.
1009*9880d681SAndroid Build Coastguard Worker   if (PtrA == PtrB)
1010*9880d681SAndroid Build Coastguard Worker     return false;
1011*9880d681SAndroid Build Coastguard Worker 
1012*9880d681SAndroid Build Coastguard Worker   // Make sure that A and B have the same type if required.
1013*9880d681SAndroid Build Coastguard Worker   if(CheckType && PtrA->getType() != PtrB->getType())
1014*9880d681SAndroid Build Coastguard Worker       return false;
1015*9880d681SAndroid Build Coastguard Worker 
1016*9880d681SAndroid Build Coastguard Worker   unsigned PtrBitWidth = DL.getPointerSizeInBits(ASA);
1017*9880d681SAndroid Build Coastguard Worker   Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1018*9880d681SAndroid Build Coastguard Worker   APInt Size(PtrBitWidth, DL.getTypeStoreSize(Ty));
1019*9880d681SAndroid Build Coastguard Worker 
1020*9880d681SAndroid Build Coastguard Worker   APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1021*9880d681SAndroid Build Coastguard Worker   PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetA);
1022*9880d681SAndroid Build Coastguard Worker   PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetB);
1023*9880d681SAndroid Build Coastguard Worker 
1024*9880d681SAndroid Build Coastguard Worker   //  OffsetDelta = OffsetB - OffsetA;
1025*9880d681SAndroid Build Coastguard Worker   const SCEV *OffsetSCEVA = SE.getConstant(OffsetA);
1026*9880d681SAndroid Build Coastguard Worker   const SCEV *OffsetSCEVB = SE.getConstant(OffsetB);
1027*9880d681SAndroid Build Coastguard Worker   const SCEV *OffsetDeltaSCEV = SE.getMinusSCEV(OffsetSCEVB, OffsetSCEVA);
1028*9880d681SAndroid Build Coastguard Worker   const SCEVConstant *OffsetDeltaC = dyn_cast<SCEVConstant>(OffsetDeltaSCEV);
1029*9880d681SAndroid Build Coastguard Worker   const APInt &OffsetDelta = OffsetDeltaC->getAPInt();
1030*9880d681SAndroid Build Coastguard Worker   // Check if they are based on the same pointer. That makes the offsets
1031*9880d681SAndroid Build Coastguard Worker   // sufficient.
1032*9880d681SAndroid Build Coastguard Worker   if (PtrA == PtrB)
1033*9880d681SAndroid Build Coastguard Worker     return OffsetDelta == Size;
1034*9880d681SAndroid Build Coastguard Worker 
1035*9880d681SAndroid Build Coastguard Worker   // Compute the necessary base pointer delta to have the necessary final delta
1036*9880d681SAndroid Build Coastguard Worker   // equal to the size.
1037*9880d681SAndroid Build Coastguard Worker   // BaseDelta = Size - OffsetDelta;
1038*9880d681SAndroid Build Coastguard Worker   const SCEV *SizeSCEV = SE.getConstant(Size);
1039*9880d681SAndroid Build Coastguard Worker   const SCEV *BaseDelta = SE.getMinusSCEV(SizeSCEV, OffsetDeltaSCEV);
1040*9880d681SAndroid Build Coastguard Worker 
1041*9880d681SAndroid Build Coastguard Worker   // Otherwise compute the distance with SCEV between the base pointers.
1042*9880d681SAndroid Build Coastguard Worker   const SCEV *PtrSCEVA = SE.getSCEV(PtrA);
1043*9880d681SAndroid Build Coastguard Worker   const SCEV *PtrSCEVB = SE.getSCEV(PtrB);
1044*9880d681SAndroid Build Coastguard Worker   const SCEV *X = SE.getAddExpr(PtrSCEVA, BaseDelta);
1045*9880d681SAndroid Build Coastguard Worker   return X == PtrSCEVB;
1046*9880d681SAndroid Build Coastguard Worker }
1047*9880d681SAndroid Build Coastguard Worker 
isSafeForVectorization(DepType Type)1048*9880d681SAndroid Build Coastguard Worker bool MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
1049*9880d681SAndroid Build Coastguard Worker   switch (Type) {
1050*9880d681SAndroid Build Coastguard Worker   case NoDep:
1051*9880d681SAndroid Build Coastguard Worker   case Forward:
1052*9880d681SAndroid Build Coastguard Worker   case BackwardVectorizable:
1053*9880d681SAndroid Build Coastguard Worker     return true;
1054*9880d681SAndroid Build Coastguard Worker 
1055*9880d681SAndroid Build Coastguard Worker   case Unknown:
1056*9880d681SAndroid Build Coastguard Worker   case ForwardButPreventsForwarding:
1057*9880d681SAndroid Build Coastguard Worker   case Backward:
1058*9880d681SAndroid Build Coastguard Worker   case BackwardVectorizableButPreventsForwarding:
1059*9880d681SAndroid Build Coastguard Worker     return false;
1060*9880d681SAndroid Build Coastguard Worker   }
1061*9880d681SAndroid Build Coastguard Worker   llvm_unreachable("unexpected DepType!");
1062*9880d681SAndroid Build Coastguard Worker }
1063*9880d681SAndroid Build Coastguard Worker 
isBackward() const1064*9880d681SAndroid Build Coastguard Worker bool MemoryDepChecker::Dependence::isBackward() const {
1065*9880d681SAndroid Build Coastguard Worker   switch (Type) {
1066*9880d681SAndroid Build Coastguard Worker   case NoDep:
1067*9880d681SAndroid Build Coastguard Worker   case Forward:
1068*9880d681SAndroid Build Coastguard Worker   case ForwardButPreventsForwarding:
1069*9880d681SAndroid Build Coastguard Worker   case Unknown:
1070*9880d681SAndroid Build Coastguard Worker     return false;
1071*9880d681SAndroid Build Coastguard Worker 
1072*9880d681SAndroid Build Coastguard Worker   case BackwardVectorizable:
1073*9880d681SAndroid Build Coastguard Worker   case Backward:
1074*9880d681SAndroid Build Coastguard Worker   case BackwardVectorizableButPreventsForwarding:
1075*9880d681SAndroid Build Coastguard Worker     return true;
1076*9880d681SAndroid Build Coastguard Worker   }
1077*9880d681SAndroid Build Coastguard Worker   llvm_unreachable("unexpected DepType!");
1078*9880d681SAndroid Build Coastguard Worker }
1079*9880d681SAndroid Build Coastguard Worker 
isPossiblyBackward() const1080*9880d681SAndroid Build Coastguard Worker bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
1081*9880d681SAndroid Build Coastguard Worker   return isBackward() || Type == Unknown;
1082*9880d681SAndroid Build Coastguard Worker }
1083*9880d681SAndroid Build Coastguard Worker 
isForward() const1084*9880d681SAndroid Build Coastguard Worker bool MemoryDepChecker::Dependence::isForward() const {
1085*9880d681SAndroid Build Coastguard Worker   switch (Type) {
1086*9880d681SAndroid Build Coastguard Worker   case Forward:
1087*9880d681SAndroid Build Coastguard Worker   case ForwardButPreventsForwarding:
1088*9880d681SAndroid Build Coastguard Worker     return true;
1089*9880d681SAndroid Build Coastguard Worker 
1090*9880d681SAndroid Build Coastguard Worker   case NoDep:
1091*9880d681SAndroid Build Coastguard Worker   case Unknown:
1092*9880d681SAndroid Build Coastguard Worker   case BackwardVectorizable:
1093*9880d681SAndroid Build Coastguard Worker   case Backward:
1094*9880d681SAndroid Build Coastguard Worker   case BackwardVectorizableButPreventsForwarding:
1095*9880d681SAndroid Build Coastguard Worker     return false;
1096*9880d681SAndroid Build Coastguard Worker   }
1097*9880d681SAndroid Build Coastguard Worker   llvm_unreachable("unexpected DepType!");
1098*9880d681SAndroid Build Coastguard Worker }
1099*9880d681SAndroid Build Coastguard Worker 
couldPreventStoreLoadForward(uint64_t Distance,uint64_t TypeByteSize)1100*9880d681SAndroid Build Coastguard Worker bool MemoryDepChecker::couldPreventStoreLoadForward(uint64_t Distance,
1101*9880d681SAndroid Build Coastguard Worker                                                     uint64_t TypeByteSize) {
1102*9880d681SAndroid Build Coastguard Worker   // If loads occur at a distance that is not a multiple of a feasible vector
1103*9880d681SAndroid Build Coastguard Worker   // factor store-load forwarding does not take place.
1104*9880d681SAndroid Build Coastguard Worker   // Positive dependences might cause troubles because vectorizing them might
1105*9880d681SAndroid Build Coastguard Worker   // prevent store-load forwarding making vectorized code run a lot slower.
1106*9880d681SAndroid Build Coastguard Worker   //   a[i] = a[i-3] ^ a[i-8];
1107*9880d681SAndroid Build Coastguard Worker   //   The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
1108*9880d681SAndroid Build Coastguard Worker   //   hence on your typical architecture store-load forwarding does not take
1109*9880d681SAndroid Build Coastguard Worker   //   place. Vectorizing in such cases does not make sense.
1110*9880d681SAndroid Build Coastguard Worker   // Store-load forwarding distance.
1111*9880d681SAndroid Build Coastguard Worker 
1112*9880d681SAndroid Build Coastguard Worker   // After this many iterations store-to-load forwarding conflicts should not
1113*9880d681SAndroid Build Coastguard Worker   // cause any slowdowns.
1114*9880d681SAndroid Build Coastguard Worker   const uint64_t NumItersForStoreLoadThroughMemory = 8 * TypeByteSize;
1115*9880d681SAndroid Build Coastguard Worker   // Maximum vector factor.
1116*9880d681SAndroid Build Coastguard Worker   uint64_t MaxVFWithoutSLForwardIssues = std::min(
1117*9880d681SAndroid Build Coastguard Worker       VectorizerParams::MaxVectorWidth * TypeByteSize, MaxSafeDepDistBytes);
1118*9880d681SAndroid Build Coastguard Worker 
1119*9880d681SAndroid Build Coastguard Worker   // Compute the smallest VF at which the store and load would be misaligned.
1120*9880d681SAndroid Build Coastguard Worker   for (uint64_t VF = 2 * TypeByteSize; VF <= MaxVFWithoutSLForwardIssues;
1121*9880d681SAndroid Build Coastguard Worker        VF *= 2) {
1122*9880d681SAndroid Build Coastguard Worker     // If the number of vector iteration between the store and the load are
1123*9880d681SAndroid Build Coastguard Worker     // small we could incur conflicts.
1124*9880d681SAndroid Build Coastguard Worker     if (Distance % VF && Distance / VF < NumItersForStoreLoadThroughMemory) {
1125*9880d681SAndroid Build Coastguard Worker       MaxVFWithoutSLForwardIssues = (VF >>= 1);
1126*9880d681SAndroid Build Coastguard Worker       break;
1127*9880d681SAndroid Build Coastguard Worker     }
1128*9880d681SAndroid Build Coastguard Worker   }
1129*9880d681SAndroid Build Coastguard Worker 
1130*9880d681SAndroid Build Coastguard Worker   if (MaxVFWithoutSLForwardIssues < 2 * TypeByteSize) {
1131*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "LAA: Distance " << Distance
1132*9880d681SAndroid Build Coastguard Worker                  << " that could cause a store-load forwarding conflict\n");
1133*9880d681SAndroid Build Coastguard Worker     return true;
1134*9880d681SAndroid Build Coastguard Worker   }
1135*9880d681SAndroid Build Coastguard Worker 
1136*9880d681SAndroid Build Coastguard Worker   if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
1137*9880d681SAndroid Build Coastguard Worker       MaxVFWithoutSLForwardIssues !=
1138*9880d681SAndroid Build Coastguard Worker           VectorizerParams::MaxVectorWidth * TypeByteSize)
1139*9880d681SAndroid Build Coastguard Worker     MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
1140*9880d681SAndroid Build Coastguard Worker   return false;
1141*9880d681SAndroid Build Coastguard Worker }
1142*9880d681SAndroid Build Coastguard Worker 
1143*9880d681SAndroid Build Coastguard Worker /// \brief Check the dependence for two accesses with the same stride \p Stride.
1144*9880d681SAndroid Build Coastguard Worker /// \p Distance is the positive distance and \p TypeByteSize is type size in
1145*9880d681SAndroid Build Coastguard Worker /// bytes.
1146*9880d681SAndroid Build Coastguard Worker ///
1147*9880d681SAndroid Build Coastguard Worker /// \returns true if they are independent.
areStridedAccessesIndependent(uint64_t Distance,uint64_t Stride,uint64_t TypeByteSize)1148*9880d681SAndroid Build Coastguard Worker static bool areStridedAccessesIndependent(uint64_t Distance, uint64_t Stride,
1149*9880d681SAndroid Build Coastguard Worker                                           uint64_t TypeByteSize) {
1150*9880d681SAndroid Build Coastguard Worker   assert(Stride > 1 && "The stride must be greater than 1");
1151*9880d681SAndroid Build Coastguard Worker   assert(TypeByteSize > 0 && "The type size in byte must be non-zero");
1152*9880d681SAndroid Build Coastguard Worker   assert(Distance > 0 && "The distance must be non-zero");
1153*9880d681SAndroid Build Coastguard Worker 
1154*9880d681SAndroid Build Coastguard Worker   // Skip if the distance is not multiple of type byte size.
1155*9880d681SAndroid Build Coastguard Worker   if (Distance % TypeByteSize)
1156*9880d681SAndroid Build Coastguard Worker     return false;
1157*9880d681SAndroid Build Coastguard Worker 
1158*9880d681SAndroid Build Coastguard Worker   uint64_t ScaledDist = Distance / TypeByteSize;
1159*9880d681SAndroid Build Coastguard Worker 
1160*9880d681SAndroid Build Coastguard Worker   // No dependence if the scaled distance is not multiple of the stride.
1161*9880d681SAndroid Build Coastguard Worker   // E.g.
1162*9880d681SAndroid Build Coastguard Worker   //      for (i = 0; i < 1024 ; i += 4)
1163*9880d681SAndroid Build Coastguard Worker   //        A[i+2] = A[i] + 1;
1164*9880d681SAndroid Build Coastguard Worker   //
1165*9880d681SAndroid Build Coastguard Worker   // Two accesses in memory (scaled distance is 2, stride is 4):
1166*9880d681SAndroid Build Coastguard Worker   //     | A[0] |      |      |      | A[4] |      |      |      |
1167*9880d681SAndroid Build Coastguard Worker   //     |      |      | A[2] |      |      |      | A[6] |      |
1168*9880d681SAndroid Build Coastguard Worker   //
1169*9880d681SAndroid Build Coastguard Worker   // E.g.
1170*9880d681SAndroid Build Coastguard Worker   //      for (i = 0; i < 1024 ; i += 3)
1171*9880d681SAndroid Build Coastguard Worker   //        A[i+4] = A[i] + 1;
1172*9880d681SAndroid Build Coastguard Worker   //
1173*9880d681SAndroid Build Coastguard Worker   // Two accesses in memory (scaled distance is 4, stride is 3):
1174*9880d681SAndroid Build Coastguard Worker   //     | A[0] |      |      | A[3] |      |      | A[6] |      |      |
1175*9880d681SAndroid Build Coastguard Worker   //     |      |      |      |      | A[4] |      |      | A[7] |      |
1176*9880d681SAndroid Build Coastguard Worker   return ScaledDist % Stride;
1177*9880d681SAndroid Build Coastguard Worker }
1178*9880d681SAndroid Build Coastguard Worker 
1179*9880d681SAndroid Build Coastguard Worker MemoryDepChecker::Dependence::DepType
isDependent(const MemAccessInfo & A,unsigned AIdx,const MemAccessInfo & B,unsigned BIdx,const ValueToValueMap & Strides)1180*9880d681SAndroid Build Coastguard Worker MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
1181*9880d681SAndroid Build Coastguard Worker                               const MemAccessInfo &B, unsigned BIdx,
1182*9880d681SAndroid Build Coastguard Worker                               const ValueToValueMap &Strides) {
1183*9880d681SAndroid Build Coastguard Worker   assert (AIdx < BIdx && "Must pass arguments in program order");
1184*9880d681SAndroid Build Coastguard Worker 
1185*9880d681SAndroid Build Coastguard Worker   Value *APtr = A.getPointer();
1186*9880d681SAndroid Build Coastguard Worker   Value *BPtr = B.getPointer();
1187*9880d681SAndroid Build Coastguard Worker   bool AIsWrite = A.getInt();
1188*9880d681SAndroid Build Coastguard Worker   bool BIsWrite = B.getInt();
1189*9880d681SAndroid Build Coastguard Worker 
1190*9880d681SAndroid Build Coastguard Worker   // Two reads are independent.
1191*9880d681SAndroid Build Coastguard Worker   if (!AIsWrite && !BIsWrite)
1192*9880d681SAndroid Build Coastguard Worker     return Dependence::NoDep;
1193*9880d681SAndroid Build Coastguard Worker 
1194*9880d681SAndroid Build Coastguard Worker   // We cannot check pointers in different address spaces.
1195*9880d681SAndroid Build Coastguard Worker   if (APtr->getType()->getPointerAddressSpace() !=
1196*9880d681SAndroid Build Coastguard Worker       BPtr->getType()->getPointerAddressSpace())
1197*9880d681SAndroid Build Coastguard Worker     return Dependence::Unknown;
1198*9880d681SAndroid Build Coastguard Worker 
1199*9880d681SAndroid Build Coastguard Worker   int64_t StrideAPtr = getPtrStride(PSE, APtr, InnermostLoop, Strides, true);
1200*9880d681SAndroid Build Coastguard Worker   int64_t StrideBPtr = getPtrStride(PSE, BPtr, InnermostLoop, Strides, true);
1201*9880d681SAndroid Build Coastguard Worker 
1202*9880d681SAndroid Build Coastguard Worker   const SCEV *Src = PSE.getSCEV(APtr);
1203*9880d681SAndroid Build Coastguard Worker   const SCEV *Sink = PSE.getSCEV(BPtr);
1204*9880d681SAndroid Build Coastguard Worker 
1205*9880d681SAndroid Build Coastguard Worker   // If the induction step is negative we have to invert source and sink of the
1206*9880d681SAndroid Build Coastguard Worker   // dependence.
1207*9880d681SAndroid Build Coastguard Worker   if (StrideAPtr < 0) {
1208*9880d681SAndroid Build Coastguard Worker     std::swap(APtr, BPtr);
1209*9880d681SAndroid Build Coastguard Worker     std::swap(Src, Sink);
1210*9880d681SAndroid Build Coastguard Worker     std::swap(AIsWrite, BIsWrite);
1211*9880d681SAndroid Build Coastguard Worker     std::swap(AIdx, BIdx);
1212*9880d681SAndroid Build Coastguard Worker     std::swap(StrideAPtr, StrideBPtr);
1213*9880d681SAndroid Build Coastguard Worker   }
1214*9880d681SAndroid Build Coastguard Worker 
1215*9880d681SAndroid Build Coastguard Worker   const SCEV *Dist = PSE.getSE()->getMinusSCEV(Sink, Src);
1216*9880d681SAndroid Build Coastguard Worker 
1217*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
1218*9880d681SAndroid Build Coastguard Worker                << "(Induction step: " << StrideAPtr << ")\n");
1219*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
1220*9880d681SAndroid Build Coastguard Worker                << *InstMap[BIdx] << ": " << *Dist << "\n");
1221*9880d681SAndroid Build Coastguard Worker 
1222*9880d681SAndroid Build Coastguard Worker   // Need accesses with constant stride. We don't want to vectorize
1223*9880d681SAndroid Build Coastguard Worker   // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
1224*9880d681SAndroid Build Coastguard Worker   // the address space.
1225*9880d681SAndroid Build Coastguard Worker   if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
1226*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "Pointer access with non-constant stride\n");
1227*9880d681SAndroid Build Coastguard Worker     return Dependence::Unknown;
1228*9880d681SAndroid Build Coastguard Worker   }
1229*9880d681SAndroid Build Coastguard Worker 
1230*9880d681SAndroid Build Coastguard Worker   const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
1231*9880d681SAndroid Build Coastguard Worker   if (!C) {
1232*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
1233*9880d681SAndroid Build Coastguard Worker     ShouldRetryWithRuntimeCheck = true;
1234*9880d681SAndroid Build Coastguard Worker     return Dependence::Unknown;
1235*9880d681SAndroid Build Coastguard Worker   }
1236*9880d681SAndroid Build Coastguard Worker 
1237*9880d681SAndroid Build Coastguard Worker   Type *ATy = APtr->getType()->getPointerElementType();
1238*9880d681SAndroid Build Coastguard Worker   Type *BTy = BPtr->getType()->getPointerElementType();
1239*9880d681SAndroid Build Coastguard Worker   auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
1240*9880d681SAndroid Build Coastguard Worker   uint64_t TypeByteSize = DL.getTypeAllocSize(ATy);
1241*9880d681SAndroid Build Coastguard Worker 
1242*9880d681SAndroid Build Coastguard Worker   const APInt &Val = C->getAPInt();
1243*9880d681SAndroid Build Coastguard Worker   int64_t Distance = Val.getSExtValue();
1244*9880d681SAndroid Build Coastguard Worker   uint64_t Stride = std::abs(StrideAPtr);
1245*9880d681SAndroid Build Coastguard Worker 
1246*9880d681SAndroid Build Coastguard Worker   // Attempt to prove strided accesses independent.
1247*9880d681SAndroid Build Coastguard Worker   if (std::abs(Distance) > 0 && Stride > 1 && ATy == BTy &&
1248*9880d681SAndroid Build Coastguard Worker       areStridedAccessesIndependent(std::abs(Distance), Stride, TypeByteSize)) {
1249*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "LAA: Strided accesses are independent\n");
1250*9880d681SAndroid Build Coastguard Worker     return Dependence::NoDep;
1251*9880d681SAndroid Build Coastguard Worker   }
1252*9880d681SAndroid Build Coastguard Worker 
1253*9880d681SAndroid Build Coastguard Worker   // Negative distances are not plausible dependencies.
1254*9880d681SAndroid Build Coastguard Worker   if (Val.isNegative()) {
1255*9880d681SAndroid Build Coastguard Worker     bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
1256*9880d681SAndroid Build Coastguard Worker     if (IsTrueDataDependence && EnableForwardingConflictDetection &&
1257*9880d681SAndroid Build Coastguard Worker         (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
1258*9880d681SAndroid Build Coastguard Worker          ATy != BTy)) {
1259*9880d681SAndroid Build Coastguard Worker       DEBUG(dbgs() << "LAA: Forward but may prevent st->ld forwarding\n");
1260*9880d681SAndroid Build Coastguard Worker       return Dependence::ForwardButPreventsForwarding;
1261*9880d681SAndroid Build Coastguard Worker     }
1262*9880d681SAndroid Build Coastguard Worker 
1263*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "LAA: Dependence is negative\n");
1264*9880d681SAndroid Build Coastguard Worker     return Dependence::Forward;
1265*9880d681SAndroid Build Coastguard Worker   }
1266*9880d681SAndroid Build Coastguard Worker 
1267*9880d681SAndroid Build Coastguard Worker   // Write to the same location with the same size.
1268*9880d681SAndroid Build Coastguard Worker   // Could be improved to assert type sizes are the same (i32 == float, etc).
1269*9880d681SAndroid Build Coastguard Worker   if (Val == 0) {
1270*9880d681SAndroid Build Coastguard Worker     if (ATy == BTy)
1271*9880d681SAndroid Build Coastguard Worker       return Dependence::Forward;
1272*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n");
1273*9880d681SAndroid Build Coastguard Worker     return Dependence::Unknown;
1274*9880d681SAndroid Build Coastguard Worker   }
1275*9880d681SAndroid Build Coastguard Worker 
1276*9880d681SAndroid Build Coastguard Worker   assert(Val.isStrictlyPositive() && "Expect a positive value");
1277*9880d681SAndroid Build Coastguard Worker 
1278*9880d681SAndroid Build Coastguard Worker   if (ATy != BTy) {
1279*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() <<
1280*9880d681SAndroid Build Coastguard Worker           "LAA: ReadWrite-Write positive dependency with different types\n");
1281*9880d681SAndroid Build Coastguard Worker     return Dependence::Unknown;
1282*9880d681SAndroid Build Coastguard Worker   }
1283*9880d681SAndroid Build Coastguard Worker 
1284*9880d681SAndroid Build Coastguard Worker   // Bail out early if passed-in parameters make vectorization not feasible.
1285*9880d681SAndroid Build Coastguard Worker   unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
1286*9880d681SAndroid Build Coastguard Worker                            VectorizerParams::VectorizationFactor : 1);
1287*9880d681SAndroid Build Coastguard Worker   unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
1288*9880d681SAndroid Build Coastguard Worker                            VectorizerParams::VectorizationInterleave : 1);
1289*9880d681SAndroid Build Coastguard Worker   // The minimum number of iterations for a vectorized/unrolled version.
1290*9880d681SAndroid Build Coastguard Worker   unsigned MinNumIter = std::max(ForcedFactor * ForcedUnroll, 2U);
1291*9880d681SAndroid Build Coastguard Worker 
1292*9880d681SAndroid Build Coastguard Worker   // It's not vectorizable if the distance is smaller than the minimum distance
1293*9880d681SAndroid Build Coastguard Worker   // needed for a vectroized/unrolled version. Vectorizing one iteration in
1294*9880d681SAndroid Build Coastguard Worker   // front needs TypeByteSize * Stride. Vectorizing the last iteration needs
1295*9880d681SAndroid Build Coastguard Worker   // TypeByteSize (No need to plus the last gap distance).
1296*9880d681SAndroid Build Coastguard Worker   //
1297*9880d681SAndroid Build Coastguard Worker   // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1298*9880d681SAndroid Build Coastguard Worker   //      foo(int *A) {
1299*9880d681SAndroid Build Coastguard Worker   //        int *B = (int *)((char *)A + 14);
1300*9880d681SAndroid Build Coastguard Worker   //        for (i = 0 ; i < 1024 ; i += 2)
1301*9880d681SAndroid Build Coastguard Worker   //          B[i] = A[i] + 1;
1302*9880d681SAndroid Build Coastguard Worker   //      }
1303*9880d681SAndroid Build Coastguard Worker   //
1304*9880d681SAndroid Build Coastguard Worker   // Two accesses in memory (stride is 2):
1305*9880d681SAndroid Build Coastguard Worker   //     | A[0] |      | A[2] |      | A[4] |      | A[6] |      |
1306*9880d681SAndroid Build Coastguard Worker   //                              | B[0] |      | B[2] |      | B[4] |
1307*9880d681SAndroid Build Coastguard Worker   //
1308*9880d681SAndroid Build Coastguard Worker   // Distance needs for vectorizing iterations except the last iteration:
1309*9880d681SAndroid Build Coastguard Worker   // 4 * 2 * (MinNumIter - 1). Distance needs for the last iteration: 4.
1310*9880d681SAndroid Build Coastguard Worker   // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4.
1311*9880d681SAndroid Build Coastguard Worker   //
1312*9880d681SAndroid Build Coastguard Worker   // If MinNumIter is 2, it is vectorizable as the minimum distance needed is
1313*9880d681SAndroid Build Coastguard Worker   // 12, which is less than distance.
1314*9880d681SAndroid Build Coastguard Worker   //
1315*9880d681SAndroid Build Coastguard Worker   // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4),
1316*9880d681SAndroid Build Coastguard Worker   // the minimum distance needed is 28, which is greater than distance. It is
1317*9880d681SAndroid Build Coastguard Worker   // not safe to do vectorization.
1318*9880d681SAndroid Build Coastguard Worker   uint64_t MinDistanceNeeded =
1319*9880d681SAndroid Build Coastguard Worker       TypeByteSize * Stride * (MinNumIter - 1) + TypeByteSize;
1320*9880d681SAndroid Build Coastguard Worker   if (MinDistanceNeeded > static_cast<uint64_t>(Distance)) {
1321*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "LAA: Failure because of positive distance " << Distance
1322*9880d681SAndroid Build Coastguard Worker                  << '\n');
1323*9880d681SAndroid Build Coastguard Worker     return Dependence::Backward;
1324*9880d681SAndroid Build Coastguard Worker   }
1325*9880d681SAndroid Build Coastguard Worker 
1326*9880d681SAndroid Build Coastguard Worker   // Unsafe if the minimum distance needed is greater than max safe distance.
1327*9880d681SAndroid Build Coastguard Worker   if (MinDistanceNeeded > MaxSafeDepDistBytes) {
1328*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "LAA: Failure because it needs at least "
1329*9880d681SAndroid Build Coastguard Worker                  << MinDistanceNeeded << " size in bytes");
1330*9880d681SAndroid Build Coastguard Worker     return Dependence::Backward;
1331*9880d681SAndroid Build Coastguard Worker   }
1332*9880d681SAndroid Build Coastguard Worker 
1333*9880d681SAndroid Build Coastguard Worker   // Positive distance bigger than max vectorization factor.
1334*9880d681SAndroid Build Coastguard Worker   // FIXME: Should use max factor instead of max distance in bytes, which could
1335*9880d681SAndroid Build Coastguard Worker   // not handle different types.
1336*9880d681SAndroid Build Coastguard Worker   // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1337*9880d681SAndroid Build Coastguard Worker   //      void foo (int *A, char *B) {
1338*9880d681SAndroid Build Coastguard Worker   //        for (unsigned i = 0; i < 1024; i++) {
1339*9880d681SAndroid Build Coastguard Worker   //          A[i+2] = A[i] + 1;
1340*9880d681SAndroid Build Coastguard Worker   //          B[i+2] = B[i] + 1;
1341*9880d681SAndroid Build Coastguard Worker   //        }
1342*9880d681SAndroid Build Coastguard Worker   //      }
1343*9880d681SAndroid Build Coastguard Worker   //
1344*9880d681SAndroid Build Coastguard Worker   // This case is currently unsafe according to the max safe distance. If we
1345*9880d681SAndroid Build Coastguard Worker   // analyze the two accesses on array B, the max safe dependence distance
1346*9880d681SAndroid Build Coastguard Worker   // is 2. Then we analyze the accesses on array A, the minimum distance needed
1347*9880d681SAndroid Build Coastguard Worker   // is 8, which is less than 2 and forbidden vectorization, But actually
1348*9880d681SAndroid Build Coastguard Worker   // both A and B could be vectorized by 2 iterations.
1349*9880d681SAndroid Build Coastguard Worker   MaxSafeDepDistBytes =
1350*9880d681SAndroid Build Coastguard Worker       std::min(static_cast<uint64_t>(Distance), MaxSafeDepDistBytes);
1351*9880d681SAndroid Build Coastguard Worker 
1352*9880d681SAndroid Build Coastguard Worker   bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
1353*9880d681SAndroid Build Coastguard Worker   if (IsTrueDataDependence && EnableForwardingConflictDetection &&
1354*9880d681SAndroid Build Coastguard Worker       couldPreventStoreLoadForward(Distance, TypeByteSize))
1355*9880d681SAndroid Build Coastguard Worker     return Dependence::BackwardVectorizableButPreventsForwarding;
1356*9880d681SAndroid Build Coastguard Worker 
1357*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue()
1358*9880d681SAndroid Build Coastguard Worker                << " with max VF = "
1359*9880d681SAndroid Build Coastguard Worker                << MaxSafeDepDistBytes / (TypeByteSize * Stride) << '\n');
1360*9880d681SAndroid Build Coastguard Worker 
1361*9880d681SAndroid Build Coastguard Worker   return Dependence::BackwardVectorizable;
1362*9880d681SAndroid Build Coastguard Worker }
1363*9880d681SAndroid Build Coastguard Worker 
areDepsSafe(DepCandidates & AccessSets,MemAccessInfoSet & CheckDeps,const ValueToValueMap & Strides)1364*9880d681SAndroid Build Coastguard Worker bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets,
1365*9880d681SAndroid Build Coastguard Worker                                    MemAccessInfoSet &CheckDeps,
1366*9880d681SAndroid Build Coastguard Worker                                    const ValueToValueMap &Strides) {
1367*9880d681SAndroid Build Coastguard Worker 
1368*9880d681SAndroid Build Coastguard Worker   MaxSafeDepDistBytes = -1;
1369*9880d681SAndroid Build Coastguard Worker   while (!CheckDeps.empty()) {
1370*9880d681SAndroid Build Coastguard Worker     MemAccessInfo CurAccess = *CheckDeps.begin();
1371*9880d681SAndroid Build Coastguard Worker 
1372*9880d681SAndroid Build Coastguard Worker     // Get the relevant memory access set.
1373*9880d681SAndroid Build Coastguard Worker     EquivalenceClasses<MemAccessInfo>::iterator I =
1374*9880d681SAndroid Build Coastguard Worker       AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
1375*9880d681SAndroid Build Coastguard Worker 
1376*9880d681SAndroid Build Coastguard Worker     // Check accesses within this set.
1377*9880d681SAndroid Build Coastguard Worker     EquivalenceClasses<MemAccessInfo>::member_iterator AI =
1378*9880d681SAndroid Build Coastguard Worker         AccessSets.member_begin(I);
1379*9880d681SAndroid Build Coastguard Worker     EquivalenceClasses<MemAccessInfo>::member_iterator AE =
1380*9880d681SAndroid Build Coastguard Worker         AccessSets.member_end();
1381*9880d681SAndroid Build Coastguard Worker 
1382*9880d681SAndroid Build Coastguard Worker     // Check every access pair.
1383*9880d681SAndroid Build Coastguard Worker     while (AI != AE) {
1384*9880d681SAndroid Build Coastguard Worker       CheckDeps.erase(*AI);
1385*9880d681SAndroid Build Coastguard Worker       EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
1386*9880d681SAndroid Build Coastguard Worker       while (OI != AE) {
1387*9880d681SAndroid Build Coastguard Worker         // Check every accessing instruction pair in program order.
1388*9880d681SAndroid Build Coastguard Worker         for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
1389*9880d681SAndroid Build Coastguard Worker              I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
1390*9880d681SAndroid Build Coastguard Worker           for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
1391*9880d681SAndroid Build Coastguard Worker                I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
1392*9880d681SAndroid Build Coastguard Worker             auto A = std::make_pair(&*AI, *I1);
1393*9880d681SAndroid Build Coastguard Worker             auto B = std::make_pair(&*OI, *I2);
1394*9880d681SAndroid Build Coastguard Worker 
1395*9880d681SAndroid Build Coastguard Worker             assert(*I1 != *I2);
1396*9880d681SAndroid Build Coastguard Worker             if (*I1 > *I2)
1397*9880d681SAndroid Build Coastguard Worker               std::swap(A, B);
1398*9880d681SAndroid Build Coastguard Worker 
1399*9880d681SAndroid Build Coastguard Worker             Dependence::DepType Type =
1400*9880d681SAndroid Build Coastguard Worker                 isDependent(*A.first, A.second, *B.first, B.second, Strides);
1401*9880d681SAndroid Build Coastguard Worker             SafeForVectorization &= Dependence::isSafeForVectorization(Type);
1402*9880d681SAndroid Build Coastguard Worker 
1403*9880d681SAndroid Build Coastguard Worker             // Gather dependences unless we accumulated MaxDependences
1404*9880d681SAndroid Build Coastguard Worker             // dependences.  In that case return as soon as we find the first
1405*9880d681SAndroid Build Coastguard Worker             // unsafe dependence.  This puts a limit on this quadratic
1406*9880d681SAndroid Build Coastguard Worker             // algorithm.
1407*9880d681SAndroid Build Coastguard Worker             if (RecordDependences) {
1408*9880d681SAndroid Build Coastguard Worker               if (Type != Dependence::NoDep)
1409*9880d681SAndroid Build Coastguard Worker                 Dependences.push_back(Dependence(A.second, B.second, Type));
1410*9880d681SAndroid Build Coastguard Worker 
1411*9880d681SAndroid Build Coastguard Worker               if (Dependences.size() >= MaxDependences) {
1412*9880d681SAndroid Build Coastguard Worker                 RecordDependences = false;
1413*9880d681SAndroid Build Coastguard Worker                 Dependences.clear();
1414*9880d681SAndroid Build Coastguard Worker                 DEBUG(dbgs() << "Too many dependences, stopped recording\n");
1415*9880d681SAndroid Build Coastguard Worker               }
1416*9880d681SAndroid Build Coastguard Worker             }
1417*9880d681SAndroid Build Coastguard Worker             if (!RecordDependences && !SafeForVectorization)
1418*9880d681SAndroid Build Coastguard Worker               return false;
1419*9880d681SAndroid Build Coastguard Worker           }
1420*9880d681SAndroid Build Coastguard Worker         ++OI;
1421*9880d681SAndroid Build Coastguard Worker       }
1422*9880d681SAndroid Build Coastguard Worker       AI++;
1423*9880d681SAndroid Build Coastguard Worker     }
1424*9880d681SAndroid Build Coastguard Worker   }
1425*9880d681SAndroid Build Coastguard Worker 
1426*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "Total Dependences: " << Dependences.size() << "\n");
1427*9880d681SAndroid Build Coastguard Worker   return SafeForVectorization;
1428*9880d681SAndroid Build Coastguard Worker }
1429*9880d681SAndroid Build Coastguard Worker 
1430*9880d681SAndroid Build Coastguard Worker SmallVector<Instruction *, 4>
getInstructionsForAccess(Value * Ptr,bool isWrite) const1431*9880d681SAndroid Build Coastguard Worker MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const {
1432*9880d681SAndroid Build Coastguard Worker   MemAccessInfo Access(Ptr, isWrite);
1433*9880d681SAndroid Build Coastguard Worker   auto &IndexVector = Accesses.find(Access)->second;
1434*9880d681SAndroid Build Coastguard Worker 
1435*9880d681SAndroid Build Coastguard Worker   SmallVector<Instruction *, 4> Insts;
1436*9880d681SAndroid Build Coastguard Worker   std::transform(IndexVector.begin(), IndexVector.end(),
1437*9880d681SAndroid Build Coastguard Worker                  std::back_inserter(Insts),
1438*9880d681SAndroid Build Coastguard Worker                  [&](unsigned Idx) { return this->InstMap[Idx]; });
1439*9880d681SAndroid Build Coastguard Worker   return Insts;
1440*9880d681SAndroid Build Coastguard Worker }
1441*9880d681SAndroid Build Coastguard Worker 
1442*9880d681SAndroid Build Coastguard Worker const char *MemoryDepChecker::Dependence::DepName[] = {
1443*9880d681SAndroid Build Coastguard Worker     "NoDep", "Unknown", "Forward", "ForwardButPreventsForwarding", "Backward",
1444*9880d681SAndroid Build Coastguard Worker     "BackwardVectorizable", "BackwardVectorizableButPreventsForwarding"};
1445*9880d681SAndroid Build Coastguard Worker 
print(raw_ostream & OS,unsigned Depth,const SmallVectorImpl<Instruction * > & Instrs) const1446*9880d681SAndroid Build Coastguard Worker void MemoryDepChecker::Dependence::print(
1447*9880d681SAndroid Build Coastguard Worker     raw_ostream &OS, unsigned Depth,
1448*9880d681SAndroid Build Coastguard Worker     const SmallVectorImpl<Instruction *> &Instrs) const {
1449*9880d681SAndroid Build Coastguard Worker   OS.indent(Depth) << DepName[Type] << ":\n";
1450*9880d681SAndroid Build Coastguard Worker   OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
1451*9880d681SAndroid Build Coastguard Worker   OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
1452*9880d681SAndroid Build Coastguard Worker }
1453*9880d681SAndroid Build Coastguard Worker 
canAnalyzeLoop()1454*9880d681SAndroid Build Coastguard Worker bool LoopAccessInfo::canAnalyzeLoop() {
1455*9880d681SAndroid Build Coastguard Worker   // We need to have a loop header.
1456*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "LAA: Found a loop in "
1457*9880d681SAndroid Build Coastguard Worker                << TheLoop->getHeader()->getParent()->getName() << ": "
1458*9880d681SAndroid Build Coastguard Worker                << TheLoop->getHeader()->getName() << '\n');
1459*9880d681SAndroid Build Coastguard Worker 
1460*9880d681SAndroid Build Coastguard Worker   // We can only analyze innermost loops.
1461*9880d681SAndroid Build Coastguard Worker   if (!TheLoop->empty()) {
1462*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
1463*9880d681SAndroid Build Coastguard Worker     emitAnalysis(LoopAccessReport() << "loop is not the innermost loop");
1464*9880d681SAndroid Build Coastguard Worker     return false;
1465*9880d681SAndroid Build Coastguard Worker   }
1466*9880d681SAndroid Build Coastguard Worker 
1467*9880d681SAndroid Build Coastguard Worker   // We must have a single backedge.
1468*9880d681SAndroid Build Coastguard Worker   if (TheLoop->getNumBackEdges() != 1) {
1469*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
1470*9880d681SAndroid Build Coastguard Worker     emitAnalysis(
1471*9880d681SAndroid Build Coastguard Worker         LoopAccessReport() <<
1472*9880d681SAndroid Build Coastguard Worker         "loop control flow is not understood by analyzer");
1473*9880d681SAndroid Build Coastguard Worker     return false;
1474*9880d681SAndroid Build Coastguard Worker   }
1475*9880d681SAndroid Build Coastguard Worker 
1476*9880d681SAndroid Build Coastguard Worker   // We must have a single exiting block.
1477*9880d681SAndroid Build Coastguard Worker   if (!TheLoop->getExitingBlock()) {
1478*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
1479*9880d681SAndroid Build Coastguard Worker     emitAnalysis(
1480*9880d681SAndroid Build Coastguard Worker         LoopAccessReport() <<
1481*9880d681SAndroid Build Coastguard Worker         "loop control flow is not understood by analyzer");
1482*9880d681SAndroid Build Coastguard Worker     return false;
1483*9880d681SAndroid Build Coastguard Worker   }
1484*9880d681SAndroid Build Coastguard Worker 
1485*9880d681SAndroid Build Coastguard Worker   // We only handle bottom-tested loops, i.e. loop in which the condition is
1486*9880d681SAndroid Build Coastguard Worker   // checked at the end of each iteration. With that we can assume that all
1487*9880d681SAndroid Build Coastguard Worker   // instructions in the loop are executed the same number of times.
1488*9880d681SAndroid Build Coastguard Worker   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
1489*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
1490*9880d681SAndroid Build Coastguard Worker     emitAnalysis(
1491*9880d681SAndroid Build Coastguard Worker         LoopAccessReport() <<
1492*9880d681SAndroid Build Coastguard Worker         "loop control flow is not understood by analyzer");
1493*9880d681SAndroid Build Coastguard Worker     return false;
1494*9880d681SAndroid Build Coastguard Worker   }
1495*9880d681SAndroid Build Coastguard Worker 
1496*9880d681SAndroid Build Coastguard Worker   // ScalarEvolution needs to be able to find the exit count.
1497*9880d681SAndroid Build Coastguard Worker   const SCEV *ExitCount = PSE->getBackedgeTakenCount();
1498*9880d681SAndroid Build Coastguard Worker   if (ExitCount == PSE->getSE()->getCouldNotCompute()) {
1499*9880d681SAndroid Build Coastguard Worker     emitAnalysis(LoopAccessReport()
1500*9880d681SAndroid Build Coastguard Worker                  << "could not determine number of loop iterations");
1501*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
1502*9880d681SAndroid Build Coastguard Worker     return false;
1503*9880d681SAndroid Build Coastguard Worker   }
1504*9880d681SAndroid Build Coastguard Worker 
1505*9880d681SAndroid Build Coastguard Worker   return true;
1506*9880d681SAndroid Build Coastguard Worker }
1507*9880d681SAndroid Build Coastguard Worker 
analyzeLoop(AliasAnalysis * AA,LoopInfo * LI,const TargetLibraryInfo * TLI,DominatorTree * DT)1508*9880d681SAndroid Build Coastguard Worker void LoopAccessInfo::analyzeLoop(AliasAnalysis *AA, LoopInfo *LI,
1509*9880d681SAndroid Build Coastguard Worker                                  const TargetLibraryInfo *TLI,
1510*9880d681SAndroid Build Coastguard Worker                                  DominatorTree *DT) {
1511*9880d681SAndroid Build Coastguard Worker   typedef SmallPtrSet<Value*, 16> ValueSet;
1512*9880d681SAndroid Build Coastguard Worker 
1513*9880d681SAndroid Build Coastguard Worker   // Holds the Load and Store instructions.
1514*9880d681SAndroid Build Coastguard Worker   SmallVector<LoadInst *, 16> Loads;
1515*9880d681SAndroid Build Coastguard Worker   SmallVector<StoreInst *, 16> Stores;
1516*9880d681SAndroid Build Coastguard Worker 
1517*9880d681SAndroid Build Coastguard Worker   // Holds all the different accesses in the loop.
1518*9880d681SAndroid Build Coastguard Worker   unsigned NumReads = 0;
1519*9880d681SAndroid Build Coastguard Worker   unsigned NumReadWrites = 0;
1520*9880d681SAndroid Build Coastguard Worker 
1521*9880d681SAndroid Build Coastguard Worker   PtrRtChecking->Pointers.clear();
1522*9880d681SAndroid Build Coastguard Worker   PtrRtChecking->Need = false;
1523*9880d681SAndroid Build Coastguard Worker 
1524*9880d681SAndroid Build Coastguard Worker   const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
1525*9880d681SAndroid Build Coastguard Worker 
1526*9880d681SAndroid Build Coastguard Worker   // For each block.
1527*9880d681SAndroid Build Coastguard Worker   for (BasicBlock *BB : TheLoop->blocks()) {
1528*9880d681SAndroid Build Coastguard Worker     // Scan the BB and collect legal loads and stores.
1529*9880d681SAndroid Build Coastguard Worker     for (Instruction &I : *BB) {
1530*9880d681SAndroid Build Coastguard Worker       // If this is a load, save it. If this instruction can read from memory
1531*9880d681SAndroid Build Coastguard Worker       // but is not a load, then we quit. Notice that we don't handle function
1532*9880d681SAndroid Build Coastguard Worker       // calls that read or write.
1533*9880d681SAndroid Build Coastguard Worker       if (I.mayReadFromMemory()) {
1534*9880d681SAndroid Build Coastguard Worker         // Many math library functions read the rounding mode. We will only
1535*9880d681SAndroid Build Coastguard Worker         // vectorize a loop if it contains known function calls that don't set
1536*9880d681SAndroid Build Coastguard Worker         // the flag. Therefore, it is safe to ignore this read from memory.
1537*9880d681SAndroid Build Coastguard Worker         auto *Call = dyn_cast<CallInst>(&I);
1538*9880d681SAndroid Build Coastguard Worker         if (Call && getVectorIntrinsicIDForCall(Call, TLI))
1539*9880d681SAndroid Build Coastguard Worker           continue;
1540*9880d681SAndroid Build Coastguard Worker 
1541*9880d681SAndroid Build Coastguard Worker         // If the function has an explicit vectorized counterpart, we can safely
1542*9880d681SAndroid Build Coastguard Worker         // assume that it can be vectorized.
1543*9880d681SAndroid Build Coastguard Worker         if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
1544*9880d681SAndroid Build Coastguard Worker             TLI->isFunctionVectorizable(Call->getCalledFunction()->getName()))
1545*9880d681SAndroid Build Coastguard Worker           continue;
1546*9880d681SAndroid Build Coastguard Worker 
1547*9880d681SAndroid Build Coastguard Worker         auto *Ld = dyn_cast<LoadInst>(&I);
1548*9880d681SAndroid Build Coastguard Worker         if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
1549*9880d681SAndroid Build Coastguard Worker           emitAnalysis(LoopAccessReport(Ld)
1550*9880d681SAndroid Build Coastguard Worker                        << "read with atomic ordering or volatile read");
1551*9880d681SAndroid Build Coastguard Worker           DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
1552*9880d681SAndroid Build Coastguard Worker           CanVecMem = false;
1553*9880d681SAndroid Build Coastguard Worker           return;
1554*9880d681SAndroid Build Coastguard Worker         }
1555*9880d681SAndroid Build Coastguard Worker         NumLoads++;
1556*9880d681SAndroid Build Coastguard Worker         Loads.push_back(Ld);
1557*9880d681SAndroid Build Coastguard Worker         DepChecker->addAccess(Ld);
1558*9880d681SAndroid Build Coastguard Worker         if (EnableMemAccessVersioning)
1559*9880d681SAndroid Build Coastguard Worker           collectStridedAccess(Ld);
1560*9880d681SAndroid Build Coastguard Worker         continue;
1561*9880d681SAndroid Build Coastguard Worker       }
1562*9880d681SAndroid Build Coastguard Worker 
1563*9880d681SAndroid Build Coastguard Worker       // Save 'store' instructions. Abort if other instructions write to memory.
1564*9880d681SAndroid Build Coastguard Worker       if (I.mayWriteToMemory()) {
1565*9880d681SAndroid Build Coastguard Worker         auto *St = dyn_cast<StoreInst>(&I);
1566*9880d681SAndroid Build Coastguard Worker         if (!St) {
1567*9880d681SAndroid Build Coastguard Worker           emitAnalysis(LoopAccessReport(St)
1568*9880d681SAndroid Build Coastguard Worker                        << "instruction cannot be vectorized");
1569*9880d681SAndroid Build Coastguard Worker           CanVecMem = false;
1570*9880d681SAndroid Build Coastguard Worker           return;
1571*9880d681SAndroid Build Coastguard Worker         }
1572*9880d681SAndroid Build Coastguard Worker         if (!St->isSimple() && !IsAnnotatedParallel) {
1573*9880d681SAndroid Build Coastguard Worker           emitAnalysis(LoopAccessReport(St)
1574*9880d681SAndroid Build Coastguard Worker                        << "write with atomic ordering or volatile write");
1575*9880d681SAndroid Build Coastguard Worker           DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
1576*9880d681SAndroid Build Coastguard Worker           CanVecMem = false;
1577*9880d681SAndroid Build Coastguard Worker           return;
1578*9880d681SAndroid Build Coastguard Worker         }
1579*9880d681SAndroid Build Coastguard Worker         NumStores++;
1580*9880d681SAndroid Build Coastguard Worker         Stores.push_back(St);
1581*9880d681SAndroid Build Coastguard Worker         DepChecker->addAccess(St);
1582*9880d681SAndroid Build Coastguard Worker         if (EnableMemAccessVersioning)
1583*9880d681SAndroid Build Coastguard Worker           collectStridedAccess(St);
1584*9880d681SAndroid Build Coastguard Worker       }
1585*9880d681SAndroid Build Coastguard Worker     } // Next instr.
1586*9880d681SAndroid Build Coastguard Worker   } // Next block.
1587*9880d681SAndroid Build Coastguard Worker 
1588*9880d681SAndroid Build Coastguard Worker   // Now we have two lists that hold the loads and the stores.
1589*9880d681SAndroid Build Coastguard Worker   // Next, we find the pointers that they use.
1590*9880d681SAndroid Build Coastguard Worker 
1591*9880d681SAndroid Build Coastguard Worker   // Check if we see any stores. If there are no stores, then we don't
1592*9880d681SAndroid Build Coastguard Worker   // care if the pointers are *restrict*.
1593*9880d681SAndroid Build Coastguard Worker   if (!Stores.size()) {
1594*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
1595*9880d681SAndroid Build Coastguard Worker     CanVecMem = true;
1596*9880d681SAndroid Build Coastguard Worker     return;
1597*9880d681SAndroid Build Coastguard Worker   }
1598*9880d681SAndroid Build Coastguard Worker 
1599*9880d681SAndroid Build Coastguard Worker   MemoryDepChecker::DepCandidates DependentAccesses;
1600*9880d681SAndroid Build Coastguard Worker   AccessAnalysis Accesses(TheLoop->getHeader()->getModule()->getDataLayout(),
1601*9880d681SAndroid Build Coastguard Worker                           AA, LI, DependentAccesses, *PSE);
1602*9880d681SAndroid Build Coastguard Worker 
1603*9880d681SAndroid Build Coastguard Worker   // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1604*9880d681SAndroid Build Coastguard Worker   // multiple times on the same object. If the ptr is accessed twice, once
1605*9880d681SAndroid Build Coastguard Worker   // for read and once for write, it will only appear once (on the write
1606*9880d681SAndroid Build Coastguard Worker   // list). This is okay, since we are going to check for conflicts between
1607*9880d681SAndroid Build Coastguard Worker   // writes and between reads and writes, but not between reads and reads.
1608*9880d681SAndroid Build Coastguard Worker   ValueSet Seen;
1609*9880d681SAndroid Build Coastguard Worker 
1610*9880d681SAndroid Build Coastguard Worker   for (StoreInst *ST : Stores) {
1611*9880d681SAndroid Build Coastguard Worker     Value *Ptr = ST->getPointerOperand();
1612*9880d681SAndroid Build Coastguard Worker     // Check for store to loop invariant address.
1613*9880d681SAndroid Build Coastguard Worker     StoreToLoopInvariantAddress |= isUniform(Ptr);
1614*9880d681SAndroid Build Coastguard Worker     // If we did *not* see this pointer before, insert it to  the read-write
1615*9880d681SAndroid Build Coastguard Worker     // list. At this phase it is only a 'write' list.
1616*9880d681SAndroid Build Coastguard Worker     if (Seen.insert(Ptr).second) {
1617*9880d681SAndroid Build Coastguard Worker       ++NumReadWrites;
1618*9880d681SAndroid Build Coastguard Worker 
1619*9880d681SAndroid Build Coastguard Worker       MemoryLocation Loc = MemoryLocation::get(ST);
1620*9880d681SAndroid Build Coastguard Worker       // The TBAA metadata could have a control dependency on the predication
1621*9880d681SAndroid Build Coastguard Worker       // condition, so we cannot rely on it when determining whether or not we
1622*9880d681SAndroid Build Coastguard Worker       // need runtime pointer checks.
1623*9880d681SAndroid Build Coastguard Worker       if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
1624*9880d681SAndroid Build Coastguard Worker         Loc.AATags.TBAA = nullptr;
1625*9880d681SAndroid Build Coastguard Worker 
1626*9880d681SAndroid Build Coastguard Worker       Accesses.addStore(Loc);
1627*9880d681SAndroid Build Coastguard Worker     }
1628*9880d681SAndroid Build Coastguard Worker   }
1629*9880d681SAndroid Build Coastguard Worker 
1630*9880d681SAndroid Build Coastguard Worker   if (IsAnnotatedParallel) {
1631*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs()
1632*9880d681SAndroid Build Coastguard Worker           << "LAA: A loop annotated parallel, ignore memory dependency "
1633*9880d681SAndroid Build Coastguard Worker           << "checks.\n");
1634*9880d681SAndroid Build Coastguard Worker     CanVecMem = true;
1635*9880d681SAndroid Build Coastguard Worker     return;
1636*9880d681SAndroid Build Coastguard Worker   }
1637*9880d681SAndroid Build Coastguard Worker 
1638*9880d681SAndroid Build Coastguard Worker   for (LoadInst *LD : Loads) {
1639*9880d681SAndroid Build Coastguard Worker     Value *Ptr = LD->getPointerOperand();
1640*9880d681SAndroid Build Coastguard Worker     // If we did *not* see this pointer before, insert it to the
1641*9880d681SAndroid Build Coastguard Worker     // read list. If we *did* see it before, then it is already in
1642*9880d681SAndroid Build Coastguard Worker     // the read-write list. This allows us to vectorize expressions
1643*9880d681SAndroid Build Coastguard Worker     // such as A[i] += x;  Because the address of A[i] is a read-write
1644*9880d681SAndroid Build Coastguard Worker     // pointer. This only works if the index of A[i] is consecutive.
1645*9880d681SAndroid Build Coastguard Worker     // If the address of i is unknown (for example A[B[i]]) then we may
1646*9880d681SAndroid Build Coastguard Worker     // read a few words, modify, and write a few words, and some of the
1647*9880d681SAndroid Build Coastguard Worker     // words may be written to the same address.
1648*9880d681SAndroid Build Coastguard Worker     bool IsReadOnlyPtr = false;
1649*9880d681SAndroid Build Coastguard Worker     if (Seen.insert(Ptr).second ||
1650*9880d681SAndroid Build Coastguard Worker         !getPtrStride(*PSE, Ptr, TheLoop, SymbolicStrides)) {
1651*9880d681SAndroid Build Coastguard Worker       ++NumReads;
1652*9880d681SAndroid Build Coastguard Worker       IsReadOnlyPtr = true;
1653*9880d681SAndroid Build Coastguard Worker     }
1654*9880d681SAndroid Build Coastguard Worker 
1655*9880d681SAndroid Build Coastguard Worker     MemoryLocation Loc = MemoryLocation::get(LD);
1656*9880d681SAndroid Build Coastguard Worker     // The TBAA metadata could have a control dependency on the predication
1657*9880d681SAndroid Build Coastguard Worker     // condition, so we cannot rely on it when determining whether or not we
1658*9880d681SAndroid Build Coastguard Worker     // need runtime pointer checks.
1659*9880d681SAndroid Build Coastguard Worker     if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
1660*9880d681SAndroid Build Coastguard Worker       Loc.AATags.TBAA = nullptr;
1661*9880d681SAndroid Build Coastguard Worker 
1662*9880d681SAndroid Build Coastguard Worker     Accesses.addLoad(Loc, IsReadOnlyPtr);
1663*9880d681SAndroid Build Coastguard Worker   }
1664*9880d681SAndroid Build Coastguard Worker 
1665*9880d681SAndroid Build Coastguard Worker   // If we write (or read-write) to a single destination and there are no
1666*9880d681SAndroid Build Coastguard Worker   // other reads in this loop then is it safe to vectorize.
1667*9880d681SAndroid Build Coastguard Worker   if (NumReadWrites == 1 && NumReads == 0) {
1668*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
1669*9880d681SAndroid Build Coastguard Worker     CanVecMem = true;
1670*9880d681SAndroid Build Coastguard Worker     return;
1671*9880d681SAndroid Build Coastguard Worker   }
1672*9880d681SAndroid Build Coastguard Worker 
1673*9880d681SAndroid Build Coastguard Worker   // Build dependence sets and check whether we need a runtime pointer bounds
1674*9880d681SAndroid Build Coastguard Worker   // check.
1675*9880d681SAndroid Build Coastguard Worker   Accesses.buildDependenceSets();
1676*9880d681SAndroid Build Coastguard Worker 
1677*9880d681SAndroid Build Coastguard Worker   // Find pointers with computable bounds. We are going to use this information
1678*9880d681SAndroid Build Coastguard Worker   // to place a runtime bound check.
1679*9880d681SAndroid Build Coastguard Worker   bool CanDoRTIfNeeded = Accesses.canCheckPtrAtRT(*PtrRtChecking, PSE->getSE(),
1680*9880d681SAndroid Build Coastguard Worker                                                   TheLoop, SymbolicStrides);
1681*9880d681SAndroid Build Coastguard Worker   if (!CanDoRTIfNeeded) {
1682*9880d681SAndroid Build Coastguard Worker     emitAnalysis(LoopAccessReport() << "cannot identify array bounds");
1683*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "LAA: We can't vectorize because we can't find "
1684*9880d681SAndroid Build Coastguard Worker                  << "the array bounds.\n");
1685*9880d681SAndroid Build Coastguard Worker     CanVecMem = false;
1686*9880d681SAndroid Build Coastguard Worker     return;
1687*9880d681SAndroid Build Coastguard Worker   }
1688*9880d681SAndroid Build Coastguard Worker 
1689*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
1690*9880d681SAndroid Build Coastguard Worker 
1691*9880d681SAndroid Build Coastguard Worker   CanVecMem = true;
1692*9880d681SAndroid Build Coastguard Worker   if (Accesses.isDependencyCheckNeeded()) {
1693*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
1694*9880d681SAndroid Build Coastguard Worker     CanVecMem = DepChecker->areDepsSafe(
1695*9880d681SAndroid Build Coastguard Worker         DependentAccesses, Accesses.getDependenciesToCheck(), SymbolicStrides);
1696*9880d681SAndroid Build Coastguard Worker     MaxSafeDepDistBytes = DepChecker->getMaxSafeDepDistBytes();
1697*9880d681SAndroid Build Coastguard Worker 
1698*9880d681SAndroid Build Coastguard Worker     if (!CanVecMem && DepChecker->shouldRetryWithRuntimeCheck()) {
1699*9880d681SAndroid Build Coastguard Worker       DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
1700*9880d681SAndroid Build Coastguard Worker 
1701*9880d681SAndroid Build Coastguard Worker       // Clear the dependency checks. We assume they are not needed.
1702*9880d681SAndroid Build Coastguard Worker       Accesses.resetDepChecks(*DepChecker);
1703*9880d681SAndroid Build Coastguard Worker 
1704*9880d681SAndroid Build Coastguard Worker       PtrRtChecking->reset();
1705*9880d681SAndroid Build Coastguard Worker       PtrRtChecking->Need = true;
1706*9880d681SAndroid Build Coastguard Worker 
1707*9880d681SAndroid Build Coastguard Worker       auto *SE = PSE->getSE();
1708*9880d681SAndroid Build Coastguard Worker       CanDoRTIfNeeded = Accesses.canCheckPtrAtRT(*PtrRtChecking, SE, TheLoop,
1709*9880d681SAndroid Build Coastguard Worker                                                  SymbolicStrides, true);
1710*9880d681SAndroid Build Coastguard Worker 
1711*9880d681SAndroid Build Coastguard Worker       // Check that we found the bounds for the pointer.
1712*9880d681SAndroid Build Coastguard Worker       if (!CanDoRTIfNeeded) {
1713*9880d681SAndroid Build Coastguard Worker         emitAnalysis(LoopAccessReport()
1714*9880d681SAndroid Build Coastguard Worker                      << "cannot check memory dependencies at runtime");
1715*9880d681SAndroid Build Coastguard Worker         DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
1716*9880d681SAndroid Build Coastguard Worker         CanVecMem = false;
1717*9880d681SAndroid Build Coastguard Worker         return;
1718*9880d681SAndroid Build Coastguard Worker       }
1719*9880d681SAndroid Build Coastguard Worker 
1720*9880d681SAndroid Build Coastguard Worker       CanVecMem = true;
1721*9880d681SAndroid Build Coastguard Worker     }
1722*9880d681SAndroid Build Coastguard Worker   }
1723*9880d681SAndroid Build Coastguard Worker 
1724*9880d681SAndroid Build Coastguard Worker   if (CanVecMem)
1725*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "LAA: No unsafe dependent memory operations in loop.  We"
1726*9880d681SAndroid Build Coastguard Worker                  << (PtrRtChecking->Need ? "" : " don't")
1727*9880d681SAndroid Build Coastguard Worker                  << " need runtime memory checks.\n");
1728*9880d681SAndroid Build Coastguard Worker   else {
1729*9880d681SAndroid Build Coastguard Worker     emitAnalysis(
1730*9880d681SAndroid Build Coastguard Worker         LoopAccessReport()
1731*9880d681SAndroid Build Coastguard Worker         << "unsafe dependent memory operations in loop. Use "
1732*9880d681SAndroid Build Coastguard Worker            "#pragma loop distribute(enable) to allow loop distribution "
1733*9880d681SAndroid Build Coastguard Worker            "to attempt to isolate the offending operations into a separate "
1734*9880d681SAndroid Build Coastguard Worker            "loop");
1735*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
1736*9880d681SAndroid Build Coastguard Worker   }
1737*9880d681SAndroid Build Coastguard Worker }
1738*9880d681SAndroid Build Coastguard Worker 
blockNeedsPredication(BasicBlock * BB,Loop * TheLoop,DominatorTree * DT)1739*9880d681SAndroid Build Coastguard Worker bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
1740*9880d681SAndroid Build Coastguard Worker                                            DominatorTree *DT)  {
1741*9880d681SAndroid Build Coastguard Worker   assert(TheLoop->contains(BB) && "Unknown block used");
1742*9880d681SAndroid Build Coastguard Worker 
1743*9880d681SAndroid Build Coastguard Worker   // Blocks that do not dominate the latch need predication.
1744*9880d681SAndroid Build Coastguard Worker   BasicBlock* Latch = TheLoop->getLoopLatch();
1745*9880d681SAndroid Build Coastguard Worker   return !DT->dominates(BB, Latch);
1746*9880d681SAndroid Build Coastguard Worker }
1747*9880d681SAndroid Build Coastguard Worker 
emitAnalysis(LoopAccessReport & Message)1748*9880d681SAndroid Build Coastguard Worker void LoopAccessInfo::emitAnalysis(LoopAccessReport &Message) {
1749*9880d681SAndroid Build Coastguard Worker   assert(!Report && "Multiple reports generated");
1750*9880d681SAndroid Build Coastguard Worker   Report = Message;
1751*9880d681SAndroid Build Coastguard Worker }
1752*9880d681SAndroid Build Coastguard Worker 
isUniform(Value * V) const1753*9880d681SAndroid Build Coastguard Worker bool LoopAccessInfo::isUniform(Value *V) const {
1754*9880d681SAndroid Build Coastguard Worker   return (PSE->getSE()->isLoopInvariant(PSE->getSE()->getSCEV(V), TheLoop));
1755*9880d681SAndroid Build Coastguard Worker }
1756*9880d681SAndroid Build Coastguard Worker 
1757*9880d681SAndroid Build Coastguard Worker // FIXME: this function is currently a duplicate of the one in
1758*9880d681SAndroid Build Coastguard Worker // LoopVectorize.cpp.
getFirstInst(Instruction * FirstInst,Value * V,Instruction * Loc)1759*9880d681SAndroid Build Coastguard Worker static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1760*9880d681SAndroid Build Coastguard Worker                                  Instruction *Loc) {
1761*9880d681SAndroid Build Coastguard Worker   if (FirstInst)
1762*9880d681SAndroid Build Coastguard Worker     return FirstInst;
1763*9880d681SAndroid Build Coastguard Worker   if (Instruction *I = dyn_cast<Instruction>(V))
1764*9880d681SAndroid Build Coastguard Worker     return I->getParent() == Loc->getParent() ? I : nullptr;
1765*9880d681SAndroid Build Coastguard Worker   return nullptr;
1766*9880d681SAndroid Build Coastguard Worker }
1767*9880d681SAndroid Build Coastguard Worker 
1768*9880d681SAndroid Build Coastguard Worker namespace {
1769*9880d681SAndroid Build Coastguard Worker /// \brief IR Values for the lower and upper bounds of a pointer evolution.  We
1770*9880d681SAndroid Build Coastguard Worker /// need to use value-handles because SCEV expansion can invalidate previously
1771*9880d681SAndroid Build Coastguard Worker /// expanded values.  Thus expansion of a pointer can invalidate the bounds for
1772*9880d681SAndroid Build Coastguard Worker /// a previous one.
1773*9880d681SAndroid Build Coastguard Worker struct PointerBounds {
1774*9880d681SAndroid Build Coastguard Worker   TrackingVH<Value> Start;
1775*9880d681SAndroid Build Coastguard Worker   TrackingVH<Value> End;
1776*9880d681SAndroid Build Coastguard Worker };
1777*9880d681SAndroid Build Coastguard Worker } // end anonymous namespace
1778*9880d681SAndroid Build Coastguard Worker 
1779*9880d681SAndroid Build Coastguard Worker /// \brief Expand code for the lower and upper bound of the pointer group \p CG
1780*9880d681SAndroid Build Coastguard Worker /// in \p TheLoop.  \return the values for the bounds.
1781*9880d681SAndroid Build Coastguard Worker static PointerBounds
expandBounds(const RuntimePointerChecking::CheckingPtrGroup * CG,Loop * TheLoop,Instruction * Loc,SCEVExpander & Exp,ScalarEvolution * SE,const RuntimePointerChecking & PtrRtChecking)1782*9880d681SAndroid Build Coastguard Worker expandBounds(const RuntimePointerChecking::CheckingPtrGroup *CG, Loop *TheLoop,
1783*9880d681SAndroid Build Coastguard Worker              Instruction *Loc, SCEVExpander &Exp, ScalarEvolution *SE,
1784*9880d681SAndroid Build Coastguard Worker              const RuntimePointerChecking &PtrRtChecking) {
1785*9880d681SAndroid Build Coastguard Worker   Value *Ptr = PtrRtChecking.Pointers[CG->Members[0]].PointerValue;
1786*9880d681SAndroid Build Coastguard Worker   const SCEV *Sc = SE->getSCEV(Ptr);
1787*9880d681SAndroid Build Coastguard Worker 
1788*9880d681SAndroid Build Coastguard Worker   if (SE->isLoopInvariant(Sc, TheLoop)) {
1789*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" << *Ptr
1790*9880d681SAndroid Build Coastguard Worker                  << "\n");
1791*9880d681SAndroid Build Coastguard Worker     return {Ptr, Ptr};
1792*9880d681SAndroid Build Coastguard Worker   } else {
1793*9880d681SAndroid Build Coastguard Worker     unsigned AS = Ptr->getType()->getPointerAddressSpace();
1794*9880d681SAndroid Build Coastguard Worker     LLVMContext &Ctx = Loc->getContext();
1795*9880d681SAndroid Build Coastguard Worker 
1796*9880d681SAndroid Build Coastguard Worker     // Use this type for pointer arithmetic.
1797*9880d681SAndroid Build Coastguard Worker     Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1798*9880d681SAndroid Build Coastguard Worker     Value *Start = nullptr, *End = nullptr;
1799*9880d681SAndroid Build Coastguard Worker 
1800*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "LAA: Adding RT check for range:\n");
1801*9880d681SAndroid Build Coastguard Worker     Start = Exp.expandCodeFor(CG->Low, PtrArithTy, Loc);
1802*9880d681SAndroid Build Coastguard Worker     End = Exp.expandCodeFor(CG->High, PtrArithTy, Loc);
1803*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "Start: " << *CG->Low << " End: " << *CG->High << "\n");
1804*9880d681SAndroid Build Coastguard Worker     return {Start, End};
1805*9880d681SAndroid Build Coastguard Worker   }
1806*9880d681SAndroid Build Coastguard Worker }
1807*9880d681SAndroid Build Coastguard Worker 
1808*9880d681SAndroid Build Coastguard Worker /// \brief Turns a collection of checks into a collection of expanded upper and
1809*9880d681SAndroid Build Coastguard Worker /// lower bounds for both pointers in the check.
expandBounds(const SmallVectorImpl<RuntimePointerChecking::PointerCheck> & PointerChecks,Loop * L,Instruction * Loc,ScalarEvolution * SE,SCEVExpander & Exp,const RuntimePointerChecking & PtrRtChecking)1810*9880d681SAndroid Build Coastguard Worker static SmallVector<std::pair<PointerBounds, PointerBounds>, 4> expandBounds(
1811*9880d681SAndroid Build Coastguard Worker     const SmallVectorImpl<RuntimePointerChecking::PointerCheck> &PointerChecks,
1812*9880d681SAndroid Build Coastguard Worker     Loop *L, Instruction *Loc, ScalarEvolution *SE, SCEVExpander &Exp,
1813*9880d681SAndroid Build Coastguard Worker     const RuntimePointerChecking &PtrRtChecking) {
1814*9880d681SAndroid Build Coastguard Worker   SmallVector<std::pair<PointerBounds, PointerBounds>, 4> ChecksWithBounds;
1815*9880d681SAndroid Build Coastguard Worker 
1816*9880d681SAndroid Build Coastguard Worker   // Here we're relying on the SCEV Expander's cache to only emit code for the
1817*9880d681SAndroid Build Coastguard Worker   // same bounds once.
1818*9880d681SAndroid Build Coastguard Worker   std::transform(
1819*9880d681SAndroid Build Coastguard Worker       PointerChecks.begin(), PointerChecks.end(),
1820*9880d681SAndroid Build Coastguard Worker       std::back_inserter(ChecksWithBounds),
1821*9880d681SAndroid Build Coastguard Worker       [&](const RuntimePointerChecking::PointerCheck &Check) {
1822*9880d681SAndroid Build Coastguard Worker         PointerBounds
1823*9880d681SAndroid Build Coastguard Worker           First = expandBounds(Check.first, L, Loc, Exp, SE, PtrRtChecking),
1824*9880d681SAndroid Build Coastguard Worker           Second = expandBounds(Check.second, L, Loc, Exp, SE, PtrRtChecking);
1825*9880d681SAndroid Build Coastguard Worker         return std::make_pair(First, Second);
1826*9880d681SAndroid Build Coastguard Worker       });
1827*9880d681SAndroid Build Coastguard Worker 
1828*9880d681SAndroid Build Coastguard Worker   return ChecksWithBounds;
1829*9880d681SAndroid Build Coastguard Worker }
1830*9880d681SAndroid Build Coastguard Worker 
addRuntimeChecks(Instruction * Loc,const SmallVectorImpl<RuntimePointerChecking::PointerCheck> & PointerChecks) const1831*9880d681SAndroid Build Coastguard Worker std::pair<Instruction *, Instruction *> LoopAccessInfo::addRuntimeChecks(
1832*9880d681SAndroid Build Coastguard Worker     Instruction *Loc,
1833*9880d681SAndroid Build Coastguard Worker     const SmallVectorImpl<RuntimePointerChecking::PointerCheck> &PointerChecks)
1834*9880d681SAndroid Build Coastguard Worker     const {
1835*9880d681SAndroid Build Coastguard Worker   const DataLayout &DL = TheLoop->getHeader()->getModule()->getDataLayout();
1836*9880d681SAndroid Build Coastguard Worker   auto *SE = PSE->getSE();
1837*9880d681SAndroid Build Coastguard Worker   SCEVExpander Exp(*SE, DL, "induction");
1838*9880d681SAndroid Build Coastguard Worker   auto ExpandedChecks =
1839*9880d681SAndroid Build Coastguard Worker       expandBounds(PointerChecks, TheLoop, Loc, SE, Exp, *PtrRtChecking);
1840*9880d681SAndroid Build Coastguard Worker 
1841*9880d681SAndroid Build Coastguard Worker   LLVMContext &Ctx = Loc->getContext();
1842*9880d681SAndroid Build Coastguard Worker   Instruction *FirstInst = nullptr;
1843*9880d681SAndroid Build Coastguard Worker   IRBuilder<> ChkBuilder(Loc);
1844*9880d681SAndroid Build Coastguard Worker   // Our instructions might fold to a constant.
1845*9880d681SAndroid Build Coastguard Worker   Value *MemoryRuntimeCheck = nullptr;
1846*9880d681SAndroid Build Coastguard Worker 
1847*9880d681SAndroid Build Coastguard Worker   for (const auto &Check : ExpandedChecks) {
1848*9880d681SAndroid Build Coastguard Worker     const PointerBounds &A = Check.first, &B = Check.second;
1849*9880d681SAndroid Build Coastguard Worker     // Check if two pointers (A and B) conflict where conflict is computed as:
1850*9880d681SAndroid Build Coastguard Worker     // start(A) <= end(B) && start(B) <= end(A)
1851*9880d681SAndroid Build Coastguard Worker     unsigned AS0 = A.Start->getType()->getPointerAddressSpace();
1852*9880d681SAndroid Build Coastguard Worker     unsigned AS1 = B.Start->getType()->getPointerAddressSpace();
1853*9880d681SAndroid Build Coastguard Worker 
1854*9880d681SAndroid Build Coastguard Worker     assert((AS0 == B.End->getType()->getPointerAddressSpace()) &&
1855*9880d681SAndroid Build Coastguard Worker            (AS1 == A.End->getType()->getPointerAddressSpace()) &&
1856*9880d681SAndroid Build Coastguard Worker            "Trying to bounds check pointers with different address spaces");
1857*9880d681SAndroid Build Coastguard Worker 
1858*9880d681SAndroid Build Coastguard Worker     Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1859*9880d681SAndroid Build Coastguard Worker     Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
1860*9880d681SAndroid Build Coastguard Worker 
1861*9880d681SAndroid Build Coastguard Worker     Value *Start0 = ChkBuilder.CreateBitCast(A.Start, PtrArithTy0, "bc");
1862*9880d681SAndroid Build Coastguard Worker     Value *Start1 = ChkBuilder.CreateBitCast(B.Start, PtrArithTy1, "bc");
1863*9880d681SAndroid Build Coastguard Worker     Value *End0 =   ChkBuilder.CreateBitCast(A.End,   PtrArithTy1, "bc");
1864*9880d681SAndroid Build Coastguard Worker     Value *End1 =   ChkBuilder.CreateBitCast(B.End,   PtrArithTy0, "bc");
1865*9880d681SAndroid Build Coastguard Worker 
1866*9880d681SAndroid Build Coastguard Worker     Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1867*9880d681SAndroid Build Coastguard Worker     FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1868*9880d681SAndroid Build Coastguard Worker     Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1869*9880d681SAndroid Build Coastguard Worker     FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1870*9880d681SAndroid Build Coastguard Worker     Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1871*9880d681SAndroid Build Coastguard Worker     FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1872*9880d681SAndroid Build Coastguard Worker     if (MemoryRuntimeCheck) {
1873*9880d681SAndroid Build Coastguard Worker       IsConflict =
1874*9880d681SAndroid Build Coastguard Worker           ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx");
1875*9880d681SAndroid Build Coastguard Worker       FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1876*9880d681SAndroid Build Coastguard Worker     }
1877*9880d681SAndroid Build Coastguard Worker     MemoryRuntimeCheck = IsConflict;
1878*9880d681SAndroid Build Coastguard Worker   }
1879*9880d681SAndroid Build Coastguard Worker 
1880*9880d681SAndroid Build Coastguard Worker   if (!MemoryRuntimeCheck)
1881*9880d681SAndroid Build Coastguard Worker     return std::make_pair(nullptr, nullptr);
1882*9880d681SAndroid Build Coastguard Worker 
1883*9880d681SAndroid Build Coastguard Worker   // We have to do this trickery because the IRBuilder might fold the check to a
1884*9880d681SAndroid Build Coastguard Worker   // constant expression in which case there is no Instruction anchored in a
1885*9880d681SAndroid Build Coastguard Worker   // the block.
1886*9880d681SAndroid Build Coastguard Worker   Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1887*9880d681SAndroid Build Coastguard Worker                                                  ConstantInt::getTrue(Ctx));
1888*9880d681SAndroid Build Coastguard Worker   ChkBuilder.Insert(Check, "memcheck.conflict");
1889*9880d681SAndroid Build Coastguard Worker   FirstInst = getFirstInst(FirstInst, Check, Loc);
1890*9880d681SAndroid Build Coastguard Worker   return std::make_pair(FirstInst, Check);
1891*9880d681SAndroid Build Coastguard Worker }
1892*9880d681SAndroid Build Coastguard Worker 
1893*9880d681SAndroid Build Coastguard Worker std::pair<Instruction *, Instruction *>
addRuntimeChecks(Instruction * Loc) const1894*9880d681SAndroid Build Coastguard Worker LoopAccessInfo::addRuntimeChecks(Instruction *Loc) const {
1895*9880d681SAndroid Build Coastguard Worker   if (!PtrRtChecking->Need)
1896*9880d681SAndroid Build Coastguard Worker     return std::make_pair(nullptr, nullptr);
1897*9880d681SAndroid Build Coastguard Worker 
1898*9880d681SAndroid Build Coastguard Worker   return addRuntimeChecks(Loc, PtrRtChecking->getChecks());
1899*9880d681SAndroid Build Coastguard Worker }
1900*9880d681SAndroid Build Coastguard Worker 
collectStridedAccess(Value * MemAccess)1901*9880d681SAndroid Build Coastguard Worker void LoopAccessInfo::collectStridedAccess(Value *MemAccess) {
1902*9880d681SAndroid Build Coastguard Worker   Value *Ptr = nullptr;
1903*9880d681SAndroid Build Coastguard Worker   if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
1904*9880d681SAndroid Build Coastguard Worker     Ptr = LI->getPointerOperand();
1905*9880d681SAndroid Build Coastguard Worker   else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
1906*9880d681SAndroid Build Coastguard Worker     Ptr = SI->getPointerOperand();
1907*9880d681SAndroid Build Coastguard Worker   else
1908*9880d681SAndroid Build Coastguard Worker     return;
1909*9880d681SAndroid Build Coastguard Worker 
1910*9880d681SAndroid Build Coastguard Worker   Value *Stride = getStrideFromPointer(Ptr, PSE->getSE(), TheLoop);
1911*9880d681SAndroid Build Coastguard Worker   if (!Stride)
1912*9880d681SAndroid Build Coastguard Worker     return;
1913*9880d681SAndroid Build Coastguard Worker 
1914*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "LAA: Found a strided access that we can version");
1915*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "  Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
1916*9880d681SAndroid Build Coastguard Worker   SymbolicStrides[Ptr] = Stride;
1917*9880d681SAndroid Build Coastguard Worker   StrideSet.insert(Stride);
1918*9880d681SAndroid Build Coastguard Worker }
1919*9880d681SAndroid Build Coastguard Worker 
LoopAccessInfo(Loop * L,ScalarEvolution * SE,const TargetLibraryInfo * TLI,AliasAnalysis * AA,DominatorTree * DT,LoopInfo * LI)1920*9880d681SAndroid Build Coastguard Worker LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
1921*9880d681SAndroid Build Coastguard Worker                                const TargetLibraryInfo *TLI, AliasAnalysis *AA,
1922*9880d681SAndroid Build Coastguard Worker                                DominatorTree *DT, LoopInfo *LI)
1923*9880d681SAndroid Build Coastguard Worker     : PSE(llvm::make_unique<PredicatedScalarEvolution>(*SE, *L)),
1924*9880d681SAndroid Build Coastguard Worker       PtrRtChecking(llvm::make_unique<RuntimePointerChecking>(SE)),
1925*9880d681SAndroid Build Coastguard Worker       DepChecker(llvm::make_unique<MemoryDepChecker>(*PSE, L)), TheLoop(L),
1926*9880d681SAndroid Build Coastguard Worker       NumLoads(0), NumStores(0), MaxSafeDepDistBytes(-1), CanVecMem(false),
1927*9880d681SAndroid Build Coastguard Worker       StoreToLoopInvariantAddress(false) {
1928*9880d681SAndroid Build Coastguard Worker   if (canAnalyzeLoop())
1929*9880d681SAndroid Build Coastguard Worker     analyzeLoop(AA, LI, TLI, DT);
1930*9880d681SAndroid Build Coastguard Worker }
1931*9880d681SAndroid Build Coastguard Worker 
print(raw_ostream & OS,unsigned Depth) const1932*9880d681SAndroid Build Coastguard Worker void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
1933*9880d681SAndroid Build Coastguard Worker   if (CanVecMem) {
1934*9880d681SAndroid Build Coastguard Worker     OS.indent(Depth) << "Memory dependences are safe";
1935*9880d681SAndroid Build Coastguard Worker     if (MaxSafeDepDistBytes != -1ULL)
1936*9880d681SAndroid Build Coastguard Worker       OS << " with a maximum dependence distance of " << MaxSafeDepDistBytes
1937*9880d681SAndroid Build Coastguard Worker          << " bytes";
1938*9880d681SAndroid Build Coastguard Worker     if (PtrRtChecking->Need)
1939*9880d681SAndroid Build Coastguard Worker       OS << " with run-time checks";
1940*9880d681SAndroid Build Coastguard Worker     OS << "\n";
1941*9880d681SAndroid Build Coastguard Worker   }
1942*9880d681SAndroid Build Coastguard Worker 
1943*9880d681SAndroid Build Coastguard Worker   if (Report)
1944*9880d681SAndroid Build Coastguard Worker     OS.indent(Depth) << "Report: " << Report->str() << "\n";
1945*9880d681SAndroid Build Coastguard Worker 
1946*9880d681SAndroid Build Coastguard Worker   if (auto *Dependences = DepChecker->getDependences()) {
1947*9880d681SAndroid Build Coastguard Worker     OS.indent(Depth) << "Dependences:\n";
1948*9880d681SAndroid Build Coastguard Worker     for (auto &Dep : *Dependences) {
1949*9880d681SAndroid Build Coastguard Worker       Dep.print(OS, Depth + 2, DepChecker->getMemoryInstructions());
1950*9880d681SAndroid Build Coastguard Worker       OS << "\n";
1951*9880d681SAndroid Build Coastguard Worker     }
1952*9880d681SAndroid Build Coastguard Worker   } else
1953*9880d681SAndroid Build Coastguard Worker     OS.indent(Depth) << "Too many dependences, not recorded\n";
1954*9880d681SAndroid Build Coastguard Worker 
1955*9880d681SAndroid Build Coastguard Worker   // List the pair of accesses need run-time checks to prove independence.
1956*9880d681SAndroid Build Coastguard Worker   PtrRtChecking->print(OS, Depth);
1957*9880d681SAndroid Build Coastguard Worker   OS << "\n";
1958*9880d681SAndroid Build Coastguard Worker 
1959*9880d681SAndroid Build Coastguard Worker   OS.indent(Depth) << "Store to invariant address was "
1960*9880d681SAndroid Build Coastguard Worker                    << (StoreToLoopInvariantAddress ? "" : "not ")
1961*9880d681SAndroid Build Coastguard Worker                    << "found in loop.\n";
1962*9880d681SAndroid Build Coastguard Worker 
1963*9880d681SAndroid Build Coastguard Worker   OS.indent(Depth) << "SCEV assumptions:\n";
1964*9880d681SAndroid Build Coastguard Worker   PSE->getUnionPredicate().print(OS, Depth);
1965*9880d681SAndroid Build Coastguard Worker 
1966*9880d681SAndroid Build Coastguard Worker   OS << "\n";
1967*9880d681SAndroid Build Coastguard Worker 
1968*9880d681SAndroid Build Coastguard Worker   OS.indent(Depth) << "Expressions re-written:\n";
1969*9880d681SAndroid Build Coastguard Worker   PSE->print(OS, Depth);
1970*9880d681SAndroid Build Coastguard Worker }
1971*9880d681SAndroid Build Coastguard Worker 
getInfo(Loop * L)1972*9880d681SAndroid Build Coastguard Worker const LoopAccessInfo &LoopAccessLegacyAnalysis::getInfo(Loop *L) {
1973*9880d681SAndroid Build Coastguard Worker   auto &LAI = LoopAccessInfoMap[L];
1974*9880d681SAndroid Build Coastguard Worker 
1975*9880d681SAndroid Build Coastguard Worker   if (!LAI)
1976*9880d681SAndroid Build Coastguard Worker     LAI = llvm::make_unique<LoopAccessInfo>(L, SE, TLI, AA, DT, LI);
1977*9880d681SAndroid Build Coastguard Worker 
1978*9880d681SAndroid Build Coastguard Worker   return *LAI.get();
1979*9880d681SAndroid Build Coastguard Worker }
1980*9880d681SAndroid Build Coastguard Worker 
print(raw_ostream & OS,const Module * M) const1981*9880d681SAndroid Build Coastguard Worker void LoopAccessLegacyAnalysis::print(raw_ostream &OS, const Module *M) const {
1982*9880d681SAndroid Build Coastguard Worker   LoopAccessLegacyAnalysis &LAA = *const_cast<LoopAccessLegacyAnalysis *>(this);
1983*9880d681SAndroid Build Coastguard Worker 
1984*9880d681SAndroid Build Coastguard Worker   for (Loop *TopLevelLoop : *LI)
1985*9880d681SAndroid Build Coastguard Worker     for (Loop *L : depth_first(TopLevelLoop)) {
1986*9880d681SAndroid Build Coastguard Worker       OS.indent(2) << L->getHeader()->getName() << ":\n";
1987*9880d681SAndroid Build Coastguard Worker       auto &LAI = LAA.getInfo(L);
1988*9880d681SAndroid Build Coastguard Worker       LAI.print(OS, 4);
1989*9880d681SAndroid Build Coastguard Worker     }
1990*9880d681SAndroid Build Coastguard Worker }
1991*9880d681SAndroid Build Coastguard Worker 
runOnFunction(Function & F)1992*9880d681SAndroid Build Coastguard Worker bool LoopAccessLegacyAnalysis::runOnFunction(Function &F) {
1993*9880d681SAndroid Build Coastguard Worker   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1994*9880d681SAndroid Build Coastguard Worker   auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1995*9880d681SAndroid Build Coastguard Worker   TLI = TLIP ? &TLIP->getTLI() : nullptr;
1996*9880d681SAndroid Build Coastguard Worker   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
1997*9880d681SAndroid Build Coastguard Worker   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1998*9880d681SAndroid Build Coastguard Worker   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1999*9880d681SAndroid Build Coastguard Worker 
2000*9880d681SAndroid Build Coastguard Worker   return false;
2001*9880d681SAndroid Build Coastguard Worker }
2002*9880d681SAndroid Build Coastguard Worker 
getAnalysisUsage(AnalysisUsage & AU) const2003*9880d681SAndroid Build Coastguard Worker void LoopAccessLegacyAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
2004*9880d681SAndroid Build Coastguard Worker     AU.addRequired<ScalarEvolutionWrapperPass>();
2005*9880d681SAndroid Build Coastguard Worker     AU.addRequired<AAResultsWrapperPass>();
2006*9880d681SAndroid Build Coastguard Worker     AU.addRequired<DominatorTreeWrapperPass>();
2007*9880d681SAndroid Build Coastguard Worker     AU.addRequired<LoopInfoWrapperPass>();
2008*9880d681SAndroid Build Coastguard Worker 
2009*9880d681SAndroid Build Coastguard Worker     AU.setPreservesAll();
2010*9880d681SAndroid Build Coastguard Worker }
2011*9880d681SAndroid Build Coastguard Worker 
2012*9880d681SAndroid Build Coastguard Worker char LoopAccessLegacyAnalysis::ID = 0;
2013*9880d681SAndroid Build Coastguard Worker static const char laa_name[] = "Loop Access Analysis";
2014*9880d681SAndroid Build Coastguard Worker #define LAA_NAME "loop-accesses"
2015*9880d681SAndroid Build Coastguard Worker 
2016*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_BEGIN(LoopAccessLegacyAnalysis, LAA_NAME, laa_name, false, true)
2017*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
2018*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
2019*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2020*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
2021*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_END(LoopAccessLegacyAnalysis, LAA_NAME, laa_name, false, true)
2022*9880d681SAndroid Build Coastguard Worker 
2023*9880d681SAndroid Build Coastguard Worker char LoopAccessAnalysis::PassID;
2024*9880d681SAndroid Build Coastguard Worker 
run(Loop & L,AnalysisManager<Loop> & AM)2025*9880d681SAndroid Build Coastguard Worker LoopAccessInfo LoopAccessAnalysis::run(Loop &L, AnalysisManager<Loop> &AM) {
2026*9880d681SAndroid Build Coastguard Worker   const AnalysisManager<Function> &FAM =
2027*9880d681SAndroid Build Coastguard Worker       AM.getResult<FunctionAnalysisManagerLoopProxy>(L).getManager();
2028*9880d681SAndroid Build Coastguard Worker   Function &F = *L.getHeader()->getParent();
2029*9880d681SAndroid Build Coastguard Worker   auto *SE = FAM.getCachedResult<ScalarEvolutionAnalysis>(F);
2030*9880d681SAndroid Build Coastguard Worker   auto *TLI = FAM.getCachedResult<TargetLibraryAnalysis>(F);
2031*9880d681SAndroid Build Coastguard Worker   auto *AA = FAM.getCachedResult<AAManager>(F);
2032*9880d681SAndroid Build Coastguard Worker   auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
2033*9880d681SAndroid Build Coastguard Worker   auto *LI = FAM.getCachedResult<LoopAnalysis>(F);
2034*9880d681SAndroid Build Coastguard Worker   if (!SE)
2035*9880d681SAndroid Build Coastguard Worker     report_fatal_error(
2036*9880d681SAndroid Build Coastguard Worker         "ScalarEvolution must have been cached at a higher level");
2037*9880d681SAndroid Build Coastguard Worker   if (!AA)
2038*9880d681SAndroid Build Coastguard Worker     report_fatal_error("AliasAnalysis must have been cached at a higher level");
2039*9880d681SAndroid Build Coastguard Worker   if (!DT)
2040*9880d681SAndroid Build Coastguard Worker     report_fatal_error("DominatorTree must have been cached at a higher level");
2041*9880d681SAndroid Build Coastguard Worker   if (!LI)
2042*9880d681SAndroid Build Coastguard Worker     report_fatal_error("LoopInfo must have been cached at a higher level");
2043*9880d681SAndroid Build Coastguard Worker   return LoopAccessInfo(&L, SE, TLI, AA, DT, LI);
2044*9880d681SAndroid Build Coastguard Worker }
2045*9880d681SAndroid Build Coastguard Worker 
run(Loop & L,AnalysisManager<Loop> & AM)2046*9880d681SAndroid Build Coastguard Worker PreservedAnalyses LoopAccessInfoPrinterPass::run(Loop &L,
2047*9880d681SAndroid Build Coastguard Worker                                                  AnalysisManager<Loop> &AM) {
2048*9880d681SAndroid Build Coastguard Worker   Function &F = *L.getHeader()->getParent();
2049*9880d681SAndroid Build Coastguard Worker   auto &LAI = AM.getResult<LoopAccessAnalysis>(L);
2050*9880d681SAndroid Build Coastguard Worker   OS << "Loop access info in function '" << F.getName() << "':\n";
2051*9880d681SAndroid Build Coastguard Worker   OS.indent(2) << L.getHeader()->getName() << ":\n";
2052*9880d681SAndroid Build Coastguard Worker   LAI.print(OS, 4);
2053*9880d681SAndroid Build Coastguard Worker   return PreservedAnalyses::all();
2054*9880d681SAndroid Build Coastguard Worker }
2055*9880d681SAndroid Build Coastguard Worker 
2056*9880d681SAndroid Build Coastguard Worker namespace llvm {
createLAAPass()2057*9880d681SAndroid Build Coastguard Worker   Pass *createLAAPass() {
2058*9880d681SAndroid Build Coastguard Worker     return new LoopAccessLegacyAnalysis();
2059*9880d681SAndroid Build Coastguard Worker   }
2060*9880d681SAndroid Build Coastguard Worker }
2061