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/Analysis/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 /// \brief The maximum iterations used to merge memory checks
52 static cl::opt<unsigned> MemoryCheckMergeThreshold(
53 "memory-check-merge-threshold", cl::Hidden,
54 cl::desc("Maximum number of comparisons done when trying to merge "
55 "runtime memory checks. (default = 100)"),
58 /// Maximum SIMD width.
59 const unsigned VectorizerParams::MaxVectorWidth = 64;
61 /// \brief We collect interesting dependences up to this threshold.
62 static cl::opt<unsigned> MaxInterestingDependence(
63 "max-interesting-dependences", cl::Hidden,
64 cl::desc("Maximum number of interesting dependences collected by "
65 "loop-access analysis (default = 100)"),
68 bool VectorizerParams::isInterleaveForced() {
69 return ::VectorizationInterleave.getNumOccurrences() > 0;
72 void LoopAccessReport::emitAnalysis(const LoopAccessReport &Message,
73 const Function *TheFunction,
75 const char *PassName) {
76 DebugLoc DL = TheLoop->getStartLoc();
77 if (const Instruction *I = Message.getInstr())
78 DL = I->getDebugLoc();
79 emitOptimizationRemarkAnalysis(TheFunction->getContext(), PassName,
80 *TheFunction, DL, Message.str());
83 Value *llvm::stripIntegerCast(Value *V) {
84 if (CastInst *CI = dyn_cast<CastInst>(V))
85 if (CI->getOperand(0)->getType()->isIntegerTy())
86 return CI->getOperand(0);
90 const SCEV *llvm::replaceSymbolicStrideSCEV(ScalarEvolution *SE,
91 const ValueToValueMap &PtrToStride,
92 Value *Ptr, Value *OrigPtr) {
94 const SCEV *OrigSCEV = SE->getSCEV(Ptr);
96 // If there is an entry in the map return the SCEV of the pointer with the
97 // symbolic stride replaced by one.
98 ValueToValueMap::const_iterator SI =
99 PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
100 if (SI != PtrToStride.end()) {
101 Value *StrideVal = SI->second;
104 StrideVal = stripIntegerCast(StrideVal);
106 // Replace symbolic stride by one.
107 Value *One = ConstantInt::get(StrideVal->getType(), 1);
108 ValueToValueMap RewriteMap;
109 RewriteMap[StrideVal] = One;
112 SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
113 DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
118 // Otherwise, just return the SCEV of the original pointer.
119 return SE->getSCEV(Ptr);
122 void RuntimePointerChecking::insert(Loop *Lp, Value *Ptr, bool WritePtr,
123 unsigned DepSetId, unsigned ASId,
124 const ValueToValueMap &Strides) {
125 // Get the stride replaced scev.
126 const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
127 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
128 assert(AR && "Invalid addrec expression");
129 const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
130 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
131 Pointers.push_back(Ptr);
132 Starts.push_back(AR->getStart());
133 Ends.push_back(ScEnd);
134 IsWritePtr.push_back(WritePtr);
135 DependencySetId.push_back(DepSetId);
136 AliasSetId.push_back(ASId);
140 bool RuntimePointerChecking::needsChecking(
141 const CheckingPtrGroup &M, const CheckingPtrGroup &N,
142 const SmallVectorImpl<int> *PtrPartition) const {
143 for (unsigned I = 0, EI = M.Members.size(); EI != I; ++I)
144 for (unsigned J = 0, EJ = N.Members.size(); EJ != J; ++J)
145 if (needsChecking(M.Members[I], N.Members[J], PtrPartition))
150 /// Compare \p I and \p J and return the minimum.
151 /// Return nullptr in case we couldn't find an answer.
152 static const SCEV *getMinFromExprs(const SCEV *I, const SCEV *J,
153 ScalarEvolution *SE) {
154 const SCEV *Diff = SE->getMinusSCEV(J, I);
155 const SCEVConstant *C = dyn_cast<const SCEVConstant>(Diff);
159 if (C->getValue()->isNegative())
164 bool RuntimePointerChecking::CheckingPtrGroup::addPointer(unsigned Index) {
165 // Compare the starts and ends with the known minimum and maximum
166 // of this set. We need to know how we compare against the min/max
167 // of the set in order to be able to emit memchecks.
168 const SCEV *Min0 = getMinFromExprs(RtCheck.Starts[Index], Low, RtCheck.SE);
172 const SCEV *Min1 = getMinFromExprs(RtCheck.Ends[Index], High, RtCheck.SE);
176 // Update the low bound expression if we've found a new min value.
177 if (Min0 == RtCheck.Starts[Index])
178 Low = RtCheck.Starts[Index];
180 // Update the high bound expression if we've found a new max value.
181 if (Min1 != RtCheck.Ends[Index])
182 High = RtCheck.Ends[Index];
184 Members.push_back(Index);
188 void RuntimePointerChecking::groupChecks(
189 MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
190 // We build the groups from dependency candidates equivalence classes
192 // - We know that pointers in the same equivalence class share
193 // the same underlying object and therefore there is a chance
194 // that we can compare pointers
195 // - We wouldn't be able to merge two pointers for which we need
196 // to emit a memcheck. The classes in DepCands are already
197 // conveniently built such that no two pointers in the same
198 // class need checking against each other.
200 // We use the following (greedy) algorithm to construct the groups
201 // For every pointer in the equivalence class:
202 // For each existing group:
203 // - if the difference between this pointer and the min/max bounds
204 // of the group is a constant, then make the pointer part of the
205 // group and update the min/max bounds of that group as required.
207 CheckingGroups.clear();
209 // If we don't have the dependency partitions, construct a new
210 // checking pointer group for each pointer.
211 if (!UseDependencies) {
212 for (unsigned I = 0; I < Pointers.size(); ++I)
213 CheckingGroups.push_back(CheckingPtrGroup(I, *this));
217 unsigned TotalComparisons = 0;
219 DenseMap<Value *, unsigned> PositionMap;
220 for (unsigned Pointer = 0; Pointer < Pointers.size(); ++Pointer)
221 PositionMap[Pointers[Pointer]] = Pointer;
223 // We need to keep track of what pointers we've already seen so we
224 // don't process them twice.
225 SmallSet<unsigned, 2> Seen;
227 // Go through all equivalence classes, get the the "pointer check groups"
228 // and add them to the overall solution. We use the order in which accesses
229 // appear in 'Pointers' to enforce determinism.
230 for (unsigned I = 0; I < Pointers.size(); ++I) {
231 // We've seen this pointer before, and therefore already processed
232 // its equivalence class.
236 MemoryDepChecker::MemAccessInfo Access(Pointers[I], IsWritePtr[I]);
238 SmallVector<CheckingPtrGroup, 2> Groups;
239 auto LeaderI = DepCands.findValue(DepCands.getLeaderValue(Access));
241 // Because DepCands is constructed by visiting accesses in the order in
242 // which they appear in alias sets (which is deterministic) and the
243 // iteration order within an equivalence class member is only dependent on
244 // the order in which unions and insertions are performed on the
245 // equivalence class, the iteration order is deterministic.
246 for (auto MI = DepCands.member_begin(LeaderI), ME = DepCands.member_end();
248 unsigned Pointer = PositionMap[MI->getPointer()];
250 // Mark this pointer as seen.
251 Seen.insert(Pointer);
253 // Go through all the existing sets and see if we can find one
254 // which can include this pointer.
255 for (CheckingPtrGroup &Group : Groups) {
256 // Don't perform more than a certain amount of comparisons.
257 // This should limit the cost of grouping the pointers to something
258 // reasonable. If we do end up hitting this threshold, the algorithm
259 // will create separate groups for all remaining pointers.
260 if (TotalComparisons > MemoryCheckMergeThreshold)
265 if (Group.addPointer(Pointer)) {
272 // We couldn't add this pointer to any existing set or the threshold
273 // for the number of comparisons has been reached. Create a new group
274 // to hold the current pointer.
275 Groups.push_back(CheckingPtrGroup(Pointer, *this));
278 // We've computed the grouped checks for this partition.
279 // Save the results and continue with the next one.
280 std::copy(Groups.begin(), Groups.end(), std::back_inserter(CheckingGroups));
284 bool RuntimePointerChecking::needsChecking(
285 unsigned I, unsigned J, const SmallVectorImpl<int> *PtrPartition) const {
286 // No need to check if two readonly pointers intersect.
287 if (!IsWritePtr[I] && !IsWritePtr[J])
290 // Only need to check pointers between two different dependency sets.
291 if (DependencySetId[I] == DependencySetId[J])
294 // Only need to check pointers in the same alias set.
295 if (AliasSetId[I] != AliasSetId[J])
298 // If PtrPartition is set omit checks between pointers of the same partition.
299 // Partition number -1 means that the pointer is used in multiple partitions.
300 // In this case we can't omit the check.
301 if (PtrPartition && (*PtrPartition)[I] != -1 &&
302 (*PtrPartition)[I] == (*PtrPartition)[J])
308 void RuntimePointerChecking::print(
309 raw_ostream &OS, unsigned Depth,
310 const SmallVectorImpl<int> *PtrPartition) const {
312 OS.indent(Depth) << "Run-time memory checks:\n";
315 for (unsigned I = 0; I < CheckingGroups.size(); ++I)
316 for (unsigned J = I + 1; J < CheckingGroups.size(); ++J)
317 if (needsChecking(CheckingGroups[I], CheckingGroups[J], PtrPartition)) {
318 OS.indent(Depth) << "Check " << N++ << ":\n";
319 OS.indent(Depth + 2) << "Comparing group " << I << ":\n";
321 for (unsigned K = 0; K < CheckingGroups[I].Members.size(); ++K) {
322 OS.indent(Depth + 2) << *Pointers[CheckingGroups[I].Members[K]]
325 OS << " (Partition: "
326 << (*PtrPartition)[CheckingGroups[I].Members[K]] << ")"
330 OS.indent(Depth + 2) << "Against group " << J << ":\n";
332 for (unsigned K = 0; K < CheckingGroups[J].Members.size(); ++K) {
333 OS.indent(Depth + 2) << *Pointers[CheckingGroups[J].Members[K]]
336 OS << " (Partition: "
337 << (*PtrPartition)[CheckingGroups[J].Members[K]] << ")"
342 OS.indent(Depth) << "Grouped accesses:\n";
343 for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
344 OS.indent(Depth + 2) << "Group " << I << ":\n";
345 OS.indent(Depth + 4) << "(Low: " << *CheckingGroups[I].Low
346 << " High: " << *CheckingGroups[I].High << ")\n";
347 for (unsigned J = 0; J < CheckingGroups[I].Members.size(); ++J) {
348 OS.indent(Depth + 6) << "Member: " << *Exprs[CheckingGroups[I].Members[J]]
354 unsigned RuntimePointerChecking::getNumberOfChecks(
355 const SmallVectorImpl<int> *PtrPartition) const {
357 unsigned NumPartitions = CheckingGroups.size();
358 unsigned CheckCount = 0;
360 for (unsigned I = 0; I < NumPartitions; ++I)
361 for (unsigned J = I + 1; J < NumPartitions; ++J)
362 if (needsChecking(CheckingGroups[I], CheckingGroups[J], PtrPartition))
367 bool RuntimePointerChecking::needsAnyChecking(
368 const SmallVectorImpl<int> *PtrPartition) const {
369 unsigned NumPointers = Pointers.size();
371 for (unsigned I = 0; I < NumPointers; ++I)
372 for (unsigned J = I + 1; J < NumPointers; ++J)
373 if (needsChecking(I, J, PtrPartition))
379 /// \brief Analyses memory accesses in a loop.
381 /// Checks whether run time pointer checks are needed and builds sets for data
382 /// dependence checking.
383 class AccessAnalysis {
385 /// \brief Read or write access location.
386 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
387 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
389 AccessAnalysis(const DataLayout &Dl, AliasAnalysis *AA, LoopInfo *LI,
390 MemoryDepChecker::DepCandidates &DA)
391 : DL(Dl), AST(*AA), LI(LI), DepCands(DA),
392 IsRTCheckAnalysisNeeded(false) {}
394 /// \brief Register a load and whether it is only read from.
395 void addLoad(MemoryLocation &Loc, bool IsReadOnly) {
396 Value *Ptr = const_cast<Value*>(Loc.Ptr);
397 AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
398 Accesses.insert(MemAccessInfo(Ptr, false));
400 ReadOnlyPtr.insert(Ptr);
403 /// \brief Register a store.
404 void addStore(MemoryLocation &Loc) {
405 Value *Ptr = const_cast<Value*>(Loc.Ptr);
406 AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
407 Accesses.insert(MemAccessInfo(Ptr, true));
410 /// \brief Check whether we can check the pointers at runtime for
411 /// non-intersection.
413 /// Returns true if we need no check or if we do and we can generate them
414 /// (i.e. the pointers have computable bounds).
415 bool canCheckPtrAtRT(RuntimePointerChecking &RtCheck, ScalarEvolution *SE,
416 Loop *TheLoop, const ValueToValueMap &Strides,
417 bool ShouldCheckStride = false);
419 /// \brief Goes over all memory accesses, checks whether a RT check is needed
420 /// and builds sets of dependent accesses.
421 void buildDependenceSets() {
422 processMemAccesses();
425 /// \brief Initial processing of memory accesses determined that we need to
426 /// perform dependency checking.
428 /// Note that this can later be cleared if we retry memcheck analysis without
429 /// dependency checking (i.e. ShouldRetryWithRuntimeCheck).
430 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
432 /// We decided that no dependence analysis would be used. Reset the state.
433 void resetDepChecks(MemoryDepChecker &DepChecker) {
435 DepChecker.clearInterestingDependences();
438 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
441 typedef SetVector<MemAccessInfo> PtrAccessSet;
443 /// \brief Go over all memory access and check whether runtime pointer checks
444 /// are needed and build sets of dependency check candidates.
445 void processMemAccesses();
447 /// Set of all accesses.
448 PtrAccessSet Accesses;
450 const DataLayout &DL;
452 /// Set of accesses that need a further dependence check.
453 MemAccessInfoSet CheckDeps;
455 /// Set of pointers that are read only.
456 SmallPtrSet<Value*, 16> ReadOnlyPtr;
458 /// An alias set tracker to partition the access set by underlying object and
459 //intrinsic property (such as TBAA metadata).
464 /// Sets of potentially dependent accesses - members of one set share an
465 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
466 /// dependence check.
467 MemoryDepChecker::DepCandidates &DepCands;
469 /// \brief Initial processing of memory accesses determined that we may need
470 /// to add memchecks. Perform the analysis to determine the necessary checks.
472 /// Note that, this is different from isDependencyCheckNeeded. When we retry
473 /// memcheck analysis without dependency checking
474 /// (i.e. ShouldRetryWithRuntimeCheck), isDependencyCheckNeeded is cleared
475 /// while this remains set if we have potentially dependent accesses.
476 bool IsRTCheckAnalysisNeeded;
479 } // end anonymous namespace
481 /// \brief Check whether a pointer can participate in a runtime bounds check.
482 static bool hasComputableBounds(ScalarEvolution *SE,
483 const ValueToValueMap &Strides, Value *Ptr) {
484 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
485 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
489 return AR->isAffine();
492 bool AccessAnalysis::canCheckPtrAtRT(RuntimePointerChecking &RtCheck,
493 ScalarEvolution *SE, Loop *TheLoop,
494 const ValueToValueMap &StridesMap,
495 bool ShouldCheckStride) {
496 // Find pointers with computable bounds. We are going to use this information
497 // to place a runtime bound check.
500 bool NeedRTCheck = false;
501 if (!IsRTCheckAnalysisNeeded) return true;
503 bool IsDepCheckNeeded = isDependencyCheckNeeded();
505 // We assign a consecutive id to access from different alias sets.
506 // Accesses between different groups doesn't need to be checked.
508 for (auto &AS : AST) {
509 int NumReadPtrChecks = 0;
510 int NumWritePtrChecks = 0;
512 // We assign consecutive id to access from different dependence sets.
513 // Accesses within the same set don't need a runtime check.
514 unsigned RunningDepId = 1;
515 DenseMap<Value *, unsigned> DepSetId;
518 Value *Ptr = A.getValue();
519 bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
520 MemAccessInfo Access(Ptr, IsWrite);
527 if (hasComputableBounds(SE, StridesMap, Ptr) &&
528 // When we run after a failing dependency check we have to make sure
529 // we don't have wrapping pointers.
530 (!ShouldCheckStride ||
531 isStridedPtr(SE, Ptr, TheLoop, StridesMap) == 1)) {
532 // The id of the dependence set.
535 if (IsDepCheckNeeded) {
536 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
537 unsigned &LeaderId = DepSetId[Leader];
539 LeaderId = RunningDepId++;
542 // Each access has its own dependence set.
543 DepId = RunningDepId++;
545 RtCheck.insert(TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap);
547 DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
549 DEBUG(dbgs() << "LAA: Can't find bounds for ptr:" << *Ptr << '\n');
554 // If we have at least two writes or one write and a read then we need to
555 // check them. But there is no need to checks if there is only one
556 // dependence set for this alias set.
558 // Note that this function computes CanDoRT and NeedRTCheck independently.
559 // For example CanDoRT=false, NeedRTCheck=false means that we have a pointer
560 // for which we couldn't find the bounds but we don't actually need to emit
561 // any checks so it does not matter.
562 if (!(IsDepCheckNeeded && CanDoRT && RunningDepId == 2))
563 NeedRTCheck |= (NumWritePtrChecks >= 2 || (NumReadPtrChecks >= 1 &&
564 NumWritePtrChecks >= 1));
569 // If the pointers that we would use for the bounds comparison have different
570 // address spaces, assume the values aren't directly comparable, so we can't
571 // use them for the runtime check. We also have to assume they could
572 // overlap. In the future there should be metadata for whether address spaces
574 unsigned NumPointers = RtCheck.Pointers.size();
575 for (unsigned i = 0; i < NumPointers; ++i) {
576 for (unsigned j = i + 1; j < NumPointers; ++j) {
577 // Only need to check pointers between two different dependency sets.
578 if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
580 // Only need to check pointers in the same alias set.
581 if (RtCheck.AliasSetId[i] != RtCheck.AliasSetId[j])
584 Value *PtrI = RtCheck.Pointers[i];
585 Value *PtrJ = RtCheck.Pointers[j];
587 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
588 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
590 DEBUG(dbgs() << "LAA: Runtime check would require comparison between"
591 " different address spaces\n");
597 if (NeedRTCheck && CanDoRT)
598 RtCheck.groupChecks(DepCands, IsDepCheckNeeded);
600 DEBUG(dbgs() << "LAA: We need to do " << RtCheck.getNumberOfChecks(nullptr)
601 << " pointer comparisons.\n");
603 RtCheck.Need = NeedRTCheck;
605 bool CanDoRTIfNeeded = !NeedRTCheck || CanDoRT;
606 if (!CanDoRTIfNeeded)
608 return CanDoRTIfNeeded;
611 void AccessAnalysis::processMemAccesses() {
612 // We process the set twice: first we process read-write pointers, last we
613 // process read-only pointers. This allows us to skip dependence tests for
614 // read-only pointers.
616 DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
617 DEBUG(dbgs() << " AST: "; AST.dump());
618 DEBUG(dbgs() << "LAA: Accesses(" << Accesses.size() << "):\n");
620 for (auto A : Accesses)
621 dbgs() << "\t" << *A.getPointer() << " (" <<
622 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
623 "read-only" : "read")) << ")\n";
626 // The AliasSetTracker has nicely partitioned our pointers by metadata
627 // compatibility and potential for underlying-object overlap. As a result, we
628 // only need to check for potential pointer dependencies within each alias
630 for (auto &AS : AST) {
631 // Note that both the alias-set tracker and the alias sets themselves used
632 // linked lists internally and so the iteration order here is deterministic
633 // (matching the original instruction order within each set).
635 bool SetHasWrite = false;
637 // Map of pointers to last access encountered.
638 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
639 UnderlyingObjToAccessMap ObjToLastAccess;
641 // Set of access to check after all writes have been processed.
642 PtrAccessSet DeferredAccesses;
644 // Iterate over each alias set twice, once to process read/write pointers,
645 // and then to process read-only pointers.
646 for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
647 bool UseDeferred = SetIteration > 0;
648 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
651 Value *Ptr = AV.getValue();
653 // For a single memory access in AliasSetTracker, Accesses may contain
654 // both read and write, and they both need to be handled for CheckDeps.
656 if (AC.getPointer() != Ptr)
659 bool IsWrite = AC.getInt();
661 // If we're using the deferred access set, then it contains only
663 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
664 if (UseDeferred && !IsReadOnlyPtr)
666 // Otherwise, the pointer must be in the PtrAccessSet, either as a
668 assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
669 S.count(MemAccessInfo(Ptr, false))) &&
670 "Alias-set pointer not in the access set?");
672 MemAccessInfo Access(Ptr, IsWrite);
673 DepCands.insert(Access);
675 // Memorize read-only pointers for later processing and skip them in
676 // the first round (they need to be checked after we have seen all
677 // write pointers). Note: we also mark pointer that are not
678 // consecutive as "read-only" pointers (so that we check
679 // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
680 if (!UseDeferred && IsReadOnlyPtr) {
681 DeferredAccesses.insert(Access);
685 // If this is a write - check other reads and writes for conflicts. If
686 // this is a read only check other writes for conflicts (but only if
687 // there is no other write to the ptr - this is an optimization to
688 // catch "a[i] = a[i] + " without having to do a dependence check).
689 if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
690 CheckDeps.insert(Access);
691 IsRTCheckAnalysisNeeded = true;
697 // Create sets of pointers connected by a shared alias set and
698 // underlying object.
699 typedef SmallVector<Value *, 16> ValueVector;
700 ValueVector TempObjects;
702 GetUnderlyingObjects(Ptr, TempObjects, DL, LI);
703 DEBUG(dbgs() << "Underlying objects for pointer " << *Ptr << "\n");
704 for (Value *UnderlyingObj : TempObjects) {
705 UnderlyingObjToAccessMap::iterator Prev =
706 ObjToLastAccess.find(UnderlyingObj);
707 if (Prev != ObjToLastAccess.end())
708 DepCands.unionSets(Access, Prev->second);
710 ObjToLastAccess[UnderlyingObj] = Access;
711 DEBUG(dbgs() << " " << *UnderlyingObj << "\n");
719 static bool isInBoundsGep(Value *Ptr) {
720 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
721 return GEP->isInBounds();
725 /// \brief Return true if an AddRec pointer \p Ptr is unsigned non-wrapping,
726 /// i.e. monotonically increasing/decreasing.
727 static bool isNoWrapAddRec(Value *Ptr, const SCEVAddRecExpr *AR,
728 ScalarEvolution *SE, const Loop *L) {
729 // FIXME: This should probably only return true for NUW.
730 if (AR->getNoWrapFlags(SCEV::NoWrapMask))
733 // Scalar evolution does not propagate the non-wrapping flags to values that
734 // are derived from a non-wrapping induction variable because non-wrapping
735 // could be flow-sensitive.
737 // Look through the potentially overflowing instruction to try to prove
738 // non-wrapping for the *specific* value of Ptr.
740 // The arithmetic implied by an inbounds GEP can't overflow.
741 auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
742 if (!GEP || !GEP->isInBounds())
745 // Make sure there is only one non-const index and analyze that.
746 Value *NonConstIndex = nullptr;
747 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
748 if (!isa<ConstantInt>(*Index)) {
751 NonConstIndex = *Index;
754 // The recurrence is on the pointer, ignore for now.
757 // The index in GEP is signed. It is non-wrapping if it's derived from a NSW
758 // AddRec using a NSW operation.
759 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(NonConstIndex))
760 if (OBO->hasNoSignedWrap() &&
761 // Assume constant for other the operand so that the AddRec can be
763 isa<ConstantInt>(OBO->getOperand(1))) {
764 auto *OpScev = SE->getSCEV(OBO->getOperand(0));
766 if (auto *OpAR = dyn_cast<SCEVAddRecExpr>(OpScev))
767 return OpAR->getLoop() == L && OpAR->getNoWrapFlags(SCEV::FlagNSW);
773 /// \brief Check whether the access through \p Ptr has a constant stride.
774 int llvm::isStridedPtr(ScalarEvolution *SE, Value *Ptr, const Loop *Lp,
775 const ValueToValueMap &StridesMap) {
776 const Type *Ty = Ptr->getType();
777 assert(Ty->isPointerTy() && "Unexpected non-ptr");
779 // Make sure that the pointer does not point to aggregate types.
780 const PointerType *PtrTy = cast<PointerType>(Ty);
781 if (PtrTy->getElementType()->isAggregateType()) {
782 DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type"
787 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
789 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
791 DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer "
792 << *Ptr << " SCEV: " << *PtrScev << "\n");
796 // The accesss function must stride over the innermost loop.
797 if (Lp != AR->getLoop()) {
798 DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " <<
799 *Ptr << " SCEV: " << *PtrScev << "\n");
802 // The address calculation must not wrap. Otherwise, a dependence could be
804 // An inbounds getelementptr that is a AddRec with a unit stride
805 // cannot wrap per definition. The unit stride requirement is checked later.
806 // An getelementptr without an inbounds attribute and unit stride would have
807 // to access the pointer value "0" which is undefined behavior in address
808 // space 0, therefore we can also vectorize this case.
809 bool IsInBoundsGEP = isInBoundsGep(Ptr);
810 bool IsNoWrapAddRec = isNoWrapAddRec(Ptr, AR, SE, Lp);
811 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
812 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
813 DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
814 << *Ptr << " SCEV: " << *PtrScev << "\n");
818 // Check the step is constant.
819 const SCEV *Step = AR->getStepRecurrence(*SE);
821 // Calculate the pointer stride and check if it is constant.
822 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
824 DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr <<
825 " SCEV: " << *PtrScev << "\n");
829 auto &DL = Lp->getHeader()->getModule()->getDataLayout();
830 int64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
831 const APInt &APStepVal = C->getValue()->getValue();
833 // Huge step value - give up.
834 if (APStepVal.getBitWidth() > 64)
837 int64_t StepVal = APStepVal.getSExtValue();
840 int64_t Stride = StepVal / Size;
841 int64_t Rem = StepVal % Size;
845 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
846 // know we can't "wrap around the address space". In case of address space
847 // zero we know that this won't happen without triggering undefined behavior.
848 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
849 Stride != 1 && Stride != -1)
855 bool MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
859 case BackwardVectorizable:
863 case ForwardButPreventsForwarding:
865 case BackwardVectorizableButPreventsForwarding:
868 llvm_unreachable("unexpected DepType!");
871 bool MemoryDepChecker::Dependence::isInterestingDependence(DepType Type) {
877 case BackwardVectorizable:
879 case ForwardButPreventsForwarding:
881 case BackwardVectorizableButPreventsForwarding:
884 llvm_unreachable("unexpected DepType!");
887 bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
891 case ForwardButPreventsForwarding:
895 case BackwardVectorizable:
897 case BackwardVectorizableButPreventsForwarding:
900 llvm_unreachable("unexpected DepType!");
903 bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
904 unsigned TypeByteSize) {
905 // If loads occur at a distance that is not a multiple of a feasible vector
906 // factor store-load forwarding does not take place.
907 // Positive dependences might cause troubles because vectorizing them might
908 // prevent store-load forwarding making vectorized code run a lot slower.
909 // a[i] = a[i-3] ^ a[i-8];
910 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
911 // hence on your typical architecture store-load forwarding does not take
912 // place. Vectorizing in such cases does not make sense.
913 // Store-load forwarding distance.
914 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
915 // Maximum vector factor.
916 unsigned MaxVFWithoutSLForwardIssues =
917 VectorizerParams::MaxVectorWidth * TypeByteSize;
918 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
919 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
921 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
923 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
924 MaxVFWithoutSLForwardIssues = (vf >>=1);
929 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
930 DEBUG(dbgs() << "LAA: Distance " << Distance <<
931 " that could cause a store-load forwarding conflict\n");
935 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
936 MaxVFWithoutSLForwardIssues !=
937 VectorizerParams::MaxVectorWidth * TypeByteSize)
938 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
942 /// \brief Check the dependence for two accesses with the same stride \p Stride.
943 /// \p Distance is the positive distance and \p TypeByteSize is type size in
946 /// \returns true if they are independent.
947 static bool areStridedAccessesIndependent(unsigned Distance, unsigned Stride,
948 unsigned TypeByteSize) {
949 assert(Stride > 1 && "The stride must be greater than 1");
950 assert(TypeByteSize > 0 && "The type size in byte must be non-zero");
951 assert(Distance > 0 && "The distance must be non-zero");
953 // Skip if the distance is not multiple of type byte size.
954 if (Distance % TypeByteSize)
957 unsigned ScaledDist = Distance / TypeByteSize;
959 // No dependence if the scaled distance is not multiple of the stride.
961 // for (i = 0; i < 1024 ; i += 4)
962 // A[i+2] = A[i] + 1;
964 // Two accesses in memory (scaled distance is 2, stride is 4):
965 // | A[0] | | | | A[4] | | | |
966 // | | | A[2] | | | | A[6] | |
969 // for (i = 0; i < 1024 ; i += 3)
970 // A[i+4] = A[i] + 1;
972 // Two accesses in memory (scaled distance is 4, stride is 3):
973 // | A[0] | | | A[3] | | | A[6] | | |
974 // | | | | | A[4] | | | A[7] | |
975 return ScaledDist % Stride;
978 MemoryDepChecker::Dependence::DepType
979 MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
980 const MemAccessInfo &B, unsigned BIdx,
981 const ValueToValueMap &Strides) {
982 assert (AIdx < BIdx && "Must pass arguments in program order");
984 Value *APtr = A.getPointer();
985 Value *BPtr = B.getPointer();
986 bool AIsWrite = A.getInt();
987 bool BIsWrite = B.getInt();
989 // Two reads are independent.
990 if (!AIsWrite && !BIsWrite)
991 return Dependence::NoDep;
993 // We cannot check pointers in different address spaces.
994 if (APtr->getType()->getPointerAddressSpace() !=
995 BPtr->getType()->getPointerAddressSpace())
996 return Dependence::Unknown;
998 const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
999 const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
1001 int StrideAPtr = isStridedPtr(SE, APtr, InnermostLoop, Strides);
1002 int StrideBPtr = isStridedPtr(SE, BPtr, InnermostLoop, Strides);
1004 const SCEV *Src = AScev;
1005 const SCEV *Sink = BScev;
1007 // If the induction step is negative we have to invert source and sink of the
1009 if (StrideAPtr < 0) {
1012 std::swap(APtr, BPtr);
1013 std::swap(Src, Sink);
1014 std::swap(AIsWrite, BIsWrite);
1015 std::swap(AIdx, BIdx);
1016 std::swap(StrideAPtr, StrideBPtr);
1019 const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
1021 DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
1022 << "(Induction step: " << StrideAPtr << ")\n");
1023 DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
1024 << *InstMap[BIdx] << ": " << *Dist << "\n");
1026 // Need accesses with constant stride. We don't want to vectorize
1027 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
1028 // the address space.
1029 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
1030 DEBUG(dbgs() << "Pointer access with non-constant stride\n");
1031 return Dependence::Unknown;
1034 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
1036 DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
1037 ShouldRetryWithRuntimeCheck = true;
1038 return Dependence::Unknown;
1041 Type *ATy = APtr->getType()->getPointerElementType();
1042 Type *BTy = BPtr->getType()->getPointerElementType();
1043 auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
1044 unsigned TypeByteSize = DL.getTypeAllocSize(ATy);
1046 // Negative distances are not plausible dependencies.
1047 const APInt &Val = C->getValue()->getValue();
1048 if (Val.isNegative()) {
1049 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
1050 if (IsTrueDataDependence &&
1051 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
1053 return Dependence::ForwardButPreventsForwarding;
1055 DEBUG(dbgs() << "LAA: Dependence is negative: NoDep\n");
1056 return Dependence::Forward;
1059 // Write to the same location with the same size.
1060 // Could be improved to assert type sizes are the same (i32 == float, etc).
1063 return Dependence::NoDep;
1064 DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n");
1065 return Dependence::Unknown;
1068 assert(Val.isStrictlyPositive() && "Expect a positive value");
1072 "LAA: ReadWrite-Write positive dependency with different types\n");
1073 return Dependence::Unknown;
1076 unsigned Distance = (unsigned) Val.getZExtValue();
1078 unsigned Stride = std::abs(StrideAPtr);
1080 areStridedAccessesIndependent(Distance, Stride, TypeByteSize)) {
1081 DEBUG(dbgs() << "LAA: Strided accesses are independent\n");
1082 return Dependence::NoDep;
1085 // Bail out early if passed-in parameters make vectorization not feasible.
1086 unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
1087 VectorizerParams::VectorizationFactor : 1);
1088 unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
1089 VectorizerParams::VectorizationInterleave : 1);
1090 // The minimum number of iterations for a vectorized/unrolled version.
1091 unsigned MinNumIter = std::max(ForcedFactor * ForcedUnroll, 2U);
1093 // It's not vectorizable if the distance is smaller than the minimum distance
1094 // needed for a vectroized/unrolled version. Vectorizing one iteration in
1095 // front needs TypeByteSize * Stride. Vectorizing the last iteration needs
1096 // TypeByteSize (No need to plus the last gap distance).
1098 // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1100 // int *B = (int *)((char *)A + 14);
1101 // for (i = 0 ; i < 1024 ; i += 2)
1105 // Two accesses in memory (stride is 2):
1106 // | A[0] | | A[2] | | A[4] | | A[6] | |
1107 // | B[0] | | B[2] | | B[4] |
1109 // Distance needs for vectorizing iterations except the last iteration:
1110 // 4 * 2 * (MinNumIter - 1). Distance needs for the last iteration: 4.
1111 // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4.
1113 // If MinNumIter is 2, it is vectorizable as the minimum distance needed is
1114 // 12, which is less than distance.
1116 // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4),
1117 // the minimum distance needed is 28, which is greater than distance. It is
1118 // not safe to do vectorization.
1119 unsigned MinDistanceNeeded =
1120 TypeByteSize * Stride * (MinNumIter - 1) + TypeByteSize;
1121 if (MinDistanceNeeded > Distance) {
1122 DEBUG(dbgs() << "LAA: Failure because of positive distance " << Distance
1124 return Dependence::Backward;
1127 // Unsafe if the minimum distance needed is greater than max safe distance.
1128 if (MinDistanceNeeded > MaxSafeDepDistBytes) {
1129 DEBUG(dbgs() << "LAA: Failure because it needs at least "
1130 << MinDistanceNeeded << " size in bytes");
1131 return Dependence::Backward;
1134 // Positive distance bigger than max vectorization factor.
1135 // FIXME: Should use max factor instead of max distance in bytes, which could
1136 // not handle different types.
1137 // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1138 // void foo (int *A, char *B) {
1139 // for (unsigned i = 0; i < 1024; i++) {
1140 // A[i+2] = A[i] + 1;
1141 // B[i+2] = B[i] + 1;
1145 // This case is currently unsafe according to the max safe distance. If we
1146 // analyze the two accesses on array B, the max safe dependence distance
1147 // is 2. Then we analyze the accesses on array A, the minimum distance needed
1148 // is 8, which is less than 2 and forbidden vectorization, But actually
1149 // both A and B could be vectorized by 2 iterations.
1150 MaxSafeDepDistBytes =
1151 Distance < MaxSafeDepDistBytes ? Distance : MaxSafeDepDistBytes;
1153 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
1154 if (IsTrueDataDependence &&
1155 couldPreventStoreLoadForward(Distance, TypeByteSize))
1156 return Dependence::BackwardVectorizableButPreventsForwarding;
1158 DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue()
1159 << " with max VF = "
1160 << MaxSafeDepDistBytes / (TypeByteSize * Stride) << '\n');
1162 return Dependence::BackwardVectorizable;
1165 bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets,
1166 MemAccessInfoSet &CheckDeps,
1167 const ValueToValueMap &Strides) {
1169 MaxSafeDepDistBytes = -1U;
1170 while (!CheckDeps.empty()) {
1171 MemAccessInfo CurAccess = *CheckDeps.begin();
1173 // Get the relevant memory access set.
1174 EquivalenceClasses<MemAccessInfo>::iterator I =
1175 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
1177 // Check accesses within this set.
1178 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
1179 AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
1181 // Check every access pair.
1183 CheckDeps.erase(*AI);
1184 EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
1186 // Check every accessing instruction pair in program order.
1187 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
1188 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
1189 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
1190 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
1191 auto A = std::make_pair(&*AI, *I1);
1192 auto B = std::make_pair(&*OI, *I2);
1198 Dependence::DepType Type =
1199 isDependent(*A.first, A.second, *B.first, B.second, Strides);
1200 SafeForVectorization &= Dependence::isSafeForVectorization(Type);
1202 // Gather dependences unless we accumulated MaxInterestingDependence
1203 // dependences. In that case return as soon as we find the first
1204 // unsafe dependence. This puts a limit on this quadratic
1206 if (RecordInterestingDependences) {
1207 if (Dependence::isInterestingDependence(Type))
1208 InterestingDependences.push_back(
1209 Dependence(A.second, B.second, Type));
1211 if (InterestingDependences.size() >= MaxInterestingDependence) {
1212 RecordInterestingDependences = false;
1213 InterestingDependences.clear();
1214 DEBUG(dbgs() << "Too many dependences, stopped recording\n");
1217 if (!RecordInterestingDependences && !SafeForVectorization)
1226 DEBUG(dbgs() << "Total Interesting Dependences: "
1227 << InterestingDependences.size() << "\n");
1228 return SafeForVectorization;
1231 SmallVector<Instruction *, 4>
1232 MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const {
1233 MemAccessInfo Access(Ptr, isWrite);
1234 auto &IndexVector = Accesses.find(Access)->second;
1236 SmallVector<Instruction *, 4> Insts;
1237 std::transform(IndexVector.begin(), IndexVector.end(),
1238 std::back_inserter(Insts),
1239 [&](unsigned Idx) { return this->InstMap[Idx]; });
1243 const char *MemoryDepChecker::Dependence::DepName[] = {
1244 "NoDep", "Unknown", "Forward", "ForwardButPreventsForwarding", "Backward",
1245 "BackwardVectorizable", "BackwardVectorizableButPreventsForwarding"};
1247 void MemoryDepChecker::Dependence::print(
1248 raw_ostream &OS, unsigned Depth,
1249 const SmallVectorImpl<Instruction *> &Instrs) const {
1250 OS.indent(Depth) << DepName[Type] << ":\n";
1251 OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
1252 OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
1255 bool LoopAccessInfo::canAnalyzeLoop() {
1256 // We need to have a loop header.
1257 DEBUG(dbgs() << "LAA: Found a loop: " <<
1258 TheLoop->getHeader()->getName() << '\n');
1260 // We can only analyze innermost loops.
1261 if (!TheLoop->empty()) {
1262 DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
1263 emitAnalysis(LoopAccessReport() << "loop is not the innermost loop");
1267 // We must have a single backedge.
1268 if (TheLoop->getNumBackEdges() != 1) {
1269 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
1271 LoopAccessReport() <<
1272 "loop control flow is not understood by analyzer");
1276 // We must have a single exiting block.
1277 if (!TheLoop->getExitingBlock()) {
1278 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
1280 LoopAccessReport() <<
1281 "loop control flow is not understood by analyzer");
1285 // We only handle bottom-tested loops, i.e. loop in which the condition is
1286 // checked at the end of each iteration. With that we can assume that all
1287 // instructions in the loop are executed the same number of times.
1288 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
1289 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
1291 LoopAccessReport() <<
1292 "loop control flow is not understood by analyzer");
1296 // ScalarEvolution needs to be able to find the exit count.
1297 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
1298 if (ExitCount == SE->getCouldNotCompute()) {
1299 emitAnalysis(LoopAccessReport() <<
1300 "could not determine number of loop iterations");
1301 DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
1308 void LoopAccessInfo::analyzeLoop(const ValueToValueMap &Strides) {
1310 typedef SmallVector<Value*, 16> ValueVector;
1311 typedef SmallPtrSet<Value*, 16> ValueSet;
1313 // Holds the Load and Store *instructions*.
1317 // Holds all the different accesses in the loop.
1318 unsigned NumReads = 0;
1319 unsigned NumReadWrites = 0;
1321 PtrRtChecking.Pointers.clear();
1322 PtrRtChecking.Need = false;
1324 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
1327 for (Loop::block_iterator bb = TheLoop->block_begin(),
1328 be = TheLoop->block_end(); bb != be; ++bb) {
1330 // Scan the BB and collect legal loads and stores.
1331 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1334 // If this is a load, save it. If this instruction can read from memory
1335 // but is not a load, then we quit. Notice that we don't handle function
1336 // calls that read or write.
1337 if (it->mayReadFromMemory()) {
1338 // Many math library functions read the rounding mode. We will only
1339 // vectorize a loop if it contains known function calls that don't set
1340 // the flag. Therefore, it is safe to ignore this read from memory.
1341 CallInst *Call = dyn_cast<CallInst>(it);
1342 if (Call && getIntrinsicIDForCall(Call, TLI))
1345 // If the function has an explicit vectorized counterpart, we can safely
1346 // assume that it can be vectorized.
1347 if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
1348 TLI->isFunctionVectorizable(Call->getCalledFunction()->getName()))
1351 LoadInst *Ld = dyn_cast<LoadInst>(it);
1352 if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
1353 emitAnalysis(LoopAccessReport(Ld)
1354 << "read with atomic ordering or volatile read");
1355 DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
1360 Loads.push_back(Ld);
1361 DepChecker.addAccess(Ld);
1365 // Save 'store' instructions. Abort if other instructions write to memory.
1366 if (it->mayWriteToMemory()) {
1367 StoreInst *St = dyn_cast<StoreInst>(it);
1369 emitAnalysis(LoopAccessReport(it) <<
1370 "instruction cannot be vectorized");
1374 if (!St->isSimple() && !IsAnnotatedParallel) {
1375 emitAnalysis(LoopAccessReport(St)
1376 << "write with atomic ordering or volatile write");
1377 DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
1382 Stores.push_back(St);
1383 DepChecker.addAccess(St);
1388 // Now we have two lists that hold the loads and the stores.
1389 // Next, we find the pointers that they use.
1391 // Check if we see any stores. If there are no stores, then we don't
1392 // care if the pointers are *restrict*.
1393 if (!Stores.size()) {
1394 DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
1399 MemoryDepChecker::DepCandidates DependentAccesses;
1400 AccessAnalysis Accesses(TheLoop->getHeader()->getModule()->getDataLayout(),
1401 AA, LI, DependentAccesses);
1403 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1404 // multiple times on the same object. If the ptr is accessed twice, once
1405 // for read and once for write, it will only appear once (on the write
1406 // list). This is okay, since we are going to check for conflicts between
1407 // writes and between reads and writes, but not between reads and reads.
1410 ValueVector::iterator I, IE;
1411 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1412 StoreInst *ST = cast<StoreInst>(*I);
1413 Value* Ptr = ST->getPointerOperand();
1414 // Check for store to loop invariant address.
1415 StoreToLoopInvariantAddress |= isUniform(Ptr);
1416 // If we did *not* see this pointer before, insert it to the read-write
1417 // list. At this phase it is only a 'write' list.
1418 if (Seen.insert(Ptr).second) {
1421 MemoryLocation Loc = MemoryLocation::get(ST);
1422 // The TBAA metadata could have a control dependency on the predication
1423 // condition, so we cannot rely on it when determining whether or not we
1424 // need runtime pointer checks.
1425 if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
1426 Loc.AATags.TBAA = nullptr;
1428 Accesses.addStore(Loc);
1432 if (IsAnnotatedParallel) {
1434 << "LAA: A loop annotated parallel, ignore memory dependency "
1440 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1441 LoadInst *LD = cast<LoadInst>(*I);
1442 Value* Ptr = LD->getPointerOperand();
1443 // If we did *not* see this pointer before, insert it to the
1444 // read list. If we *did* see it before, then it is already in
1445 // the read-write list. This allows us to vectorize expressions
1446 // such as A[i] += x; Because the address of A[i] is a read-write
1447 // pointer. This only works if the index of A[i] is consecutive.
1448 // If the address of i is unknown (for example A[B[i]]) then we may
1449 // read a few words, modify, and write a few words, and some of the
1450 // words may be written to the same address.
1451 bool IsReadOnlyPtr = false;
1452 if (Seen.insert(Ptr).second || !isStridedPtr(SE, Ptr, TheLoop, Strides)) {
1454 IsReadOnlyPtr = true;
1457 MemoryLocation Loc = MemoryLocation::get(LD);
1458 // The TBAA metadata could have a control dependency on the predication
1459 // condition, so we cannot rely on it when determining whether or not we
1460 // need runtime pointer checks.
1461 if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
1462 Loc.AATags.TBAA = nullptr;
1464 Accesses.addLoad(Loc, IsReadOnlyPtr);
1467 // If we write (or read-write) to a single destination and there are no
1468 // other reads in this loop then is it safe to vectorize.
1469 if (NumReadWrites == 1 && NumReads == 0) {
1470 DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
1475 // Build dependence sets and check whether we need a runtime pointer bounds
1477 Accesses.buildDependenceSets();
1479 // Find pointers with computable bounds. We are going to use this information
1480 // to place a runtime bound check.
1481 bool CanDoRTIfNeeded =
1482 Accesses.canCheckPtrAtRT(PtrRtChecking, SE, TheLoop, Strides);
1483 if (!CanDoRTIfNeeded) {
1484 emitAnalysis(LoopAccessReport() << "cannot identify array bounds");
1485 DEBUG(dbgs() << "LAA: We can't vectorize because we can't find "
1486 << "the array bounds.\n");
1491 DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
1494 if (Accesses.isDependencyCheckNeeded()) {
1495 DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
1496 CanVecMem = DepChecker.areDepsSafe(
1497 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
1498 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
1500 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
1501 DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
1503 // Clear the dependency checks. We assume they are not needed.
1504 Accesses.resetDepChecks(DepChecker);
1506 PtrRtChecking.reset();
1507 PtrRtChecking.Need = true;
1510 Accesses.canCheckPtrAtRT(PtrRtChecking, SE, TheLoop, Strides, true);
1512 // Check that we found the bounds for the pointer.
1513 if (!CanDoRTIfNeeded) {
1514 emitAnalysis(LoopAccessReport()
1515 << "cannot check memory dependencies at runtime");
1516 DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
1526 DEBUG(dbgs() << "LAA: No unsafe dependent memory operations in loop. We"
1527 << (PtrRtChecking.Need ? "" : " don't")
1528 << " need runtime memory checks.\n");
1530 emitAnalysis(LoopAccessReport() <<
1531 "unsafe dependent memory operations in loop");
1532 DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
1536 bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
1537 DominatorTree *DT) {
1538 assert(TheLoop->contains(BB) && "Unknown block used");
1540 // Blocks that do not dominate the latch need predication.
1541 BasicBlock* Latch = TheLoop->getLoopLatch();
1542 return !DT->dominates(BB, Latch);
1545 void LoopAccessInfo::emitAnalysis(LoopAccessReport &Message) {
1546 assert(!Report && "Multiple reports generated");
1550 bool LoopAccessInfo::isUniform(Value *V) const {
1551 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1554 // FIXME: this function is currently a duplicate of the one in
1555 // LoopVectorize.cpp.
1556 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1560 if (Instruction *I = dyn_cast<Instruction>(V))
1561 return I->getParent() == Loc->getParent() ? I : nullptr;
1565 std::pair<Instruction *, Instruction *> LoopAccessInfo::addRuntimeCheck(
1566 Instruction *Loc, const SmallVectorImpl<int> *PtrPartition) const {
1567 if (!PtrRtChecking.Need)
1568 return std::make_pair(nullptr, nullptr);
1570 SmallVector<TrackingVH<Value>, 2> Starts;
1571 SmallVector<TrackingVH<Value>, 2> Ends;
1573 LLVMContext &Ctx = Loc->getContext();
1574 SCEVExpander Exp(*SE, DL, "induction");
1575 Instruction *FirstInst = nullptr;
1577 for (unsigned i = 0; i < PtrRtChecking.CheckingGroups.size(); ++i) {
1578 const RuntimePointerChecking::CheckingPtrGroup &CG =
1579 PtrRtChecking.CheckingGroups[i];
1580 Value *Ptr = PtrRtChecking.Pointers[CG.Members[0]];
1581 const SCEV *Sc = SE->getSCEV(Ptr);
1583 if (SE->isLoopInvariant(Sc, TheLoop)) {
1584 DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" << *Ptr
1586 Starts.push_back(Ptr);
1587 Ends.push_back(Ptr);
1589 unsigned AS = Ptr->getType()->getPointerAddressSpace();
1591 // Use this type for pointer arithmetic.
1592 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1593 Value *Start = nullptr, *End = nullptr;
1595 DEBUG(dbgs() << "LAA: Adding RT check for range:\n");
1596 Start = Exp.expandCodeFor(CG.Low, PtrArithTy, Loc);
1597 End = Exp.expandCodeFor(CG.High, PtrArithTy, Loc);
1598 DEBUG(dbgs() << "Start: " << *CG.Low << " End: " << *CG.High << "\n");
1599 Starts.push_back(Start);
1600 Ends.push_back(End);
1604 IRBuilder<> ChkBuilder(Loc);
1605 // Our instructions might fold to a constant.
1606 Value *MemoryRuntimeCheck = nullptr;
1607 for (unsigned i = 0; i < PtrRtChecking.CheckingGroups.size(); ++i) {
1608 for (unsigned j = i + 1; j < PtrRtChecking.CheckingGroups.size(); ++j) {
1609 const RuntimePointerChecking::CheckingPtrGroup &CGI =
1610 PtrRtChecking.CheckingGroups[i];
1611 const RuntimePointerChecking::CheckingPtrGroup &CGJ =
1612 PtrRtChecking.CheckingGroups[j];
1614 if (!PtrRtChecking.needsChecking(CGI, CGJ, PtrPartition))
1617 unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
1618 unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
1620 assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
1621 (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
1622 "Trying to bounds check pointers with different address spaces");
1624 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1625 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
1627 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
1628 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
1629 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc");
1630 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc");
1632 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1633 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1634 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1635 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1636 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1637 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1638 if (MemoryRuntimeCheck) {
1639 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1641 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1643 MemoryRuntimeCheck = IsConflict;
1647 if (!MemoryRuntimeCheck)
1648 return std::make_pair(nullptr, nullptr);
1650 // We have to do this trickery because the IRBuilder might fold the check to a
1651 // constant expression in which case there is no Instruction anchored in a
1653 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1654 ConstantInt::getTrue(Ctx));
1655 ChkBuilder.Insert(Check, "memcheck.conflict");
1656 FirstInst = getFirstInst(FirstInst, Check, Loc);
1657 return std::make_pair(FirstInst, Check);
1660 LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
1661 const DataLayout &DL,
1662 const TargetLibraryInfo *TLI, AliasAnalysis *AA,
1663 DominatorTree *DT, LoopInfo *LI,
1664 const ValueToValueMap &Strides)
1665 : PtrRtChecking(SE), DepChecker(SE, L), TheLoop(L), SE(SE), DL(DL),
1666 TLI(TLI), AA(AA), DT(DT), LI(LI), NumLoads(0), NumStores(0),
1667 MaxSafeDepDistBytes(-1U), CanVecMem(false),
1668 StoreToLoopInvariantAddress(false) {
1669 if (canAnalyzeLoop())
1670 analyzeLoop(Strides);
1673 void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
1675 if (PtrRtChecking.Need)
1676 OS.indent(Depth) << "Memory dependences are safe with run-time checks\n";
1678 OS.indent(Depth) << "Memory dependences are safe\n";
1682 OS.indent(Depth) << "Report: " << Report->str() << "\n";
1684 if (auto *InterestingDependences = DepChecker.getInterestingDependences()) {
1685 OS.indent(Depth) << "Interesting Dependences:\n";
1686 for (auto &Dep : *InterestingDependences) {
1687 Dep.print(OS, Depth + 2, DepChecker.getMemoryInstructions());
1691 OS.indent(Depth) << "Too many interesting dependences, not recorded\n";
1693 // List the pair of accesses need run-time checks to prove independence.
1694 PtrRtChecking.print(OS, Depth);
1697 OS.indent(Depth) << "Store to invariant address was "
1698 << (StoreToLoopInvariantAddress ? "" : "not ")
1699 << "found in loop.\n";
1702 const LoopAccessInfo &
1703 LoopAccessAnalysis::getInfo(Loop *L, const ValueToValueMap &Strides) {
1704 auto &LAI = LoopAccessInfoMap[L];
1707 assert((!LAI || LAI->NumSymbolicStrides == Strides.size()) &&
1708 "Symbolic strides changed for loop");
1712 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
1713 LAI = llvm::make_unique<LoopAccessInfo>(L, SE, DL, TLI, AA, DT, LI,
1716 LAI->NumSymbolicStrides = Strides.size();
1722 void LoopAccessAnalysis::print(raw_ostream &OS, const Module *M) const {
1723 LoopAccessAnalysis &LAA = *const_cast<LoopAccessAnalysis *>(this);
1725 ValueToValueMap NoSymbolicStrides;
1727 for (Loop *TopLevelLoop : *LI)
1728 for (Loop *L : depth_first(TopLevelLoop)) {
1729 OS.indent(2) << L->getHeader()->getName() << ":\n";
1730 auto &LAI = LAA.getInfo(L, NoSymbolicStrides);
1735 bool LoopAccessAnalysis::runOnFunction(Function &F) {
1736 SE = &getAnalysis<ScalarEvolution>();
1737 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1738 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1739 AA = &getAnalysis<AliasAnalysis>();
1740 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1741 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1746 void LoopAccessAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
1747 AU.addRequired<ScalarEvolution>();
1748 AU.addRequired<AliasAnalysis>();
1749 AU.addRequired<DominatorTreeWrapperPass>();
1750 AU.addRequired<LoopInfoWrapperPass>();
1752 AU.setPreservesAll();
1755 char LoopAccessAnalysis::ID = 0;
1756 static const char laa_name[] = "Loop Access Analysis";
1757 #define LAA_NAME "loop-accesses"
1759 INITIALIZE_PASS_BEGIN(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1760 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1761 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1762 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1763 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
1764 INITIALIZE_PASS_END(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1767 Pass *createLAAPass() {
1768 return new LoopAccessAnalysis();