1 //===- LoopAccessAnalysis.cpp - Loop Access Analysis Implementation --------==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // The implementation for the loop memory dependence that was originally
11 // developed for the loop vectorizer.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Analysis/LoopAccessAnalysis.h"
16 #include "llvm/Analysis/LoopInfo.h"
17 #include "llvm/Analysis/ScalarEvolutionExpander.h"
18 #include "llvm/Analysis/TargetLibraryInfo.h"
19 #include "llvm/Analysis/ValueTracking.h"
20 #include "llvm/IR/DiagnosticInfo.h"
21 #include "llvm/IR/Dominators.h"
22 #include "llvm/IR/IRBuilder.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/Transforms/Utils/VectorUtils.h"
28 #define DEBUG_TYPE "loop-accesses"
30 static cl::opt<unsigned, true>
31 VectorizationFactor("force-vector-width", cl::Hidden,
32 cl::desc("Sets the SIMD width. Zero is autoselect."),
33 cl::location(VectorizerParams::VectorizationFactor));
34 unsigned VectorizerParams::VectorizationFactor;
36 static cl::opt<unsigned, true>
37 VectorizationInterleave("force-vector-interleave", cl::Hidden,
38 cl::desc("Sets the vectorization interleave count. "
39 "Zero is autoselect."),
41 VectorizerParams::VectorizationInterleave));
42 unsigned VectorizerParams::VectorizationInterleave;
44 static cl::opt<unsigned, true> RuntimeMemoryCheckThreshold(
45 "runtime-memory-check-threshold", cl::Hidden,
46 cl::desc("When performing memory disambiguation checks at runtime do not "
47 "generate more than this number of comparisons (default = 8)."),
48 cl::location(VectorizerParams::RuntimeMemoryCheckThreshold), cl::init(8));
49 unsigned VectorizerParams::RuntimeMemoryCheckThreshold;
51 /// Maximum SIMD width.
52 const unsigned VectorizerParams::MaxVectorWidth = 64;
54 /// \brief We collect interesting dependences up to this threshold.
55 static cl::opt<unsigned> MaxInterestingDependence(
56 "max-interesting-dependences", cl::Hidden,
57 cl::desc("Maximum number of interesting dependences collected by "
58 "loop-access analysis (default = 100)"),
61 bool VectorizerParams::isInterleaveForced() {
62 return ::VectorizationInterleave.getNumOccurrences() > 0;
65 void LoopAccessReport::emitAnalysis(const LoopAccessReport &Message,
66 const Function *TheFunction,
68 const char *PassName) {
69 DebugLoc DL = TheLoop->getStartLoc();
70 if (const Instruction *I = Message.getInstr())
71 DL = I->getDebugLoc();
72 emitOptimizationRemarkAnalysis(TheFunction->getContext(), PassName,
73 *TheFunction, DL, Message.str());
76 Value *llvm::stripIntegerCast(Value *V) {
77 if (CastInst *CI = dyn_cast<CastInst>(V))
78 if (CI->getOperand(0)->getType()->isIntegerTy())
79 return CI->getOperand(0);
83 const SCEV *llvm::replaceSymbolicStrideSCEV(ScalarEvolution *SE,
84 const ValueToValueMap &PtrToStride,
85 Value *Ptr, Value *OrigPtr) {
87 const SCEV *OrigSCEV = SE->getSCEV(Ptr);
89 // If there is an entry in the map return the SCEV of the pointer with the
90 // symbolic stride replaced by one.
91 ValueToValueMap::const_iterator SI =
92 PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
93 if (SI != PtrToStride.end()) {
94 Value *StrideVal = SI->second;
97 StrideVal = stripIntegerCast(StrideVal);
99 // Replace symbolic stride by one.
100 Value *One = ConstantInt::get(StrideVal->getType(), 1);
101 ValueToValueMap RewriteMap;
102 RewriteMap[StrideVal] = One;
105 SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
106 DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
111 // Otherwise, just return the SCEV of the original pointer.
112 return SE->getSCEV(Ptr);
115 void LoopAccessInfo::RuntimePointerCheck::insert(
116 ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId,
117 unsigned ASId, const ValueToValueMap &Strides) {
118 // Get the stride replaced scev.
119 const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
120 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
121 assert(AR && "Invalid addrec expression");
122 const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
123 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
124 Pointers.push_back(Ptr);
125 Starts.push_back(AR->getStart());
126 Ends.push_back(ScEnd);
127 IsWritePtr.push_back(WritePtr);
128 DependencySetId.push_back(DepSetId);
129 AliasSetId.push_back(ASId);
132 bool LoopAccessInfo::RuntimePointerCheck::needsChecking(
133 unsigned I, unsigned J, const SmallVectorImpl<int> *PtrPartition) const {
134 // No need to check if two readonly pointers intersect.
135 if (!IsWritePtr[I] && !IsWritePtr[J])
138 // Only need to check pointers between two different dependency sets.
139 if (DependencySetId[I] == DependencySetId[J])
142 // Only need to check pointers in the same alias set.
143 if (AliasSetId[I] != AliasSetId[J])
146 // If PtrPartition is set omit checks between pointers of the same partition.
147 // Partition number -1 means that the pointer is used in multiple partitions.
148 // In this case we can't omit the check.
149 if (PtrPartition && (*PtrPartition)[I] != -1 &&
150 (*PtrPartition)[I] == (*PtrPartition)[J])
156 void LoopAccessInfo::RuntimePointerCheck::print(
157 raw_ostream &OS, unsigned Depth,
158 const SmallVectorImpl<int> *PtrPartition) const {
159 unsigned NumPointers = Pointers.size();
160 if (NumPointers == 0)
163 OS.indent(Depth) << "Run-time memory checks:\n";
165 for (unsigned I = 0; I < NumPointers; ++I)
166 for (unsigned J = I + 1; J < NumPointers; ++J)
167 if (needsChecking(I, J, PtrPartition)) {
168 OS.indent(Depth) << N++ << ":\n";
169 OS.indent(Depth + 2) << *Pointers[I];
171 OS << " (Partition: " << (*PtrPartition)[I] << ")";
173 OS.indent(Depth + 2) << *Pointers[J];
175 OS << " (Partition: " << (*PtrPartition)[J] << ")";
181 /// \brief Analyses memory accesses in a loop.
183 /// Checks whether run time pointer checks are needed and builds sets for data
184 /// dependence checking.
185 class AccessAnalysis {
187 /// \brief Read or write access location.
188 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
189 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
191 AccessAnalysis(const DataLayout &Dl, AliasAnalysis *AA,
192 MemoryDepChecker::DepCandidates &DA)
193 : DL(Dl), AST(*AA), DepCands(DA), IsRTCheckNeeded(false) {}
195 /// \brief Register a load and whether it is only read from.
196 void addLoad(AliasAnalysis::Location &Loc, bool IsReadOnly) {
197 Value *Ptr = const_cast<Value*>(Loc.Ptr);
198 AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
199 Accesses.insert(MemAccessInfo(Ptr, false));
201 ReadOnlyPtr.insert(Ptr);
204 /// \brief Register a store.
205 void addStore(AliasAnalysis::Location &Loc) {
206 Value *Ptr = const_cast<Value*>(Loc.Ptr);
207 AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
208 Accesses.insert(MemAccessInfo(Ptr, true));
211 /// \brief Check whether we can check the pointers at runtime for
212 /// non-intersection.
213 bool canCheckPtrAtRT(LoopAccessInfo::RuntimePointerCheck &RtCheck,
214 unsigned &NumComparisons, ScalarEvolution *SE,
215 Loop *TheLoop, const ValueToValueMap &Strides,
216 bool ShouldCheckStride = false);
218 /// \brief Goes over all memory accesses, checks whether a RT check is needed
219 /// and builds sets of dependent accesses.
220 void buildDependenceSets() {
221 processMemAccesses();
224 bool isRTCheckNeeded() { return IsRTCheckNeeded; }
226 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
227 void resetDepChecks() { CheckDeps.clear(); }
229 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
232 typedef SetVector<MemAccessInfo> PtrAccessSet;
234 /// \brief Go over all memory access and check whether runtime pointer checks
235 /// are needed /// and build sets of dependency check candidates.
236 void processMemAccesses();
238 /// Set of all accesses.
239 PtrAccessSet Accesses;
241 const DataLayout &DL;
243 /// Set of accesses that need a further dependence check.
244 MemAccessInfoSet CheckDeps;
246 /// Set of pointers that are read only.
247 SmallPtrSet<Value*, 16> ReadOnlyPtr;
249 /// An alias set tracker to partition the access set by underlying object and
250 //intrinsic property (such as TBAA metadata).
253 /// Sets of potentially dependent accesses - members of one set share an
254 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
255 /// dependence check.
256 MemoryDepChecker::DepCandidates &DepCands;
258 bool IsRTCheckNeeded;
261 } // end anonymous namespace
263 /// \brief Check whether a pointer can participate in a runtime bounds check.
264 static bool hasComputableBounds(ScalarEvolution *SE,
265 const ValueToValueMap &Strides, Value *Ptr) {
266 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
267 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
271 return AR->isAffine();
274 /// \brief Check the stride of the pointer and ensure that it does not wrap in
275 /// the address space.
276 static int isStridedPtr(ScalarEvolution *SE, Value *Ptr, const Loop *Lp,
277 const ValueToValueMap &StridesMap);
279 bool AccessAnalysis::canCheckPtrAtRT(
280 LoopAccessInfo::RuntimePointerCheck &RtCheck, unsigned &NumComparisons,
281 ScalarEvolution *SE, Loop *TheLoop, const ValueToValueMap &StridesMap,
282 bool ShouldCheckStride) {
283 // Find pointers with computable bounds. We are going to use this information
284 // to place a runtime bound check.
287 bool IsDepCheckNeeded = isDependencyCheckNeeded();
290 // We assign a consecutive id to access from different alias sets.
291 // Accesses between different groups doesn't need to be checked.
293 for (auto &AS : AST) {
294 unsigned NumReadPtrChecks = 0;
295 unsigned NumWritePtrChecks = 0;
297 // We assign consecutive id to access from different dependence sets.
298 // Accesses within the same set don't need a runtime check.
299 unsigned RunningDepId = 1;
300 DenseMap<Value *, unsigned> DepSetId;
303 Value *Ptr = A.getValue();
304 bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
305 MemAccessInfo Access(Ptr, IsWrite);
312 if (hasComputableBounds(SE, StridesMap, Ptr) &&
313 // When we run after a failing dependency check we have to make sure
314 // we don't have wrapping pointers.
315 (!ShouldCheckStride ||
316 isStridedPtr(SE, Ptr, TheLoop, StridesMap) == 1)) {
317 // The id of the dependence set.
320 if (IsDepCheckNeeded) {
321 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
322 unsigned &LeaderId = DepSetId[Leader];
324 LeaderId = RunningDepId++;
327 // Each access has its own dependence set.
328 DepId = RunningDepId++;
330 RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap);
332 DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
338 if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
339 NumComparisons += 0; // Only one dependence set.
341 NumComparisons += (NumWritePtrChecks * (NumReadPtrChecks +
342 NumWritePtrChecks - 1));
348 // If the pointers that we would use for the bounds comparison have different
349 // address spaces, assume the values aren't directly comparable, so we can't
350 // use them for the runtime check. We also have to assume they could
351 // overlap. In the future there should be metadata for whether address spaces
353 unsigned NumPointers = RtCheck.Pointers.size();
354 for (unsigned i = 0; i < NumPointers; ++i) {
355 for (unsigned j = i + 1; j < NumPointers; ++j) {
356 // Only need to check pointers between two different dependency sets.
357 if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
359 // Only need to check pointers in the same alias set.
360 if (RtCheck.AliasSetId[i] != RtCheck.AliasSetId[j])
363 Value *PtrI = RtCheck.Pointers[i];
364 Value *PtrJ = RtCheck.Pointers[j];
366 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
367 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
369 DEBUG(dbgs() << "LAA: Runtime check would require comparison between"
370 " different address spaces\n");
379 void AccessAnalysis::processMemAccesses() {
380 // We process the set twice: first we process read-write pointers, last we
381 // process read-only pointers. This allows us to skip dependence tests for
382 // read-only pointers.
384 DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
385 DEBUG(dbgs() << " AST: "; AST.dump());
386 DEBUG(dbgs() << "LAA: Accesses(" << Accesses.size() << "):\n");
388 for (auto A : Accesses)
389 dbgs() << "\t" << *A.getPointer() << " (" <<
390 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
391 "read-only" : "read")) << ")\n";
394 // The AliasSetTracker has nicely partitioned our pointers by metadata
395 // compatibility and potential for underlying-object overlap. As a result, we
396 // only need to check for potential pointer dependencies within each alias
398 for (auto &AS : AST) {
399 // Note that both the alias-set tracker and the alias sets themselves used
400 // linked lists internally and so the iteration order here is deterministic
401 // (matching the original instruction order within each set).
403 bool SetHasWrite = false;
405 // Map of pointers to last access encountered.
406 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
407 UnderlyingObjToAccessMap ObjToLastAccess;
409 // Set of access to check after all writes have been processed.
410 PtrAccessSet DeferredAccesses;
412 // Iterate over each alias set twice, once to process read/write pointers,
413 // and then to process read-only pointers.
414 for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
415 bool UseDeferred = SetIteration > 0;
416 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
419 Value *Ptr = AV.getValue();
421 // For a single memory access in AliasSetTracker, Accesses may contain
422 // both read and write, and they both need to be handled for CheckDeps.
424 if (AC.getPointer() != Ptr)
427 bool IsWrite = AC.getInt();
429 // If we're using the deferred access set, then it contains only
431 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
432 if (UseDeferred && !IsReadOnlyPtr)
434 // Otherwise, the pointer must be in the PtrAccessSet, either as a
436 assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
437 S.count(MemAccessInfo(Ptr, false))) &&
438 "Alias-set pointer not in the access set?");
440 MemAccessInfo Access(Ptr, IsWrite);
441 DepCands.insert(Access);
443 // Memorize read-only pointers for later processing and skip them in
444 // the first round (they need to be checked after we have seen all
445 // write pointers). Note: we also mark pointer that are not
446 // consecutive as "read-only" pointers (so that we check
447 // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
448 if (!UseDeferred && IsReadOnlyPtr) {
449 DeferredAccesses.insert(Access);
453 // If this is a write - check other reads and writes for conflicts. If
454 // this is a read only check other writes for conflicts (but only if
455 // there is no other write to the ptr - this is an optimization to
456 // catch "a[i] = a[i] + " without having to do a dependence check).
457 if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
458 CheckDeps.insert(Access);
459 IsRTCheckNeeded = true;
465 // Create sets of pointers connected by a shared alias set and
466 // underlying object.
467 typedef SmallVector<Value *, 16> ValueVector;
468 ValueVector TempObjects;
469 GetUnderlyingObjects(Ptr, TempObjects, DL);
470 for (Value *UnderlyingObj : TempObjects) {
471 UnderlyingObjToAccessMap::iterator Prev =
472 ObjToLastAccess.find(UnderlyingObj);
473 if (Prev != ObjToLastAccess.end())
474 DepCands.unionSets(Access, Prev->second);
476 ObjToLastAccess[UnderlyingObj] = Access;
484 static bool isInBoundsGep(Value *Ptr) {
485 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
486 return GEP->isInBounds();
490 /// \brief Check whether the access through \p Ptr has a constant stride.
491 static int isStridedPtr(ScalarEvolution *SE, Value *Ptr, const Loop *Lp,
492 const ValueToValueMap &StridesMap) {
493 const Type *Ty = Ptr->getType();
494 assert(Ty->isPointerTy() && "Unexpected non-ptr");
496 // Make sure that the pointer does not point to aggregate types.
497 const PointerType *PtrTy = cast<PointerType>(Ty);
498 if (PtrTy->getElementType()->isAggregateType()) {
499 DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type"
504 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
506 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
508 DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer "
509 << *Ptr << " SCEV: " << *PtrScev << "\n");
513 // The accesss function must stride over the innermost loop.
514 if (Lp != AR->getLoop()) {
515 DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " <<
516 *Ptr << " SCEV: " << *PtrScev << "\n");
519 // The address calculation must not wrap. Otherwise, a dependence could be
521 // An inbounds getelementptr that is a AddRec with a unit stride
522 // cannot wrap per definition. The unit stride requirement is checked later.
523 // An getelementptr without an inbounds attribute and unit stride would have
524 // to access the pointer value "0" which is undefined behavior in address
525 // space 0, therefore we can also vectorize this case.
526 bool IsInBoundsGEP = isInBoundsGep(Ptr);
527 bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
528 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
529 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
530 DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
531 << *Ptr << " SCEV: " << *PtrScev << "\n");
535 // Check the step is constant.
536 const SCEV *Step = AR->getStepRecurrence(*SE);
538 // Calculate the pointer stride and check if it is consecutive.
539 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
541 DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr <<
542 " SCEV: " << *PtrScev << "\n");
546 auto &DL = Lp->getHeader()->getModule()->getDataLayout();
547 int64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
548 const APInt &APStepVal = C->getValue()->getValue();
550 // Huge step value - give up.
551 if (APStepVal.getBitWidth() > 64)
554 int64_t StepVal = APStepVal.getSExtValue();
557 int64_t Stride = StepVal / Size;
558 int64_t Rem = StepVal % Size;
562 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
563 // know we can't "wrap around the address space". In case of address space
564 // zero we know that this won't happen without triggering undefined behavior.
565 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
566 Stride != 1 && Stride != -1)
572 bool MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
576 case BackwardVectorizable:
580 case ForwardButPreventsForwarding:
582 case BackwardVectorizableButPreventsForwarding:
585 llvm_unreachable("unexpected DepType!");
588 bool MemoryDepChecker::Dependence::isInterestingDependence(DepType Type) {
594 case BackwardVectorizable:
596 case ForwardButPreventsForwarding:
598 case BackwardVectorizableButPreventsForwarding:
601 llvm_unreachable("unexpected DepType!");
604 bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
608 case ForwardButPreventsForwarding:
612 case BackwardVectorizable:
614 case BackwardVectorizableButPreventsForwarding:
617 llvm_unreachable("unexpected DepType!");
620 bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
621 unsigned TypeByteSize) {
622 // If loads occur at a distance that is not a multiple of a feasible vector
623 // factor store-load forwarding does not take place.
624 // Positive dependences might cause troubles because vectorizing them might
625 // prevent store-load forwarding making vectorized code run a lot slower.
626 // a[i] = a[i-3] ^ a[i-8];
627 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
628 // hence on your typical architecture store-load forwarding does not take
629 // place. Vectorizing in such cases does not make sense.
630 // Store-load forwarding distance.
631 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
632 // Maximum vector factor.
633 unsigned MaxVFWithoutSLForwardIssues =
634 VectorizerParams::MaxVectorWidth * TypeByteSize;
635 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
636 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
638 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
640 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
641 MaxVFWithoutSLForwardIssues = (vf >>=1);
646 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
647 DEBUG(dbgs() << "LAA: Distance " << Distance <<
648 " that could cause a store-load forwarding conflict\n");
652 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
653 MaxVFWithoutSLForwardIssues !=
654 VectorizerParams::MaxVectorWidth * TypeByteSize)
655 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
659 MemoryDepChecker::Dependence::DepType
660 MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
661 const MemAccessInfo &B, unsigned BIdx,
662 const ValueToValueMap &Strides) {
663 assert (AIdx < BIdx && "Must pass arguments in program order");
665 Value *APtr = A.getPointer();
666 Value *BPtr = B.getPointer();
667 bool AIsWrite = A.getInt();
668 bool BIsWrite = B.getInt();
670 // Two reads are independent.
671 if (!AIsWrite && !BIsWrite)
672 return Dependence::NoDep;
674 // We cannot check pointers in different address spaces.
675 if (APtr->getType()->getPointerAddressSpace() !=
676 BPtr->getType()->getPointerAddressSpace())
677 return Dependence::Unknown;
679 const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
680 const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
682 int StrideAPtr = isStridedPtr(SE, APtr, InnermostLoop, Strides);
683 int StrideBPtr = isStridedPtr(SE, BPtr, InnermostLoop, Strides);
685 const SCEV *Src = AScev;
686 const SCEV *Sink = BScev;
688 // If the induction step is negative we have to invert source and sink of the
690 if (StrideAPtr < 0) {
693 std::swap(APtr, BPtr);
694 std::swap(Src, Sink);
695 std::swap(AIsWrite, BIsWrite);
696 std::swap(AIdx, BIdx);
697 std::swap(StrideAPtr, StrideBPtr);
700 const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
702 DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
703 << "(Induction step: " << StrideAPtr << ")\n");
704 DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
705 << *InstMap[BIdx] << ": " << *Dist << "\n");
707 // Need consecutive accesses. We don't want to vectorize
708 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
709 // the address space.
710 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
711 DEBUG(dbgs() << "Non-consecutive pointer access\n");
712 return Dependence::Unknown;
715 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
717 DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
718 ShouldRetryWithRuntimeCheck = true;
719 return Dependence::Unknown;
722 Type *ATy = APtr->getType()->getPointerElementType();
723 Type *BTy = BPtr->getType()->getPointerElementType();
724 auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
725 unsigned TypeByteSize = DL.getTypeAllocSize(ATy);
727 // Negative distances are not plausible dependencies.
728 const APInt &Val = C->getValue()->getValue();
729 if (Val.isNegative()) {
730 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
731 if (IsTrueDataDependence &&
732 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
734 return Dependence::ForwardButPreventsForwarding;
736 DEBUG(dbgs() << "LAA: Dependence is negative: NoDep\n");
737 return Dependence::Forward;
740 // Write to the same location with the same size.
741 // Could be improved to assert type sizes are the same (i32 == float, etc).
744 return Dependence::NoDep;
745 DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n");
746 return Dependence::Unknown;
749 assert(Val.isStrictlyPositive() && "Expect a positive value");
753 "LAA: ReadWrite-Write positive dependency with different types\n");
754 return Dependence::Unknown;
757 unsigned Distance = (unsigned) Val.getZExtValue();
759 // Bail out early if passed-in parameters make vectorization not feasible.
760 unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
761 VectorizerParams::VectorizationFactor : 1);
762 unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
763 VectorizerParams::VectorizationInterleave : 1);
765 // The distance must be bigger than the size needed for a vectorized version
766 // of the operation and the size of the vectorized operation must not be
767 // bigger than the currrent maximum size.
768 if (Distance < 2*TypeByteSize ||
769 2*TypeByteSize > MaxSafeDepDistBytes ||
770 Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
771 DEBUG(dbgs() << "LAA: Failure because of Positive distance "
772 << Val.getSExtValue() << '\n');
773 return Dependence::Backward;
776 // Positive distance bigger than max vectorization factor.
777 MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
778 Distance : MaxSafeDepDistBytes;
780 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
781 if (IsTrueDataDependence &&
782 couldPreventStoreLoadForward(Distance, TypeByteSize))
783 return Dependence::BackwardVectorizableButPreventsForwarding;
785 DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue() <<
786 " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n');
788 return Dependence::BackwardVectorizable;
791 bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets,
792 MemAccessInfoSet &CheckDeps,
793 const ValueToValueMap &Strides) {
795 MaxSafeDepDistBytes = -1U;
796 while (!CheckDeps.empty()) {
797 MemAccessInfo CurAccess = *CheckDeps.begin();
799 // Get the relevant memory access set.
800 EquivalenceClasses<MemAccessInfo>::iterator I =
801 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
803 // Check accesses within this set.
804 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
805 AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
807 // Check every access pair.
809 CheckDeps.erase(*AI);
810 EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
812 // Check every accessing instruction pair in program order.
813 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
814 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
815 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
816 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
817 auto A = std::make_pair(&*AI, *I1);
818 auto B = std::make_pair(&*OI, *I2);
824 Dependence::DepType Type =
825 isDependent(*A.first, A.second, *B.first, B.second, Strides);
826 SafeForVectorization &= Dependence::isSafeForVectorization(Type);
828 // Gather dependences unless we accumulated MaxInterestingDependence
829 // dependences. In that case return as soon as we find the first
830 // unsafe dependence. This puts a limit on this quadratic
832 if (RecordInterestingDependences) {
833 if (Dependence::isInterestingDependence(Type))
834 InterestingDependences.push_back(
835 Dependence(A.second, B.second, Type));
837 if (InterestingDependences.size() >= MaxInterestingDependence) {
838 RecordInterestingDependences = false;
839 InterestingDependences.clear();
840 DEBUG(dbgs() << "Too many dependences, stopped recording\n");
843 if (!RecordInterestingDependences && !SafeForVectorization)
852 DEBUG(dbgs() << "Total Interesting Dependences: "
853 << InterestingDependences.size() << "\n");
854 return SafeForVectorization;
857 SmallVector<Instruction *, 4>
858 MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const {
859 MemAccessInfo Access(Ptr, isWrite);
860 auto &IndexVector = Accesses.find(Access)->second;
862 SmallVector<Instruction *, 4> Insts;
863 std::transform(IndexVector.begin(), IndexVector.end(),
864 std::back_inserter(Insts),
865 [&](unsigned Idx) { return this->InstMap[Idx]; });
869 const char *MemoryDepChecker::Dependence::DepName[] = {
870 "NoDep", "Unknown", "Forward", "ForwardButPreventsForwarding", "Backward",
871 "BackwardVectorizable", "BackwardVectorizableButPreventsForwarding"};
873 void MemoryDepChecker::Dependence::print(
874 raw_ostream &OS, unsigned Depth,
875 const SmallVectorImpl<Instruction *> &Instrs) const {
876 OS.indent(Depth) << DepName[Type] << ":\n";
877 OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
878 OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
881 bool LoopAccessInfo::canAnalyzeLoop() {
882 // We can only analyze innermost loops.
883 if (!TheLoop->empty()) {
884 emitAnalysis(LoopAccessReport() << "loop is not the innermost loop");
888 // We must have a single backedge.
889 if (TheLoop->getNumBackEdges() != 1) {
891 LoopAccessReport() <<
892 "loop control flow is not understood by analyzer");
896 // We must have a single exiting block.
897 if (!TheLoop->getExitingBlock()) {
899 LoopAccessReport() <<
900 "loop control flow is not understood by analyzer");
904 // We only handle bottom-tested loops, i.e. loop in which the condition is
905 // checked at the end of each iteration. With that we can assume that all
906 // instructions in the loop are executed the same number of times.
907 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
909 LoopAccessReport() <<
910 "loop control flow is not understood by analyzer");
914 // We need to have a loop header.
915 DEBUG(dbgs() << "LAA: Found a loop: " <<
916 TheLoop->getHeader()->getName() << '\n');
918 // ScalarEvolution needs to be able to find the exit count.
919 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
920 if (ExitCount == SE->getCouldNotCompute()) {
921 emitAnalysis(LoopAccessReport() <<
922 "could not determine number of loop iterations");
923 DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
930 void LoopAccessInfo::analyzeLoop(const ValueToValueMap &Strides) {
932 typedef SmallVector<Value*, 16> ValueVector;
933 typedef SmallPtrSet<Value*, 16> ValueSet;
935 // Holds the Load and Store *instructions*.
939 // Holds all the different accesses in the loop.
940 unsigned NumReads = 0;
941 unsigned NumReadWrites = 0;
943 PtrRtCheck.Pointers.clear();
944 PtrRtCheck.Need = false;
946 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
949 for (Loop::block_iterator bb = TheLoop->block_begin(),
950 be = TheLoop->block_end(); bb != be; ++bb) {
952 // Scan the BB and collect legal loads and stores.
953 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
956 // If this is a load, save it. If this instruction can read from memory
957 // but is not a load, then we quit. Notice that we don't handle function
958 // calls that read or write.
959 if (it->mayReadFromMemory()) {
960 // Many math library functions read the rounding mode. We will only
961 // vectorize a loop if it contains known function calls that don't set
962 // the flag. Therefore, it is safe to ignore this read from memory.
963 CallInst *Call = dyn_cast<CallInst>(it);
964 if (Call && getIntrinsicIDForCall(Call, TLI))
967 // If the function has an explicit vectorized counterpart, we can safely
968 // assume that it can be vectorized.
969 if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
970 TLI->isFunctionVectorizable(Call->getCalledFunction()->getName()))
973 LoadInst *Ld = dyn_cast<LoadInst>(it);
974 if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
975 emitAnalysis(LoopAccessReport(Ld)
976 << "read with atomic ordering or volatile read");
977 DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
983 DepChecker.addAccess(Ld);
987 // Save 'store' instructions. Abort if other instructions write to memory.
988 if (it->mayWriteToMemory()) {
989 StoreInst *St = dyn_cast<StoreInst>(it);
991 emitAnalysis(LoopAccessReport(it) <<
992 "instruction cannot be vectorized");
996 if (!St->isSimple() && !IsAnnotatedParallel) {
997 emitAnalysis(LoopAccessReport(St)
998 << "write with atomic ordering or volatile write");
999 DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
1004 Stores.push_back(St);
1005 DepChecker.addAccess(St);
1010 // Now we have two lists that hold the loads and the stores.
1011 // Next, we find the pointers that they use.
1013 // Check if we see any stores. If there are no stores, then we don't
1014 // care if the pointers are *restrict*.
1015 if (!Stores.size()) {
1016 DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
1021 MemoryDepChecker::DepCandidates DependentAccesses;
1022 AccessAnalysis Accesses(TheLoop->getHeader()->getModule()->getDataLayout(),
1023 AA, DependentAccesses);
1025 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1026 // multiple times on the same object. If the ptr is accessed twice, once
1027 // for read and once for write, it will only appear once (on the write
1028 // list). This is okay, since we are going to check for conflicts between
1029 // writes and between reads and writes, but not between reads and reads.
1032 ValueVector::iterator I, IE;
1033 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1034 StoreInst *ST = cast<StoreInst>(*I);
1035 Value* Ptr = ST->getPointerOperand();
1037 if (isUniform(Ptr)) {
1039 LoopAccessReport(ST)
1040 << "write to a loop invariant address could not be vectorized");
1041 DEBUG(dbgs() << "LAA: We don't allow storing to uniform addresses\n");
1046 // If we did *not* see this pointer before, insert it to the read-write
1047 // list. At this phase it is only a 'write' list.
1048 if (Seen.insert(Ptr).second) {
1051 AliasAnalysis::Location Loc = AA->getLocation(ST);
1052 // The TBAA metadata could have a control dependency on the predication
1053 // condition, so we cannot rely on it when determining whether or not we
1054 // need runtime pointer checks.
1055 if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
1056 Loc.AATags.TBAA = nullptr;
1058 Accesses.addStore(Loc);
1062 if (IsAnnotatedParallel) {
1064 << "LAA: A loop annotated parallel, ignore memory dependency "
1070 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1071 LoadInst *LD = cast<LoadInst>(*I);
1072 Value* Ptr = LD->getPointerOperand();
1073 // If we did *not* see this pointer before, insert it to the
1074 // read list. If we *did* see it before, then it is already in
1075 // the read-write list. This allows us to vectorize expressions
1076 // such as A[i] += x; Because the address of A[i] is a read-write
1077 // pointer. This only works if the index of A[i] is consecutive.
1078 // If the address of i is unknown (for example A[B[i]]) then we may
1079 // read a few words, modify, and write a few words, and some of the
1080 // words may be written to the same address.
1081 bool IsReadOnlyPtr = false;
1082 if (Seen.insert(Ptr).second || !isStridedPtr(SE, Ptr, TheLoop, Strides)) {
1084 IsReadOnlyPtr = true;
1087 AliasAnalysis::Location Loc = AA->getLocation(LD);
1088 // The TBAA metadata could have a control dependency on the predication
1089 // condition, so we cannot rely on it when determining whether or not we
1090 // need runtime pointer checks.
1091 if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
1092 Loc.AATags.TBAA = nullptr;
1094 Accesses.addLoad(Loc, IsReadOnlyPtr);
1097 // If we write (or read-write) to a single destination and there are no
1098 // other reads in this loop then is it safe to vectorize.
1099 if (NumReadWrites == 1 && NumReads == 0) {
1100 DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
1105 // Build dependence sets and check whether we need a runtime pointer bounds
1107 Accesses.buildDependenceSets();
1108 bool NeedRTCheck = Accesses.isRTCheckNeeded();
1110 // Find pointers with computable bounds. We are going to use this information
1111 // to place a runtime bound check.
1112 bool CanDoRT = false;
1114 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop,
1117 DEBUG(dbgs() << "LAA: We need to do " << NumComparisons <<
1118 " pointer comparisons.\n");
1120 // If we only have one set of dependences to check pointers among we don't
1121 // need a runtime check.
1122 if (NumComparisons == 0 && NeedRTCheck)
1123 NeedRTCheck = false;
1125 // Check that we found the bounds for the pointer.
1127 DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
1128 else if (NeedRTCheck) {
1129 emitAnalysis(LoopAccessReport() << "cannot identify array bounds");
1130 DEBUG(dbgs() << "LAA: We can't vectorize because we can't find " <<
1131 "the array bounds.\n");
1137 PtrRtCheck.Need = NeedRTCheck;
1140 if (Accesses.isDependencyCheckNeeded()) {
1141 DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
1142 CanVecMem = DepChecker.areDepsSafe(
1143 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
1144 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
1146 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
1147 DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
1150 // Clear the dependency checks. We assume they are not needed.
1151 Accesses.resetDepChecks();
1154 PtrRtCheck.Need = true;
1156 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE,
1157 TheLoop, Strides, true);
1158 // Check that we found the bounds for the pointer.
1159 if (!CanDoRT && NumComparisons > 0) {
1160 emitAnalysis(LoopAccessReport()
1161 << "cannot check memory dependencies at runtime");
1162 DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
1173 DEBUG(dbgs() << "LAA: No unsafe dependent memory operations in loop. We"
1174 << (NeedRTCheck ? "" : " don't")
1175 << " need a runtime memory check.\n");
1177 emitAnalysis(LoopAccessReport() <<
1178 "unsafe dependent memory operations in loop");
1179 DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
1183 bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
1184 DominatorTree *DT) {
1185 assert(TheLoop->contains(BB) && "Unknown block used");
1187 // Blocks that do not dominate the latch need predication.
1188 BasicBlock* Latch = TheLoop->getLoopLatch();
1189 return !DT->dominates(BB, Latch);
1192 void LoopAccessInfo::emitAnalysis(LoopAccessReport &Message) {
1193 assert(!Report && "Multiple reports generated");
1197 bool LoopAccessInfo::isUniform(Value *V) const {
1198 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1201 // FIXME: this function is currently a duplicate of the one in
1202 // LoopVectorize.cpp.
1203 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1207 if (Instruction *I = dyn_cast<Instruction>(V))
1208 return I->getParent() == Loc->getParent() ? I : nullptr;
1212 std::pair<Instruction *, Instruction *> LoopAccessInfo::addRuntimeCheck(
1213 Instruction *Loc, const SmallVectorImpl<int> *PtrPartition) const {
1214 if (!PtrRtCheck.Need)
1215 return std::make_pair(nullptr, nullptr);
1217 unsigned NumPointers = PtrRtCheck.Pointers.size();
1218 SmallVector<TrackingVH<Value> , 2> Starts;
1219 SmallVector<TrackingVH<Value> , 2> Ends;
1221 LLVMContext &Ctx = Loc->getContext();
1222 SCEVExpander Exp(*SE, DL, "induction");
1223 Instruction *FirstInst = nullptr;
1225 for (unsigned i = 0; i < NumPointers; ++i) {
1226 Value *Ptr = PtrRtCheck.Pointers[i];
1227 const SCEV *Sc = SE->getSCEV(Ptr);
1229 if (SE->isLoopInvariant(Sc, TheLoop)) {
1230 DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" <<
1232 Starts.push_back(Ptr);
1233 Ends.push_back(Ptr);
1235 DEBUG(dbgs() << "LAA: Adding RT check for range:" << *Ptr << '\n');
1236 unsigned AS = Ptr->getType()->getPointerAddressSpace();
1238 // Use this type for pointer arithmetic.
1239 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1241 Value *Start = Exp.expandCodeFor(PtrRtCheck.Starts[i], PtrArithTy, Loc);
1242 Value *End = Exp.expandCodeFor(PtrRtCheck.Ends[i], PtrArithTy, Loc);
1243 Starts.push_back(Start);
1244 Ends.push_back(End);
1248 IRBuilder<> ChkBuilder(Loc);
1249 // Our instructions might fold to a constant.
1250 Value *MemoryRuntimeCheck = nullptr;
1251 for (unsigned i = 0; i < NumPointers; ++i) {
1252 for (unsigned j = i+1; j < NumPointers; ++j) {
1253 if (!PtrRtCheck.needsChecking(i, j, PtrPartition))
1256 unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
1257 unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
1259 assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
1260 (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
1261 "Trying to bounds check pointers with different address spaces");
1263 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1264 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
1266 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
1267 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
1268 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc");
1269 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc");
1271 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1272 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1273 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1274 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1275 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1276 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1277 if (MemoryRuntimeCheck) {
1278 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1280 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1282 MemoryRuntimeCheck = IsConflict;
1286 if (!MemoryRuntimeCheck)
1287 return std::make_pair(nullptr, nullptr);
1289 // We have to do this trickery because the IRBuilder might fold the check to a
1290 // constant expression in which case there is no Instruction anchored in a
1292 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1293 ConstantInt::getTrue(Ctx));
1294 ChkBuilder.Insert(Check, "memcheck.conflict");
1295 FirstInst = getFirstInst(FirstInst, Check, Loc);
1296 return std::make_pair(FirstInst, Check);
1299 LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
1300 const DataLayout &DL,
1301 const TargetLibraryInfo *TLI, AliasAnalysis *AA,
1303 const ValueToValueMap &Strides)
1304 : DepChecker(SE, L), NumComparisons(0), TheLoop(L), SE(SE), DL(DL),
1305 TLI(TLI), AA(AA), DT(DT), NumLoads(0), NumStores(0),
1306 MaxSafeDepDistBytes(-1U), CanVecMem(false) {
1307 if (canAnalyzeLoop())
1308 analyzeLoop(Strides);
1311 void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
1313 if (PtrRtCheck.empty())
1314 OS.indent(Depth) << "Memory dependences are safe\n";
1316 OS.indent(Depth) << "Memory dependences are safe with run-time checks\n";
1320 OS.indent(Depth) << "Report: " << Report->str() << "\n";
1322 if (auto *InterestingDependences = DepChecker.getInterestingDependences()) {
1323 OS.indent(Depth) << "Interesting Dependences:\n";
1324 for (auto &Dep : *InterestingDependences) {
1325 Dep.print(OS, Depth + 2, DepChecker.getMemoryInstructions());
1329 OS.indent(Depth) << "Too many interesting dependences, not recorded\n";
1331 // List the pair of accesses need run-time checks to prove independence.
1332 PtrRtCheck.print(OS, Depth);
1336 const LoopAccessInfo &
1337 LoopAccessAnalysis::getInfo(Loop *L, const ValueToValueMap &Strides) {
1338 auto &LAI = LoopAccessInfoMap[L];
1341 assert((!LAI || LAI->NumSymbolicStrides == Strides.size()) &&
1342 "Symbolic strides changed for loop");
1346 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
1347 LAI = llvm::make_unique<LoopAccessInfo>(L, SE, DL, TLI, AA, DT, Strides);
1349 LAI->NumSymbolicStrides = Strides.size();
1355 void LoopAccessAnalysis::print(raw_ostream &OS, const Module *M) const {
1356 LoopAccessAnalysis &LAA = *const_cast<LoopAccessAnalysis *>(this);
1358 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1359 ValueToValueMap NoSymbolicStrides;
1361 for (Loop *TopLevelLoop : *LI)
1362 for (Loop *L : depth_first(TopLevelLoop)) {
1363 OS.indent(2) << L->getHeader()->getName() << ":\n";
1364 auto &LAI = LAA.getInfo(L, NoSymbolicStrides);
1369 bool LoopAccessAnalysis::runOnFunction(Function &F) {
1370 SE = &getAnalysis<ScalarEvolution>();
1371 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1372 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1373 AA = &getAnalysis<AliasAnalysis>();
1374 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1379 void LoopAccessAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
1380 AU.addRequired<ScalarEvolution>();
1381 AU.addRequired<AliasAnalysis>();
1382 AU.addRequired<DominatorTreeWrapperPass>();
1383 AU.addRequired<LoopInfoWrapperPass>();
1385 AU.setPreservesAll();
1388 char LoopAccessAnalysis::ID = 0;
1389 static const char laa_name[] = "Loop Access Analysis";
1390 #define LAA_NAME "loop-accesses"
1392 INITIALIZE_PASS_BEGIN(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1393 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1394 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1395 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1396 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
1397 INITIALIZE_PASS_END(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1400 Pass *createLAAPass() {
1401 return new LoopAccessAnalysis();