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/ValueTracking.h"
19 #include "llvm/IR/DiagnosticInfo.h"
20 #include "llvm/IR/Dominators.h"
21 #include "llvm/IR/IRBuilder.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Transforms/Utils/VectorUtils.h"
26 #define DEBUG_TYPE "loop-accesses"
28 static cl::opt<unsigned, true>
29 VectorizationFactor("force-vector-width", cl::Hidden,
30 cl::desc("Sets the SIMD width. Zero is autoselect."),
31 cl::location(VectorizerParams::VectorizationFactor));
32 unsigned VectorizerParams::VectorizationFactor = 0;
34 static cl::opt<unsigned, true>
35 VectorizationInterleave("force-vector-interleave", cl::Hidden,
36 cl::desc("Sets the vectorization interleave count. "
37 "Zero is autoselect."),
39 VectorizerParams::VectorizationInterleave));
40 unsigned VectorizerParams::VectorizationInterleave = 0;
42 /// When performing memory disambiguation checks at runtime do not make more
43 /// than this number of comparisons.
44 const unsigned VectorizerParams::RuntimeMemoryCheckThreshold = 8;
46 /// Maximum SIMD width.
47 const unsigned VectorizerParams::MaxVectorWidth = 64;
49 bool VectorizerParams::isInterleaveForced() {
50 return ::VectorizationInterleave.getNumOccurrences() > 0;
53 void LoopAccessReport::emitAnalysis(const LoopAccessReport &Message,
54 const Function *TheFunction,
56 const char *PassName) {
57 DebugLoc DL = TheLoop->getStartLoc();
58 if (const Instruction *I = Message.getInstr())
59 DL = I->getDebugLoc();
60 emitOptimizationRemarkAnalysis(TheFunction->getContext(), PassName,
61 *TheFunction, DL, Message.str());
64 Value *llvm::stripIntegerCast(Value *V) {
65 if (CastInst *CI = dyn_cast<CastInst>(V))
66 if (CI->getOperand(0)->getType()->isIntegerTy())
67 return CI->getOperand(0);
71 const SCEV *llvm::replaceSymbolicStrideSCEV(ScalarEvolution *SE,
72 ValueToValueMap &PtrToStride,
73 Value *Ptr, Value *OrigPtr) {
75 const SCEV *OrigSCEV = SE->getSCEV(Ptr);
77 // If there is an entry in the map return the SCEV of the pointer with the
78 // symbolic stride replaced by one.
79 ValueToValueMap::iterator SI = PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
80 if (SI != PtrToStride.end()) {
81 Value *StrideVal = SI->second;
84 StrideVal = stripIntegerCast(StrideVal);
86 // Replace symbolic stride by one.
87 Value *One = ConstantInt::get(StrideVal->getType(), 1);
88 ValueToValueMap RewriteMap;
89 RewriteMap[StrideVal] = One;
92 SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
93 DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
98 // Otherwise, just return the SCEV of the original pointer.
99 return SE->getSCEV(Ptr);
102 void LoopAccessInfo::RuntimePointerCheck::insert(ScalarEvolution *SE, Loop *Lp,
103 Value *Ptr, bool WritePtr,
106 ValueToValueMap &Strides) {
107 // Get the stride replaced scev.
108 const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
109 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
110 assert(AR && "Invalid addrec expression");
111 const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
112 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
113 Pointers.push_back(Ptr);
114 Starts.push_back(AR->getStart());
115 Ends.push_back(ScEnd);
116 IsWritePtr.push_back(WritePtr);
117 DependencySetId.push_back(DepSetId);
118 AliasSetId.push_back(ASId);
121 bool LoopAccessInfo::RuntimePointerCheck::needsChecking(unsigned I,
123 // No need to check if two readonly pointers intersect.
124 if (!IsWritePtr[I] && !IsWritePtr[J])
127 // Only need to check pointers between two different dependency sets.
128 if (DependencySetId[I] == DependencySetId[J])
131 // Only need to check pointers in the same alias set.
132 if (AliasSetId[I] != AliasSetId[J])
139 /// \brief Analyses memory accesses in a loop.
141 /// Checks whether run time pointer checks are needed and builds sets for data
142 /// dependence checking.
143 class AccessAnalysis {
145 /// \brief Read or write access location.
146 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
147 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
149 /// \brief Set of potential dependent memory accesses.
150 typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
152 AccessAnalysis(const DataLayout *Dl, AliasAnalysis *AA, DepCandidates &DA) :
153 DL(Dl), AST(*AA), DepCands(DA), IsRTCheckNeeded(false) {}
155 /// \brief Register a load and whether it is only read from.
156 void addLoad(AliasAnalysis::Location &Loc, bool IsReadOnly) {
157 Value *Ptr = const_cast<Value*>(Loc.Ptr);
158 AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
159 Accesses.insert(MemAccessInfo(Ptr, false));
161 ReadOnlyPtr.insert(Ptr);
164 /// \brief Register a store.
165 void addStore(AliasAnalysis::Location &Loc) {
166 Value *Ptr = const_cast<Value*>(Loc.Ptr);
167 AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
168 Accesses.insert(MemAccessInfo(Ptr, true));
171 /// \brief Check whether we can check the pointers at runtime for
172 /// non-intersection.
173 bool canCheckPtrAtRT(LoopAccessInfo::RuntimePointerCheck &RtCheck,
174 unsigned &NumComparisons,
175 ScalarEvolution *SE, Loop *TheLoop,
176 ValueToValueMap &Strides,
177 bool ShouldCheckStride = false);
179 /// \brief Goes over all memory accesses, checks whether a RT check is needed
180 /// and builds sets of dependent accesses.
181 void buildDependenceSets() {
182 processMemAccesses();
185 bool isRTCheckNeeded() { return IsRTCheckNeeded; }
187 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
188 void resetDepChecks() { CheckDeps.clear(); }
190 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
193 typedef SetVector<MemAccessInfo> PtrAccessSet;
195 /// \brief Go over all memory access and check whether runtime pointer checks
196 /// are needed /// and build sets of dependency check candidates.
197 void processMemAccesses();
199 /// Set of all accesses.
200 PtrAccessSet Accesses;
202 /// Set of accesses that need a further dependence check.
203 MemAccessInfoSet CheckDeps;
205 /// Set of pointers that are read only.
206 SmallPtrSet<Value*, 16> ReadOnlyPtr;
208 const DataLayout *DL;
210 /// An alias set tracker to partition the access set by underlying object and
211 //intrinsic property (such as TBAA metadata).
214 /// Sets of potentially dependent accesses - members of one set share an
215 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
216 /// dependence check.
217 DepCandidates &DepCands;
219 bool IsRTCheckNeeded;
222 } // end anonymous namespace
224 /// \brief Check whether a pointer can participate in a runtime bounds check.
225 static bool hasComputableBounds(ScalarEvolution *SE, ValueToValueMap &Strides,
227 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
228 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
232 return AR->isAffine();
235 /// \brief Check the stride of the pointer and ensure that it does not wrap in
236 /// the address space.
237 static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
238 const Loop *Lp, ValueToValueMap &StridesMap);
240 bool AccessAnalysis::canCheckPtrAtRT(
241 LoopAccessInfo::RuntimePointerCheck &RtCheck,
242 unsigned &NumComparisons, ScalarEvolution *SE, Loop *TheLoop,
243 ValueToValueMap &StridesMap, bool ShouldCheckStride) {
244 // Find pointers with computable bounds. We are going to use this information
245 // to place a runtime bound check.
248 bool IsDepCheckNeeded = isDependencyCheckNeeded();
251 // We assign a consecutive id to access from different alias sets.
252 // Accesses between different groups doesn't need to be checked.
254 for (auto &AS : AST) {
255 unsigned NumReadPtrChecks = 0;
256 unsigned NumWritePtrChecks = 0;
258 // We assign consecutive id to access from different dependence sets.
259 // Accesses within the same set don't need a runtime check.
260 unsigned RunningDepId = 1;
261 DenseMap<Value *, unsigned> DepSetId;
264 Value *Ptr = A.getValue();
265 bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
266 MemAccessInfo Access(Ptr, IsWrite);
273 if (hasComputableBounds(SE, StridesMap, Ptr) &&
274 // When we run after a failing dependency check we have to make sure we
275 // don't have wrapping pointers.
276 (!ShouldCheckStride ||
277 isStridedPtr(SE, DL, Ptr, TheLoop, StridesMap) == 1)) {
278 // The id of the dependence set.
281 if (IsDepCheckNeeded) {
282 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
283 unsigned &LeaderId = DepSetId[Leader];
285 LeaderId = RunningDepId++;
288 // Each access has its own dependence set.
289 DepId = RunningDepId++;
291 RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap);
293 DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
299 if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
300 NumComparisons += 0; // Only one dependence set.
302 NumComparisons += (NumWritePtrChecks * (NumReadPtrChecks +
303 NumWritePtrChecks - 1));
309 // If the pointers that we would use for the bounds comparison have different
310 // address spaces, assume the values aren't directly comparable, so we can't
311 // use them for the runtime check. We also have to assume they could
312 // overlap. In the future there should be metadata for whether address spaces
314 unsigned NumPointers = RtCheck.Pointers.size();
315 for (unsigned i = 0; i < NumPointers; ++i) {
316 for (unsigned j = i + 1; j < NumPointers; ++j) {
317 // Only need to check pointers between two different dependency sets.
318 if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
320 // Only need to check pointers in the same alias set.
321 if (RtCheck.AliasSetId[i] != RtCheck.AliasSetId[j])
324 Value *PtrI = RtCheck.Pointers[i];
325 Value *PtrJ = RtCheck.Pointers[j];
327 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
328 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
330 DEBUG(dbgs() << "LAA: Runtime check would require comparison between"
331 " different address spaces\n");
340 void AccessAnalysis::processMemAccesses() {
341 // We process the set twice: first we process read-write pointers, last we
342 // process read-only pointers. This allows us to skip dependence tests for
343 // read-only pointers.
345 DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
346 DEBUG(dbgs() << " AST: "; AST.dump());
347 DEBUG(dbgs() << "LAA: Accesses:\n");
349 for (auto A : Accesses)
350 dbgs() << "\t" << *A.getPointer() << " (" <<
351 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
352 "read-only" : "read")) << ")\n";
355 // The AliasSetTracker has nicely partitioned our pointers by metadata
356 // compatibility and potential for underlying-object overlap. As a result, we
357 // only need to check for potential pointer dependencies within each alias
359 for (auto &AS : AST) {
360 // Note that both the alias-set tracker and the alias sets themselves used
361 // linked lists internally and so the iteration order here is deterministic
362 // (matching the original instruction order within each set).
364 bool SetHasWrite = false;
366 // Map of pointers to last access encountered.
367 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
368 UnderlyingObjToAccessMap ObjToLastAccess;
370 // Set of access to check after all writes have been processed.
371 PtrAccessSet DeferredAccesses;
373 // Iterate over each alias set twice, once to process read/write pointers,
374 // and then to process read-only pointers.
375 for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
376 bool UseDeferred = SetIteration > 0;
377 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
380 Value *Ptr = AV.getValue();
382 // For a single memory access in AliasSetTracker, Accesses may contain
383 // both read and write, and they both need to be handled for CheckDeps.
385 if (AC.getPointer() != Ptr)
388 bool IsWrite = AC.getInt();
390 // If we're using the deferred access set, then it contains only
392 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
393 if (UseDeferred && !IsReadOnlyPtr)
395 // Otherwise, the pointer must be in the PtrAccessSet, either as a
397 assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
398 S.count(MemAccessInfo(Ptr, false))) &&
399 "Alias-set pointer not in the access set?");
401 MemAccessInfo Access(Ptr, IsWrite);
402 DepCands.insert(Access);
404 // Memorize read-only pointers for later processing and skip them in
405 // the first round (they need to be checked after we have seen all
406 // write pointers). Note: we also mark pointer that are not
407 // consecutive as "read-only" pointers (so that we check
408 // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
409 if (!UseDeferred && IsReadOnlyPtr) {
410 DeferredAccesses.insert(Access);
414 // If this is a write - check other reads and writes for conflicts. If
415 // this is a read only check other writes for conflicts (but only if
416 // there is no other write to the ptr - this is an optimization to
417 // catch "a[i] = a[i] + " without having to do a dependence check).
418 if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
419 CheckDeps.insert(Access);
420 IsRTCheckNeeded = true;
426 // Create sets of pointers connected by a shared alias set and
427 // underlying object.
428 typedef SmallVector<Value *, 16> ValueVector;
429 ValueVector TempObjects;
430 GetUnderlyingObjects(Ptr, TempObjects, DL);
431 for (Value *UnderlyingObj : TempObjects) {
432 UnderlyingObjToAccessMap::iterator Prev =
433 ObjToLastAccess.find(UnderlyingObj);
434 if (Prev != ObjToLastAccess.end())
435 DepCands.unionSets(Access, Prev->second);
437 ObjToLastAccess[UnderlyingObj] = Access;
446 /// \brief Checks memory dependences among accesses to the same underlying
447 /// object to determine whether there vectorization is legal or not (and at
448 /// which vectorization factor).
450 /// This class works under the assumption that we already checked that memory
451 /// locations with different underlying pointers are "must-not alias".
452 /// We use the ScalarEvolution framework to symbolically evalutate access
453 /// functions pairs. Since we currently don't restructure the loop we can rely
454 /// on the program order of memory accesses to determine their safety.
455 /// At the moment we will only deem accesses as safe for:
456 /// * A negative constant distance assuming program order.
458 /// Safe: tmp = a[i + 1]; OR a[i + 1] = x;
459 /// a[i] = tmp; y = a[i];
461 /// The latter case is safe because later checks guarantuee that there can't
462 /// be a cycle through a phi node (that is, we check that "x" and "y" is not
463 /// the same variable: a header phi can only be an induction or a reduction, a
464 /// reduction can't have a memory sink, an induction can't have a memory
465 /// source). This is important and must not be violated (or we have to
466 /// resort to checking for cycles through memory).
468 /// * A positive constant distance assuming program order that is bigger
469 /// than the biggest memory access.
471 /// tmp = a[i] OR b[i] = x
472 /// a[i+2] = tmp y = b[i+2];
474 /// Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
476 /// * Zero distances and all accesses have the same size.
478 class MemoryDepChecker {
480 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
481 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
483 MemoryDepChecker(ScalarEvolution *Se, const DataLayout *Dl, const Loop *L)
484 : SE(Se), DL(Dl), InnermostLoop(L), AccessIdx(0),
485 ShouldRetryWithRuntimeCheck(false) {}
487 /// \brief Register the location (instructions are given increasing numbers)
488 /// of a write access.
489 void addAccess(StoreInst *SI) {
490 Value *Ptr = SI->getPointerOperand();
491 Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
492 InstMap.push_back(SI);
496 /// \brief Register the location (instructions are given increasing numbers)
497 /// of a write access.
498 void addAccess(LoadInst *LI) {
499 Value *Ptr = LI->getPointerOperand();
500 Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
501 InstMap.push_back(LI);
505 /// \brief Check whether the dependencies between the accesses are safe.
507 /// Only checks sets with elements in \p CheckDeps.
508 bool areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
509 MemAccessInfoSet &CheckDeps, ValueToValueMap &Strides);
511 /// \brief The maximum number of bytes of a vector register we can vectorize
512 /// the accesses safely with.
513 unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
515 /// \brief In same cases when the dependency check fails we can still
516 /// vectorize the loop with a dynamic array access check.
517 bool shouldRetryWithRuntimeCheck() { return ShouldRetryWithRuntimeCheck; }
521 const DataLayout *DL;
522 const Loop *InnermostLoop;
524 /// \brief Maps access locations (ptr, read/write) to program order.
525 DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
527 /// \brief Memory access instructions in program order.
528 SmallVector<Instruction *, 16> InstMap;
530 /// \brief The program order index to be used for the next instruction.
533 // We can access this many bytes in parallel safely.
534 unsigned MaxSafeDepDistBytes;
536 /// \brief If we see a non-constant dependence distance we can still try to
537 /// vectorize this loop with runtime checks.
538 bool ShouldRetryWithRuntimeCheck;
540 /// \brief Check whether there is a plausible dependence between the two
543 /// Access \p A must happen before \p B in program order. The two indices
544 /// identify the index into the program order map.
546 /// This function checks whether there is a plausible dependence (or the
547 /// absence of such can't be proved) between the two accesses. If there is a
548 /// plausible dependence but the dependence distance is bigger than one
549 /// element access it records this distance in \p MaxSafeDepDistBytes (if this
550 /// distance is smaller than any other distance encountered so far).
551 /// Otherwise, this function returns true signaling a possible dependence.
552 bool isDependent(const MemAccessInfo &A, unsigned AIdx,
553 const MemAccessInfo &B, unsigned BIdx,
554 ValueToValueMap &Strides);
556 /// \brief Check whether the data dependence could prevent store-load
558 bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize);
561 } // end anonymous namespace
563 static bool isInBoundsGep(Value *Ptr) {
564 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
565 return GEP->isInBounds();
569 /// \brief Check whether the access through \p Ptr has a constant stride.
570 static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
571 const Loop *Lp, ValueToValueMap &StridesMap) {
572 const Type *Ty = Ptr->getType();
573 assert(Ty->isPointerTy() && "Unexpected non-ptr");
575 // Make sure that the pointer does not point to aggregate types.
576 const PointerType *PtrTy = cast<PointerType>(Ty);
577 if (PtrTy->getElementType()->isAggregateType()) {
578 DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type"
583 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
585 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
587 DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer "
588 << *Ptr << " SCEV: " << *PtrScev << "\n");
592 // The accesss function must stride over the innermost loop.
593 if (Lp != AR->getLoop()) {
594 DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " <<
595 *Ptr << " SCEV: " << *PtrScev << "\n");
598 // The address calculation must not wrap. Otherwise, a dependence could be
600 // An inbounds getelementptr that is a AddRec with a unit stride
601 // cannot wrap per definition. The unit stride requirement is checked later.
602 // An getelementptr without an inbounds attribute and unit stride would have
603 // to access the pointer value "0" which is undefined behavior in address
604 // space 0, therefore we can also vectorize this case.
605 bool IsInBoundsGEP = isInBoundsGep(Ptr);
606 bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
607 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
608 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
609 DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
610 << *Ptr << " SCEV: " << *PtrScev << "\n");
614 // Check the step is constant.
615 const SCEV *Step = AR->getStepRecurrence(*SE);
617 // Calculate the pointer stride and check if it is consecutive.
618 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
620 DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr <<
621 " SCEV: " << *PtrScev << "\n");
625 int64_t Size = DL->getTypeAllocSize(PtrTy->getElementType());
626 const APInt &APStepVal = C->getValue()->getValue();
628 // Huge step value - give up.
629 if (APStepVal.getBitWidth() > 64)
632 int64_t StepVal = APStepVal.getSExtValue();
635 int64_t Stride = StepVal / Size;
636 int64_t Rem = StepVal % Size;
640 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
641 // know we can't "wrap around the address space". In case of address space
642 // zero we know that this won't happen without triggering undefined behavior.
643 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
644 Stride != 1 && Stride != -1)
650 bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
651 unsigned TypeByteSize) {
652 // If loads occur at a distance that is not a multiple of a feasible vector
653 // factor store-load forwarding does not take place.
654 // Positive dependences might cause troubles because vectorizing them might
655 // prevent store-load forwarding making vectorized code run a lot slower.
656 // a[i] = a[i-3] ^ a[i-8];
657 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
658 // hence on your typical architecture store-load forwarding does not take
659 // place. Vectorizing in such cases does not make sense.
660 // Store-load forwarding distance.
661 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
662 // Maximum vector factor.
663 unsigned MaxVFWithoutSLForwardIssues =
664 VectorizerParams::MaxVectorWidth * TypeByteSize;
665 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
666 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
668 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
670 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
671 MaxVFWithoutSLForwardIssues = (vf >>=1);
676 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
677 DEBUG(dbgs() << "LAA: Distance " << Distance <<
678 " that could cause a store-load forwarding conflict\n");
682 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
683 MaxVFWithoutSLForwardIssues !=
684 VectorizerParams::MaxVectorWidth * TypeByteSize)
685 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
689 bool MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
690 const MemAccessInfo &B, unsigned BIdx,
691 ValueToValueMap &Strides) {
692 assert (AIdx < BIdx && "Must pass arguments in program order");
694 Value *APtr = A.getPointer();
695 Value *BPtr = B.getPointer();
696 bool AIsWrite = A.getInt();
697 bool BIsWrite = B.getInt();
699 // Two reads are independent.
700 if (!AIsWrite && !BIsWrite)
703 // We cannot check pointers in different address spaces.
704 if (APtr->getType()->getPointerAddressSpace() !=
705 BPtr->getType()->getPointerAddressSpace())
708 const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
709 const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
711 int StrideAPtr = isStridedPtr(SE, DL, APtr, InnermostLoop, Strides);
712 int StrideBPtr = isStridedPtr(SE, DL, BPtr, InnermostLoop, Strides);
714 const SCEV *Src = AScev;
715 const SCEV *Sink = BScev;
717 // If the induction step is negative we have to invert source and sink of the
719 if (StrideAPtr < 0) {
722 std::swap(APtr, BPtr);
723 std::swap(Src, Sink);
724 std::swap(AIsWrite, BIsWrite);
725 std::swap(AIdx, BIdx);
726 std::swap(StrideAPtr, StrideBPtr);
729 const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
731 DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
732 << "(Induction step: " << StrideAPtr << ")\n");
733 DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
734 << *InstMap[BIdx] << ": " << *Dist << "\n");
736 // Need consecutive accesses. We don't want to vectorize
737 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
738 // the address space.
739 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
740 DEBUG(dbgs() << "Non-consecutive pointer access\n");
744 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
746 DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
747 ShouldRetryWithRuntimeCheck = true;
751 Type *ATy = APtr->getType()->getPointerElementType();
752 Type *BTy = BPtr->getType()->getPointerElementType();
753 unsigned TypeByteSize = DL->getTypeAllocSize(ATy);
755 // Negative distances are not plausible dependencies.
756 const APInt &Val = C->getValue()->getValue();
757 if (Val.isNegative()) {
758 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
759 if (IsTrueDataDependence &&
760 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
764 DEBUG(dbgs() << "LAA: Dependence is negative: NoDep\n");
768 // Write to the same location with the same size.
769 // Could be improved to assert type sizes are the same (i32 == float, etc).
773 DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n");
777 assert(Val.isStrictlyPositive() && "Expect a positive value");
779 // Positive distance bigger than max vectorization factor.
782 "LAA: ReadWrite-Write positive dependency with different types\n");
786 unsigned Distance = (unsigned) Val.getZExtValue();
788 // Bail out early if passed-in parameters make vectorization not feasible.
789 unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
790 VectorizerParams::VectorizationFactor : 1);
791 unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
792 VectorizerParams::VectorizationInterleave : 1);
794 // The distance must be bigger than the size needed for a vectorized version
795 // of the operation and the size of the vectorized operation must not be
796 // bigger than the currrent maximum size.
797 if (Distance < 2*TypeByteSize ||
798 2*TypeByteSize > MaxSafeDepDistBytes ||
799 Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
800 DEBUG(dbgs() << "LAA: Failure because of Positive distance "
801 << Val.getSExtValue() << '\n');
805 MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
806 Distance : MaxSafeDepDistBytes;
808 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
809 if (IsTrueDataDependence &&
810 couldPreventStoreLoadForward(Distance, TypeByteSize))
813 DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue() <<
814 " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n');
819 bool MemoryDepChecker::areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
820 MemAccessInfoSet &CheckDeps,
821 ValueToValueMap &Strides) {
823 MaxSafeDepDistBytes = -1U;
824 while (!CheckDeps.empty()) {
825 MemAccessInfo CurAccess = *CheckDeps.begin();
827 // Get the relevant memory access set.
828 EquivalenceClasses<MemAccessInfo>::iterator I =
829 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
831 // Check accesses within this set.
832 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
833 AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
835 // Check every access pair.
837 CheckDeps.erase(*AI);
838 EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
840 // Check every accessing instruction pair in program order.
841 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
842 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
843 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
844 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
845 if (*I1 < *I2 && isDependent(*AI, *I1, *OI, *I2, Strides))
847 if (*I2 < *I1 && isDependent(*OI, *I2, *AI, *I1, Strides))
858 bool LoopAccessInfo::canAnalyzeLoop() {
859 // We can only analyze innermost loops.
860 if (!TheLoop->empty()) {
861 emitAnalysis(LoopAccessReport() << "loop is not the innermost loop");
865 // We must have a single backedge.
866 if (TheLoop->getNumBackEdges() != 1) {
868 LoopAccessReport() <<
869 "loop control flow is not understood by analyzer");
873 // We must have a single exiting block.
874 if (!TheLoop->getExitingBlock()) {
876 LoopAccessReport() <<
877 "loop control flow is not understood by analyzer");
881 // We only handle bottom-tested loops, i.e. loop in which the condition is
882 // checked at the end of each iteration. With that we can assume that all
883 // instructions in the loop are executed the same number of times.
884 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
886 LoopAccessReport() <<
887 "loop control flow is not understood by analyzer");
891 // We need to have a loop header.
892 DEBUG(dbgs() << "LAA: Found a loop: " <<
893 TheLoop->getHeader()->getName() << '\n');
895 // ScalarEvolution needs to be able to find the exit count.
896 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
897 if (ExitCount == SE->getCouldNotCompute()) {
898 emitAnalysis(LoopAccessReport() <<
899 "could not determine number of loop iterations");
900 DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
907 void LoopAccessInfo::analyzeLoop(ValueToValueMap &Strides) {
909 typedef SmallVector<Value*, 16> ValueVector;
910 typedef SmallPtrSet<Value*, 16> ValueSet;
912 // Holds the Load and Store *instructions*.
916 // Holds all the different accesses in the loop.
917 unsigned NumReads = 0;
918 unsigned NumReadWrites = 0;
920 PtrRtCheck.Pointers.clear();
921 PtrRtCheck.Need = false;
923 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
924 MemoryDepChecker DepChecker(SE, DL, TheLoop);
927 for (Loop::block_iterator bb = TheLoop->block_begin(),
928 be = TheLoop->block_end(); bb != be; ++bb) {
930 // Scan the BB and collect legal loads and stores.
931 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
934 // If this is a load, save it. If this instruction can read from memory
935 // but is not a load, then we quit. Notice that we don't handle function
936 // calls that read or write.
937 if (it->mayReadFromMemory()) {
938 // Many math library functions read the rounding mode. We will only
939 // vectorize a loop if it contains known function calls that don't set
940 // the flag. Therefore, it is safe to ignore this read from memory.
941 CallInst *Call = dyn_cast<CallInst>(it);
942 if (Call && getIntrinsicIDForCall(Call, TLI))
945 LoadInst *Ld = dyn_cast<LoadInst>(it);
946 if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
947 emitAnalysis(LoopAccessReport(Ld)
948 << "read with atomic ordering or volatile read");
949 DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
955 DepChecker.addAccess(Ld);
959 // Save 'store' instructions. Abort if other instructions write to memory.
960 if (it->mayWriteToMemory()) {
961 StoreInst *St = dyn_cast<StoreInst>(it);
963 emitAnalysis(LoopAccessReport(it) <<
964 "instruction cannot be vectorized");
968 if (!St->isSimple() && !IsAnnotatedParallel) {
969 emitAnalysis(LoopAccessReport(St)
970 << "write with atomic ordering or volatile write");
971 DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
976 Stores.push_back(St);
977 DepChecker.addAccess(St);
982 // Now we have two lists that hold the loads and the stores.
983 // Next, we find the pointers that they use.
985 // Check if we see any stores. If there are no stores, then we don't
986 // care if the pointers are *restrict*.
987 if (!Stores.size()) {
988 DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
993 AccessAnalysis::DepCandidates DependentAccesses;
994 AccessAnalysis Accesses(DL, AA, DependentAccesses);
996 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
997 // multiple times on the same object. If the ptr is accessed twice, once
998 // for read and once for write, it will only appear once (on the write
999 // list). This is okay, since we are going to check for conflicts between
1000 // writes and between reads and writes, but not between reads and reads.
1003 ValueVector::iterator I, IE;
1004 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1005 StoreInst *ST = cast<StoreInst>(*I);
1006 Value* Ptr = ST->getPointerOperand();
1008 if (isUniform(Ptr)) {
1010 LoopAccessReport(ST)
1011 << "write to a loop invariant address could not be vectorized");
1012 DEBUG(dbgs() << "LAA: We don't allow storing to uniform addresses\n");
1017 // If we did *not* see this pointer before, insert it to the read-write
1018 // list. At this phase it is only a 'write' list.
1019 if (Seen.insert(Ptr).second) {
1022 AliasAnalysis::Location Loc = AA->getLocation(ST);
1023 // The TBAA metadata could have a control dependency on the predication
1024 // condition, so we cannot rely on it when determining whether or not we
1025 // need runtime pointer checks.
1026 if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
1027 Loc.AATags.TBAA = nullptr;
1029 Accesses.addStore(Loc);
1033 if (IsAnnotatedParallel) {
1035 << "LAA: A loop annotated parallel, ignore memory dependency "
1041 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1042 LoadInst *LD = cast<LoadInst>(*I);
1043 Value* Ptr = LD->getPointerOperand();
1044 // If we did *not* see this pointer before, insert it to the
1045 // read list. If we *did* see it before, then it is already in
1046 // the read-write list. This allows us to vectorize expressions
1047 // such as A[i] += x; Because the address of A[i] is a read-write
1048 // pointer. This only works if the index of A[i] is consecutive.
1049 // If the address of i is unknown (for example A[B[i]]) then we may
1050 // read a few words, modify, and write a few words, and some of the
1051 // words may be written to the same address.
1052 bool IsReadOnlyPtr = false;
1053 if (Seen.insert(Ptr).second ||
1054 !isStridedPtr(SE, DL, Ptr, TheLoop, Strides)) {
1056 IsReadOnlyPtr = true;
1059 AliasAnalysis::Location Loc = AA->getLocation(LD);
1060 // The TBAA metadata could have a control dependency on the predication
1061 // condition, so we cannot rely on it when determining whether or not we
1062 // need runtime pointer checks.
1063 if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
1064 Loc.AATags.TBAA = nullptr;
1066 Accesses.addLoad(Loc, IsReadOnlyPtr);
1069 // If we write (or read-write) to a single destination and there are no
1070 // other reads in this loop then is it safe to vectorize.
1071 if (NumReadWrites == 1 && NumReads == 0) {
1072 DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
1077 // Build dependence sets and check whether we need a runtime pointer bounds
1079 Accesses.buildDependenceSets();
1080 bool NeedRTCheck = Accesses.isRTCheckNeeded();
1082 // Find pointers with computable bounds. We are going to use this information
1083 // to place a runtime bound check.
1084 unsigned NumComparisons = 0;
1085 bool CanDoRT = false;
1087 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop,
1090 DEBUG(dbgs() << "LAA: We need to do " << NumComparisons <<
1091 " pointer comparisons.\n");
1093 // If we only have one set of dependences to check pointers among we don't
1094 // need a runtime check.
1095 if (NumComparisons == 0 && NeedRTCheck)
1096 NeedRTCheck = false;
1098 // Check that we did not collect too many pointers or found an unsizeable
1101 NumComparisons > VectorizerParams::RuntimeMemoryCheckThreshold) {
1107 DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
1110 if (NeedRTCheck && !CanDoRT) {
1111 emitAnalysis(LoopAccessReport() << "cannot identify array bounds");
1112 DEBUG(dbgs() << "LAA: We can't vectorize because we can't find " <<
1113 "the array bounds.\n");
1119 PtrRtCheck.Need = NeedRTCheck;
1122 if (Accesses.isDependencyCheckNeeded()) {
1123 DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
1124 CanVecMem = DepChecker.areDepsSafe(
1125 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
1126 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
1128 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
1129 DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
1132 // Clear the dependency checks. We assume they are not needed.
1133 Accesses.resetDepChecks();
1136 PtrRtCheck.Need = true;
1138 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE,
1139 TheLoop, Strides, true);
1140 // Check that we did not collect too many pointers or found an unsizeable
1143 NumComparisons > VectorizerParams::RuntimeMemoryCheckThreshold) {
1144 if (!CanDoRT && NumComparisons > 0)
1145 emitAnalysis(LoopAccessReport()
1146 << "cannot check memory dependencies at runtime");
1148 emitAnalysis(LoopAccessReport()
1149 << NumComparisons << " exceeds limit of "
1150 << VectorizerParams::RuntimeMemoryCheckThreshold
1151 << " dependent memory operations checked at runtime");
1152 DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
1163 emitAnalysis(LoopAccessReport() <<
1164 "unsafe dependent memory operations in loop");
1166 DEBUG(dbgs() << "LAA: We" << (NeedRTCheck ? "" : " don't") <<
1167 " need a runtime memory check.\n");
1170 bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
1171 DominatorTree *DT) {
1172 assert(TheLoop->contains(BB) && "Unknown block used");
1174 // Blocks that do not dominate the latch need predication.
1175 BasicBlock* Latch = TheLoop->getLoopLatch();
1176 return !DT->dominates(BB, Latch);
1179 void LoopAccessInfo::emitAnalysis(LoopAccessReport &Message) {
1180 assert(!Report && "Multiple reports generated");
1184 bool LoopAccessInfo::isUniform(Value *V) {
1185 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1188 // FIXME: this function is currently a duplicate of the one in
1189 // LoopVectorize.cpp.
1190 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1194 if (Instruction *I = dyn_cast<Instruction>(V))
1195 return I->getParent() == Loc->getParent() ? I : nullptr;
1199 std::pair<Instruction *, Instruction *>
1200 LoopAccessInfo::addRuntimeCheck(Instruction *Loc) {
1201 Instruction *tnullptr = nullptr;
1202 if (!PtrRtCheck.Need)
1203 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1205 unsigned NumPointers = PtrRtCheck.Pointers.size();
1206 SmallVector<TrackingVH<Value> , 2> Starts;
1207 SmallVector<TrackingVH<Value> , 2> Ends;
1209 LLVMContext &Ctx = Loc->getContext();
1210 SCEVExpander Exp(*SE, "induction");
1211 Instruction *FirstInst = nullptr;
1213 for (unsigned i = 0; i < NumPointers; ++i) {
1214 Value *Ptr = PtrRtCheck.Pointers[i];
1215 const SCEV *Sc = SE->getSCEV(Ptr);
1217 if (SE->isLoopInvariant(Sc, TheLoop)) {
1218 DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" <<
1220 Starts.push_back(Ptr);
1221 Ends.push_back(Ptr);
1223 DEBUG(dbgs() << "LAA: Adding RT check for range:" << *Ptr << '\n');
1224 unsigned AS = Ptr->getType()->getPointerAddressSpace();
1226 // Use this type for pointer arithmetic.
1227 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1229 Value *Start = Exp.expandCodeFor(PtrRtCheck.Starts[i], PtrArithTy, Loc);
1230 Value *End = Exp.expandCodeFor(PtrRtCheck.Ends[i], PtrArithTy, Loc);
1231 Starts.push_back(Start);
1232 Ends.push_back(End);
1236 IRBuilder<> ChkBuilder(Loc);
1237 // Our instructions might fold to a constant.
1238 Value *MemoryRuntimeCheck = nullptr;
1239 for (unsigned i = 0; i < NumPointers; ++i) {
1240 for (unsigned j = i+1; j < NumPointers; ++j) {
1241 if (!PtrRtCheck.needsChecking(i, j))
1244 unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
1245 unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
1247 assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
1248 (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
1249 "Trying to bounds check pointers with different address spaces");
1251 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1252 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
1254 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
1255 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
1256 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc");
1257 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc");
1259 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1260 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1261 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1262 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1263 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1264 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1265 if (MemoryRuntimeCheck) {
1266 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1268 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1270 MemoryRuntimeCheck = IsConflict;
1274 // We have to do this trickery because the IRBuilder might fold the check to a
1275 // constant expression in which case there is no Instruction anchored in a
1277 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1278 ConstantInt::getTrue(Ctx));
1279 ChkBuilder.Insert(Check, "memcheck.conflict");
1280 FirstInst = getFirstInst(FirstInst, Check, Loc);
1281 return std::make_pair(FirstInst, Check);
1284 LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
1285 const DataLayout *DL,
1286 const TargetLibraryInfo *TLI, AliasAnalysis *AA,
1287 DominatorTree *DT, ValueToValueMap &Strides)
1288 : TheLoop(L), SE(SE), DL(DL), TLI(TLI), AA(AA), DT(DT), NumLoads(0),
1289 NumStores(0), MaxSafeDepDistBytes(-1U), CanVecMem(false) {
1290 if (canAnalyzeLoop())
1291 analyzeLoop(Strides);
1294 LoopAccessInfo &LoopAccessAnalysis::getInfo(Loop *L, ValueToValueMap &Strides) {
1295 auto &LAI = LoopAccessInfoMap[L];
1298 assert((!LAI || LAI->NumSymbolicStrides == Strides.size()) &&
1299 "Symbolic strides changed for loop");
1303 LAI = llvm::make_unique<LoopAccessInfo>(L, SE, DL, TLI, AA, DT, Strides);
1305 LAI->NumSymbolicStrides = Strides.size();
1311 bool LoopAccessAnalysis::runOnFunction(Function &F) {
1312 SE = &getAnalysis<ScalarEvolution>();
1313 DL = F.getParent()->getDataLayout();
1314 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1315 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1316 AA = &getAnalysis<AliasAnalysis>();
1317 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1322 void LoopAccessAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
1323 AU.addRequired<ScalarEvolution>();
1324 AU.addRequired<AliasAnalysis>();
1325 AU.addRequired<DominatorTreeWrapperPass>();
1327 AU.setPreservesAll();
1330 char LoopAccessAnalysis::ID = 0;
1331 static const char laa_name[] = "Loop Access Analysis";
1332 #define LAA_NAME "loop-accesses"
1334 INITIALIZE_PASS_BEGIN(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1335 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1336 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1337 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1338 INITIALIZE_PASS_END(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1341 Pass *createLAAPass() {
1342 return new LoopAccessAnalysis();