10b57cec5SDimitry Andric //===- LoopAccessAnalysis.cpp - Loop Access Analysis Implementation --------==//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // The implementation for the loop memory dependence that was originally
100b57cec5SDimitry Andric // developed for the loop vectorizer.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric
140b57cec5SDimitry Andric #include "llvm/Analysis/LoopAccessAnalysis.h"
150b57cec5SDimitry Andric #include "llvm/ADT/APInt.h"
160b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
170b57cec5SDimitry Andric #include "llvm/ADT/EquivalenceClasses.h"
180b57cec5SDimitry Andric #include "llvm/ADT/PointerIntPair.h"
190b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
200b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h"
210b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
220b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
230b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
240b57cec5SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
250b57cec5SDimitry Andric #include "llvm/Analysis/AliasSetTracker.h"
260b57cec5SDimitry Andric #include "llvm/Analysis/LoopAnalysisManager.h"
270b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
28bdd1243dSDimitry Andric #include "llvm/Analysis/LoopIterator.h"
290b57cec5SDimitry Andric #include "llvm/Analysis/MemoryLocation.h"
300b57cec5SDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h"
310b57cec5SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
320b57cec5SDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpressions.h"
330b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
340b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
350b57cec5SDimitry Andric #include "llvm/Analysis/VectorUtils.h"
360b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
370b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
380b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
390b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
400b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
410b57cec5SDimitry Andric #include "llvm/IR/DiagnosticInfo.h"
420b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
430b57cec5SDimitry Andric #include "llvm/IR/Function.h"
44fe013be4SDimitry Andric #include "llvm/IR/GetElementPtrTypeIterator.h"
450b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
460b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
470b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
480b57cec5SDimitry Andric #include "llvm/IR/Operator.h"
490b57cec5SDimitry Andric #include "llvm/IR/PassManager.h"
5081ad6265SDimitry Andric #include "llvm/IR/PatternMatch.h"
510b57cec5SDimitry Andric #include "llvm/IR/Type.h"
520b57cec5SDimitry Andric #include "llvm/IR/Value.h"
530b57cec5SDimitry Andric #include "llvm/IR/ValueHandle.h"
540b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
550b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
560b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
570b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
580b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
590b57cec5SDimitry Andric #include <algorithm>
600b57cec5SDimitry Andric #include <cassert>
610b57cec5SDimitry Andric #include <cstdint>
620b57cec5SDimitry Andric #include <iterator>
630b57cec5SDimitry Andric #include <utility>
64c9157d92SDimitry Andric #include <variant>
650b57cec5SDimitry Andric #include <vector>
660b57cec5SDimitry Andric
670b57cec5SDimitry Andric using namespace llvm;
6881ad6265SDimitry Andric using namespace llvm::PatternMatch;
690b57cec5SDimitry Andric
700b57cec5SDimitry Andric #define DEBUG_TYPE "loop-accesses"
710b57cec5SDimitry Andric
720b57cec5SDimitry Andric static cl::opt<unsigned, true>
730b57cec5SDimitry Andric VectorizationFactor("force-vector-width", cl::Hidden,
740b57cec5SDimitry Andric cl::desc("Sets the SIMD width. Zero is autoselect."),
750b57cec5SDimitry Andric cl::location(VectorizerParams::VectorizationFactor));
760b57cec5SDimitry Andric unsigned VectorizerParams::VectorizationFactor;
770b57cec5SDimitry Andric
780b57cec5SDimitry Andric static cl::opt<unsigned, true>
790b57cec5SDimitry Andric VectorizationInterleave("force-vector-interleave", cl::Hidden,
800b57cec5SDimitry Andric cl::desc("Sets the vectorization interleave count. "
810b57cec5SDimitry Andric "Zero is autoselect."),
820b57cec5SDimitry Andric cl::location(
830b57cec5SDimitry Andric VectorizerParams::VectorizationInterleave));
840b57cec5SDimitry Andric unsigned VectorizerParams::VectorizationInterleave;
850b57cec5SDimitry Andric
860b57cec5SDimitry Andric static cl::opt<unsigned, true> RuntimeMemoryCheckThreshold(
870b57cec5SDimitry Andric "runtime-memory-check-threshold", cl::Hidden,
880b57cec5SDimitry Andric cl::desc("When performing memory disambiguation checks at runtime do not "
890b57cec5SDimitry Andric "generate more than this number of comparisons (default = 8)."),
900b57cec5SDimitry Andric cl::location(VectorizerParams::RuntimeMemoryCheckThreshold), cl::init(8));
910b57cec5SDimitry Andric unsigned VectorizerParams::RuntimeMemoryCheckThreshold;
920b57cec5SDimitry Andric
930b57cec5SDimitry Andric /// The maximum iterations used to merge memory checks
940b57cec5SDimitry Andric static cl::opt<unsigned> MemoryCheckMergeThreshold(
950b57cec5SDimitry Andric "memory-check-merge-threshold", cl::Hidden,
960b57cec5SDimitry Andric cl::desc("Maximum number of comparisons done when trying to merge "
970b57cec5SDimitry Andric "runtime memory checks. (default = 100)"),
980b57cec5SDimitry Andric cl::init(100));
990b57cec5SDimitry Andric
1000b57cec5SDimitry Andric /// Maximum SIMD width.
1010b57cec5SDimitry Andric const unsigned VectorizerParams::MaxVectorWidth = 64;
1020b57cec5SDimitry Andric
1030b57cec5SDimitry Andric /// We collect dependences up to this threshold.
1040b57cec5SDimitry Andric static cl::opt<unsigned>
1050b57cec5SDimitry Andric MaxDependences("max-dependences", cl::Hidden,
1060b57cec5SDimitry Andric cl::desc("Maximum number of dependences collected by "
1070b57cec5SDimitry Andric "loop-access analysis (default = 100)"),
1080b57cec5SDimitry Andric cl::init(100));
1090b57cec5SDimitry Andric
1100b57cec5SDimitry Andric /// This enables versioning on the strides of symbolically striding memory
1110b57cec5SDimitry Andric /// accesses in code like the following.
1120b57cec5SDimitry Andric /// for (i = 0; i < N; ++i)
1130b57cec5SDimitry Andric /// A[i * Stride1] += B[i * Stride2] ...
1140b57cec5SDimitry Andric ///
1150b57cec5SDimitry Andric /// Will be roughly translated to
1160b57cec5SDimitry Andric /// if (Stride1 == 1 && Stride2 == 1) {
1170b57cec5SDimitry Andric /// for (i = 0; i < N; i+=4)
1180b57cec5SDimitry Andric /// A[i:i+3] += ...
1190b57cec5SDimitry Andric /// } else
1200b57cec5SDimitry Andric /// ...
1210b57cec5SDimitry Andric static cl::opt<bool> EnableMemAccessVersioning(
1220b57cec5SDimitry Andric "enable-mem-access-versioning", cl::init(true), cl::Hidden,
1230b57cec5SDimitry Andric cl::desc("Enable symbolic stride memory access versioning"));
1240b57cec5SDimitry Andric
1250b57cec5SDimitry Andric /// Enable store-to-load forwarding conflict detection. This option can
1260b57cec5SDimitry Andric /// be disabled for correctness testing.
1270b57cec5SDimitry Andric static cl::opt<bool> EnableForwardingConflictDetection(
1280b57cec5SDimitry Andric "store-to-load-forwarding-conflict-detection", cl::Hidden,
1290b57cec5SDimitry Andric cl::desc("Enable conflict detection in loop-access analysis"),
1300b57cec5SDimitry Andric cl::init(true));
1310b57cec5SDimitry Andric
132fcaf7f86SDimitry Andric static cl::opt<unsigned> MaxForkedSCEVDepth(
133fcaf7f86SDimitry Andric "max-forked-scev-depth", cl::Hidden,
134fcaf7f86SDimitry Andric cl::desc("Maximum recursion depth when finding forked SCEVs (default = 5)"),
135fcaf7f86SDimitry Andric cl::init(5));
136fcaf7f86SDimitry Andric
137fe013be4SDimitry Andric static cl::opt<bool> SpeculateUnitStride(
138fe013be4SDimitry Andric "laa-speculate-unit-stride", cl::Hidden,
139fe013be4SDimitry Andric cl::desc("Speculate that non-constant strides are unit in LAA"),
140fe013be4SDimitry Andric cl::init(true));
141fe013be4SDimitry Andric
142c9157d92SDimitry Andric static cl::opt<bool, true> HoistRuntimeChecks(
143c9157d92SDimitry Andric "hoist-runtime-checks", cl::Hidden,
144c9157d92SDimitry Andric cl::desc(
145c9157d92SDimitry Andric "Hoist inner loop runtime memory checks to outer loop if possible"),
146e710425bSDimitry Andric cl::location(VectorizerParams::HoistRuntimeChecks), cl::init(true));
147c9157d92SDimitry Andric bool VectorizerParams::HoistRuntimeChecks;
148c9157d92SDimitry Andric
isInterleaveForced()1490b57cec5SDimitry Andric bool VectorizerParams::isInterleaveForced() {
1500b57cec5SDimitry Andric return ::VectorizationInterleave.getNumOccurrences() > 0;
1510b57cec5SDimitry Andric }
1520b57cec5SDimitry Andric
replaceSymbolicStrideSCEV(PredicatedScalarEvolution & PSE,const DenseMap<Value *,const SCEV * > & PtrToStride,Value * Ptr)1530b57cec5SDimitry Andric const SCEV *llvm::replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE,
154fe013be4SDimitry Andric const DenseMap<Value *, const SCEV *> &PtrToStride,
155349cc55cSDimitry Andric Value *Ptr) {
1560b57cec5SDimitry Andric const SCEV *OrigSCEV = PSE.getSCEV(Ptr);
1570b57cec5SDimitry Andric
1580b57cec5SDimitry Andric // If there is an entry in the map return the SCEV of the pointer with the
1590b57cec5SDimitry Andric // symbolic stride replaced by one.
160fe013be4SDimitry Andric DenseMap<Value *, const SCEV *>::const_iterator SI = PtrToStride.find(Ptr);
161e8d8bef9SDimitry Andric if (SI == PtrToStride.end())
162e8d8bef9SDimitry Andric // For a non-symbolic stride, just return the original expression.
163e8d8bef9SDimitry Andric return OrigSCEV;
1640b57cec5SDimitry Andric
165fe013be4SDimitry Andric const SCEV *StrideSCEV = SI->second;
166fe013be4SDimitry Andric // Note: This assert is both overly strong and overly weak. The actual
167fe013be4SDimitry Andric // invariant here is that StrideSCEV should be loop invariant. The only
168fe013be4SDimitry Andric // such invariant strides we happen to speculate right now are unknowns
169fe013be4SDimitry Andric // and thus this is a reasonable proxy of the actual invariant.
170fe013be4SDimitry Andric assert(isa<SCEVUnknown>(StrideSCEV) && "shouldn't be in map");
1710b57cec5SDimitry Andric
1720b57cec5SDimitry Andric ScalarEvolution *SE = PSE.getSE();
173fe013be4SDimitry Andric const auto *CT = SE->getOne(StrideSCEV->getType());
174fe013be4SDimitry Andric PSE.addPredicate(*SE->getEqualPredicate(StrideSCEV, CT));
1750b57cec5SDimitry Andric auto *Expr = PSE.getSCEV(Ptr);
1760b57cec5SDimitry Andric
1770b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV
1780b57cec5SDimitry Andric << " by: " << *Expr << "\n");
1790b57cec5SDimitry Andric return Expr;
1800b57cec5SDimitry Andric }
1810b57cec5SDimitry Andric
RuntimeCheckingPtrGroup(unsigned Index,RuntimePointerChecking & RtCheck)1825ffd83dbSDimitry Andric RuntimeCheckingPtrGroup::RuntimeCheckingPtrGroup(
1835ffd83dbSDimitry Andric unsigned Index, RuntimePointerChecking &RtCheck)
184fe6060f1SDimitry Andric : High(RtCheck.Pointers[Index].End), Low(RtCheck.Pointers[Index].Start),
185fe6060f1SDimitry Andric AddressSpace(RtCheck.Pointers[Index]
186fe6060f1SDimitry Andric .PointerValue->getType()
18781ad6265SDimitry Andric ->getPointerAddressSpace()),
18881ad6265SDimitry Andric NeedsFreeze(RtCheck.Pointers[Index].NeedsFreeze) {
1895ffd83dbSDimitry Andric Members.push_back(Index);
1905ffd83dbSDimitry Andric }
1915ffd83dbSDimitry Andric
1920b57cec5SDimitry Andric /// Calculate Start and End points of memory access.
1930b57cec5SDimitry Andric /// Let's assume A is the first access and B is a memory access on N-th loop
1940b57cec5SDimitry Andric /// iteration. Then B is calculated as:
1950b57cec5SDimitry Andric /// B = A + Step*N .
1960b57cec5SDimitry Andric /// Step value may be positive or negative.
1970b57cec5SDimitry Andric /// N is a calculated back-edge taken count:
1980b57cec5SDimitry Andric /// N = (TripCount > 0) ? RoundDown(TripCount -1 , VF) : 0
1990b57cec5SDimitry Andric /// Start and End points are calculated in the following way:
2000b57cec5SDimitry Andric /// Start = UMIN(A, B) ; End = UMAX(A, B) + SizeOfElt,
2010b57cec5SDimitry Andric /// where SizeOfElt is the size of single memory access in bytes.
2020b57cec5SDimitry Andric ///
2030b57cec5SDimitry Andric /// There is no conflict when the intervals are disjoint:
2040b57cec5SDimitry Andric /// NoConflict = (P2.Start >= P1.End) || (P1.Start >= P2.End)
insert(Loop * Lp,Value * Ptr,const SCEV * PtrExpr,Type * AccessTy,bool WritePtr,unsigned DepSetId,unsigned ASId,PredicatedScalarEvolution & PSE,bool NeedsFreeze)20581ad6265SDimitry Andric void RuntimePointerChecking::insert(Loop *Lp, Value *Ptr, const SCEV *PtrExpr,
20681ad6265SDimitry Andric Type *AccessTy, bool WritePtr,
2070b57cec5SDimitry Andric unsigned DepSetId, unsigned ASId,
20881ad6265SDimitry Andric PredicatedScalarEvolution &PSE,
20981ad6265SDimitry Andric bool NeedsFreeze) {
2100b57cec5SDimitry Andric ScalarEvolution *SE = PSE.getSE();
2110b57cec5SDimitry Andric
2120b57cec5SDimitry Andric const SCEV *ScStart;
2130b57cec5SDimitry Andric const SCEV *ScEnd;
2140b57cec5SDimitry Andric
21581ad6265SDimitry Andric if (SE->isLoopInvariant(PtrExpr, Lp)) {
21681ad6265SDimitry Andric ScStart = ScEnd = PtrExpr;
217fe6060f1SDimitry Andric } else {
21881ad6265SDimitry Andric const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrExpr);
2190b57cec5SDimitry Andric assert(AR && "Invalid addrec expression");
2200b57cec5SDimitry Andric const SCEV *Ex = PSE.getBackedgeTakenCount();
2210b57cec5SDimitry Andric
2220b57cec5SDimitry Andric ScStart = AR->getStart();
2230b57cec5SDimitry Andric ScEnd = AR->evaluateAtIteration(Ex, *SE);
2240b57cec5SDimitry Andric const SCEV *Step = AR->getStepRecurrence(*SE);
2250b57cec5SDimitry Andric
2260b57cec5SDimitry Andric // For expressions with negative step, the upper bound is ScStart and the
2270b57cec5SDimitry Andric // lower bound is ScEnd.
2280b57cec5SDimitry Andric if (const auto *CStep = dyn_cast<SCEVConstant>(Step)) {
2290b57cec5SDimitry Andric if (CStep->getValue()->isNegative())
2300b57cec5SDimitry Andric std::swap(ScStart, ScEnd);
2310b57cec5SDimitry Andric } else {
2320b57cec5SDimitry Andric // Fallback case: the step is not constant, but we can still
2330b57cec5SDimitry Andric // get the upper and lower bounds of the interval by using min/max
2340b57cec5SDimitry Andric // expressions.
2350b57cec5SDimitry Andric ScStart = SE->getUMinExpr(ScStart, ScEnd);
2360b57cec5SDimitry Andric ScEnd = SE->getUMaxExpr(AR->getStart(), ScEnd);
2370b57cec5SDimitry Andric }
238fe6060f1SDimitry Andric }
239fe013be4SDimitry Andric assert(SE->isLoopInvariant(ScStart, Lp) && "ScStart needs to be invariant");
240fe013be4SDimitry Andric assert(SE->isLoopInvariant(ScEnd, Lp)&& "ScEnd needs to be invariant");
241fe013be4SDimitry Andric
2420b57cec5SDimitry Andric // Add the size of the pointed element to ScEnd.
243e8d8bef9SDimitry Andric auto &DL = Lp->getHeader()->getModule()->getDataLayout();
244e8d8bef9SDimitry Andric Type *IdxTy = DL.getIndexType(Ptr->getType());
24581ad6265SDimitry Andric const SCEV *EltSizeSCEV = SE->getStoreSizeOfExpr(IdxTy, AccessTy);
2460b57cec5SDimitry Andric ScEnd = SE->getAddExpr(ScEnd, EltSizeSCEV);
2470b57cec5SDimitry Andric
24881ad6265SDimitry Andric Pointers.emplace_back(Ptr, ScStart, ScEnd, WritePtr, DepSetId, ASId, PtrExpr,
24981ad6265SDimitry Andric NeedsFreeze);
2500b57cec5SDimitry Andric }
2510b57cec5SDimitry Andric
tryToCreateDiffCheck(const RuntimeCheckingPtrGroup & CGI,const RuntimeCheckingPtrGroup & CGJ)25281ad6265SDimitry Andric void RuntimePointerChecking::tryToCreateDiffCheck(
25381ad6265SDimitry Andric const RuntimeCheckingPtrGroup &CGI, const RuntimeCheckingPtrGroup &CGJ) {
25481ad6265SDimitry Andric if (!CanUseDiffCheck)
25581ad6265SDimitry Andric return;
25681ad6265SDimitry Andric
25781ad6265SDimitry Andric // If either group contains multiple different pointers, bail out.
25881ad6265SDimitry Andric // TODO: Support multiple pointers by using the minimum or maximum pointer,
25981ad6265SDimitry Andric // depending on src & sink.
26081ad6265SDimitry Andric if (CGI.Members.size() != 1 || CGJ.Members.size() != 1) {
26181ad6265SDimitry Andric CanUseDiffCheck = false;
26281ad6265SDimitry Andric return;
26381ad6265SDimitry Andric }
26481ad6265SDimitry Andric
26581ad6265SDimitry Andric PointerInfo *Src = &Pointers[CGI.Members[0]];
26681ad6265SDimitry Andric PointerInfo *Sink = &Pointers[CGJ.Members[0]];
26781ad6265SDimitry Andric
26881ad6265SDimitry Andric // If either pointer is read and written, multiple checks may be needed. Bail
26981ad6265SDimitry Andric // out.
27081ad6265SDimitry Andric if (!DC.getOrderForAccess(Src->PointerValue, !Src->IsWritePtr).empty() ||
27181ad6265SDimitry Andric !DC.getOrderForAccess(Sink->PointerValue, !Sink->IsWritePtr).empty()) {
27281ad6265SDimitry Andric CanUseDiffCheck = false;
27381ad6265SDimitry Andric return;
27481ad6265SDimitry Andric }
27581ad6265SDimitry Andric
27681ad6265SDimitry Andric ArrayRef<unsigned> AccSrc =
27781ad6265SDimitry Andric DC.getOrderForAccess(Src->PointerValue, Src->IsWritePtr);
27881ad6265SDimitry Andric ArrayRef<unsigned> AccSink =
27981ad6265SDimitry Andric DC.getOrderForAccess(Sink->PointerValue, Sink->IsWritePtr);
28081ad6265SDimitry Andric // If either pointer is accessed multiple times, there may not be a clear
28181ad6265SDimitry Andric // src/sink relation. Bail out for now.
28281ad6265SDimitry Andric if (AccSrc.size() != 1 || AccSink.size() != 1) {
28381ad6265SDimitry Andric CanUseDiffCheck = false;
28481ad6265SDimitry Andric return;
28581ad6265SDimitry Andric }
28681ad6265SDimitry Andric // If the sink is accessed before src, swap src/sink.
28781ad6265SDimitry Andric if (AccSink[0] < AccSrc[0])
28881ad6265SDimitry Andric std::swap(Src, Sink);
28981ad6265SDimitry Andric
29081ad6265SDimitry Andric auto *SrcAR = dyn_cast<SCEVAddRecExpr>(Src->Expr);
29181ad6265SDimitry Andric auto *SinkAR = dyn_cast<SCEVAddRecExpr>(Sink->Expr);
292a4a491e2SDimitry Andric if (!SrcAR || !SinkAR || SrcAR->getLoop() != DC.getInnermostLoop() ||
293a4a491e2SDimitry Andric SinkAR->getLoop() != DC.getInnermostLoop()) {
29481ad6265SDimitry Andric CanUseDiffCheck = false;
29581ad6265SDimitry Andric return;
29681ad6265SDimitry Andric }
29781ad6265SDimitry Andric
29881ad6265SDimitry Andric SmallVector<Instruction *, 4> SrcInsts =
29981ad6265SDimitry Andric DC.getInstructionsForAccess(Src->PointerValue, Src->IsWritePtr);
30081ad6265SDimitry Andric SmallVector<Instruction *, 4> SinkInsts =
30181ad6265SDimitry Andric DC.getInstructionsForAccess(Sink->PointerValue, Sink->IsWritePtr);
30281ad6265SDimitry Andric Type *SrcTy = getLoadStoreType(SrcInsts[0]);
30381ad6265SDimitry Andric Type *DstTy = getLoadStoreType(SinkInsts[0]);
304fcaf7f86SDimitry Andric if (isa<ScalableVectorType>(SrcTy) || isa<ScalableVectorType>(DstTy)) {
305fcaf7f86SDimitry Andric CanUseDiffCheck = false;
30681ad6265SDimitry Andric return;
307fcaf7f86SDimitry Andric }
308bdd1243dSDimitry Andric const DataLayout &DL =
309bdd1243dSDimitry Andric SinkAR->getLoop()->getHeader()->getModule()->getDataLayout();
31081ad6265SDimitry Andric unsigned AllocSize =
31181ad6265SDimitry Andric std::max(DL.getTypeAllocSize(SrcTy), DL.getTypeAllocSize(DstTy));
31281ad6265SDimitry Andric
31381ad6265SDimitry Andric // Only matching constant steps matching the AllocSize are supported at the
31481ad6265SDimitry Andric // moment. This simplifies the difference computation. Can be extended in the
31581ad6265SDimitry Andric // future.
31681ad6265SDimitry Andric auto *Step = dyn_cast<SCEVConstant>(SinkAR->getStepRecurrence(*SE));
31781ad6265SDimitry Andric if (!Step || Step != SrcAR->getStepRecurrence(*SE) ||
31881ad6265SDimitry Andric Step->getAPInt().abs() != AllocSize) {
31981ad6265SDimitry Andric CanUseDiffCheck = false;
32081ad6265SDimitry Andric return;
32181ad6265SDimitry Andric }
32281ad6265SDimitry Andric
323bdd1243dSDimitry Andric IntegerType *IntTy =
324bdd1243dSDimitry Andric IntegerType::get(Src->PointerValue->getContext(),
325bdd1243dSDimitry Andric DL.getPointerSizeInBits(CGI.AddressSpace));
326bdd1243dSDimitry Andric
32781ad6265SDimitry Andric // When counting down, the dependence distance needs to be swapped.
32881ad6265SDimitry Andric if (Step->getValue()->isNegative())
32981ad6265SDimitry Andric std::swap(SinkAR, SrcAR);
33081ad6265SDimitry Andric
33181ad6265SDimitry Andric const SCEV *SinkStartInt = SE->getPtrToIntExpr(SinkAR->getStart(), IntTy);
33281ad6265SDimitry Andric const SCEV *SrcStartInt = SE->getPtrToIntExpr(SrcAR->getStart(), IntTy);
33381ad6265SDimitry Andric if (isa<SCEVCouldNotCompute>(SinkStartInt) ||
33481ad6265SDimitry Andric isa<SCEVCouldNotCompute>(SrcStartInt)) {
33581ad6265SDimitry Andric CanUseDiffCheck = false;
33681ad6265SDimitry Andric return;
33781ad6265SDimitry Andric }
338c9157d92SDimitry Andric
339c9157d92SDimitry Andric const Loop *InnerLoop = SrcAR->getLoop();
340c9157d92SDimitry Andric // If the start values for both Src and Sink also vary according to an outer
341c9157d92SDimitry Andric // loop, then it's probably better to avoid creating diff checks because
342c9157d92SDimitry Andric // they may not be hoisted. We should instead let llvm::addRuntimeChecks
343c9157d92SDimitry Andric // do the expanded full range overlap checks, which can be hoisted.
344c9157d92SDimitry Andric if (HoistRuntimeChecks && InnerLoop->getParentLoop() &&
345c9157d92SDimitry Andric isa<SCEVAddRecExpr>(SinkStartInt) && isa<SCEVAddRecExpr>(SrcStartInt)) {
346c9157d92SDimitry Andric auto *SrcStartAR = cast<SCEVAddRecExpr>(SrcStartInt);
347c9157d92SDimitry Andric auto *SinkStartAR = cast<SCEVAddRecExpr>(SinkStartInt);
348c9157d92SDimitry Andric const Loop *StartARLoop = SrcStartAR->getLoop();
349c9157d92SDimitry Andric if (StartARLoop == SinkStartAR->getLoop() &&
350c9157d92SDimitry Andric StartARLoop == InnerLoop->getParentLoop() &&
351c9157d92SDimitry Andric // If the diff check would already be loop invariant (due to the
352c9157d92SDimitry Andric // recurrences being the same), then we prefer to keep the diff checks
353c9157d92SDimitry Andric // because they are cheaper.
354c9157d92SDimitry Andric SrcStartAR->getStepRecurrence(*SE) !=
355c9157d92SDimitry Andric SinkStartAR->getStepRecurrence(*SE)) {
356c9157d92SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Not creating diff runtime check, since these "
357c9157d92SDimitry Andric "cannot be hoisted out of the outer loop\n");
358c9157d92SDimitry Andric CanUseDiffCheck = false;
359c9157d92SDimitry Andric return;
360c9157d92SDimitry Andric }
361c9157d92SDimitry Andric }
362c9157d92SDimitry Andric
363c9157d92SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Creating diff runtime check for:\n"
364c9157d92SDimitry Andric << "SrcStart: " << *SrcStartInt << '\n'
365c9157d92SDimitry Andric << "SinkStartInt: " << *SinkStartInt << '\n');
36681ad6265SDimitry Andric DiffChecks.emplace_back(SrcStartInt, SinkStartInt, AllocSize,
36781ad6265SDimitry Andric Src->NeedsFreeze || Sink->NeedsFreeze);
36881ad6265SDimitry Andric }
36981ad6265SDimitry Andric
generateChecks()37081ad6265SDimitry Andric SmallVector<RuntimePointerCheck, 4> RuntimePointerChecking::generateChecks() {
3715ffd83dbSDimitry Andric SmallVector<RuntimePointerCheck, 4> Checks;
3720b57cec5SDimitry Andric
3730b57cec5SDimitry Andric for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
3740b57cec5SDimitry Andric for (unsigned J = I + 1; J < CheckingGroups.size(); ++J) {
3755ffd83dbSDimitry Andric const RuntimeCheckingPtrGroup &CGI = CheckingGroups[I];
3765ffd83dbSDimitry Andric const RuntimeCheckingPtrGroup &CGJ = CheckingGroups[J];
3770b57cec5SDimitry Andric
37881ad6265SDimitry Andric if (needsChecking(CGI, CGJ)) {
37981ad6265SDimitry Andric tryToCreateDiffCheck(CGI, CGJ);
3800b57cec5SDimitry Andric Checks.push_back(std::make_pair(&CGI, &CGJ));
3810b57cec5SDimitry Andric }
3820b57cec5SDimitry Andric }
38381ad6265SDimitry Andric }
3840b57cec5SDimitry Andric return Checks;
3850b57cec5SDimitry Andric }
3860b57cec5SDimitry Andric
generateChecks(MemoryDepChecker::DepCandidates & DepCands,bool UseDependencies)3870b57cec5SDimitry Andric void RuntimePointerChecking::generateChecks(
3880b57cec5SDimitry Andric MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
3890b57cec5SDimitry Andric assert(Checks.empty() && "Checks is not empty");
3900b57cec5SDimitry Andric groupChecks(DepCands, UseDependencies);
3910b57cec5SDimitry Andric Checks = generateChecks();
3920b57cec5SDimitry Andric }
3930b57cec5SDimitry Andric
needsChecking(const RuntimeCheckingPtrGroup & M,const RuntimeCheckingPtrGroup & N) const3945ffd83dbSDimitry Andric bool RuntimePointerChecking::needsChecking(
3955ffd83dbSDimitry Andric const RuntimeCheckingPtrGroup &M, const RuntimeCheckingPtrGroup &N) const {
3960b57cec5SDimitry Andric for (unsigned I = 0, EI = M.Members.size(); EI != I; ++I)
3970b57cec5SDimitry Andric for (unsigned J = 0, EJ = N.Members.size(); EJ != J; ++J)
3980b57cec5SDimitry Andric if (needsChecking(M.Members[I], N.Members[J]))
3990b57cec5SDimitry Andric return true;
4000b57cec5SDimitry Andric return false;
4010b57cec5SDimitry Andric }
4020b57cec5SDimitry Andric
4030b57cec5SDimitry Andric /// Compare \p I and \p J and return the minimum.
4040b57cec5SDimitry Andric /// Return nullptr in case we couldn't find an answer.
getMinFromExprs(const SCEV * I,const SCEV * J,ScalarEvolution * SE)4050b57cec5SDimitry Andric static const SCEV *getMinFromExprs(const SCEV *I, const SCEV *J,
4060b57cec5SDimitry Andric ScalarEvolution *SE) {
4070b57cec5SDimitry Andric const SCEV *Diff = SE->getMinusSCEV(J, I);
4080b57cec5SDimitry Andric const SCEVConstant *C = dyn_cast<const SCEVConstant>(Diff);
4090b57cec5SDimitry Andric
4100b57cec5SDimitry Andric if (!C)
4110b57cec5SDimitry Andric return nullptr;
4120b57cec5SDimitry Andric if (C->getValue()->isNegative())
4130b57cec5SDimitry Andric return J;
4140b57cec5SDimitry Andric return I;
4150b57cec5SDimitry Andric }
4160b57cec5SDimitry Andric
addPointer(unsigned Index,RuntimePointerChecking & RtCheck)417fe6060f1SDimitry Andric bool RuntimeCheckingPtrGroup::addPointer(unsigned Index,
418fe6060f1SDimitry Andric RuntimePointerChecking &RtCheck) {
419fe6060f1SDimitry Andric return addPointer(
420fe6060f1SDimitry Andric Index, RtCheck.Pointers[Index].Start, RtCheck.Pointers[Index].End,
421fe6060f1SDimitry Andric RtCheck.Pointers[Index].PointerValue->getType()->getPointerAddressSpace(),
42281ad6265SDimitry Andric RtCheck.Pointers[Index].NeedsFreeze, *RtCheck.SE);
423fe6060f1SDimitry Andric }
424fe6060f1SDimitry Andric
addPointer(unsigned Index,const SCEV * Start,const SCEV * End,unsigned AS,bool NeedsFreeze,ScalarEvolution & SE)425fe6060f1SDimitry Andric bool RuntimeCheckingPtrGroup::addPointer(unsigned Index, const SCEV *Start,
426fe6060f1SDimitry Andric const SCEV *End, unsigned AS,
42781ad6265SDimitry Andric bool NeedsFreeze,
428fe6060f1SDimitry Andric ScalarEvolution &SE) {
429fe6060f1SDimitry Andric assert(AddressSpace == AS &&
430fe6060f1SDimitry Andric "all pointers in a checking group must be in the same address space");
4310b57cec5SDimitry Andric
4320b57cec5SDimitry Andric // Compare the starts and ends with the known minimum and maximum
4330b57cec5SDimitry Andric // of this set. We need to know how we compare against the min/max
4340b57cec5SDimitry Andric // of the set in order to be able to emit memchecks.
435fe6060f1SDimitry Andric const SCEV *Min0 = getMinFromExprs(Start, Low, &SE);
4360b57cec5SDimitry Andric if (!Min0)
4370b57cec5SDimitry Andric return false;
4380b57cec5SDimitry Andric
439fe6060f1SDimitry Andric const SCEV *Min1 = getMinFromExprs(End, High, &SE);
4400b57cec5SDimitry Andric if (!Min1)
4410b57cec5SDimitry Andric return false;
4420b57cec5SDimitry Andric
4430b57cec5SDimitry Andric // Update the low bound expression if we've found a new min value.
4440b57cec5SDimitry Andric if (Min0 == Start)
4450b57cec5SDimitry Andric Low = Start;
4460b57cec5SDimitry Andric
4470b57cec5SDimitry Andric // Update the high bound expression if we've found a new max value.
4480b57cec5SDimitry Andric if (Min1 != End)
4490b57cec5SDimitry Andric High = End;
4500b57cec5SDimitry Andric
4510b57cec5SDimitry Andric Members.push_back(Index);
45281ad6265SDimitry Andric this->NeedsFreeze |= NeedsFreeze;
4530b57cec5SDimitry Andric return true;
4540b57cec5SDimitry Andric }
4550b57cec5SDimitry Andric
groupChecks(MemoryDepChecker::DepCandidates & DepCands,bool UseDependencies)4560b57cec5SDimitry Andric void RuntimePointerChecking::groupChecks(
4570b57cec5SDimitry Andric MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
4580b57cec5SDimitry Andric // We build the groups from dependency candidates equivalence classes
4590b57cec5SDimitry Andric // because:
4600b57cec5SDimitry Andric // - We know that pointers in the same equivalence class share
4610b57cec5SDimitry Andric // the same underlying object and therefore there is a chance
4620b57cec5SDimitry Andric // that we can compare pointers
4630b57cec5SDimitry Andric // - We wouldn't be able to merge two pointers for which we need
4640b57cec5SDimitry Andric // to emit a memcheck. The classes in DepCands are already
4650b57cec5SDimitry Andric // conveniently built such that no two pointers in the same
4660b57cec5SDimitry Andric // class need checking against each other.
4670b57cec5SDimitry Andric
4680b57cec5SDimitry Andric // We use the following (greedy) algorithm to construct the groups
4690b57cec5SDimitry Andric // For every pointer in the equivalence class:
4700b57cec5SDimitry Andric // For each existing group:
4710b57cec5SDimitry Andric // - if the difference between this pointer and the min/max bounds
4720b57cec5SDimitry Andric // of the group is a constant, then make the pointer part of the
4730b57cec5SDimitry Andric // group and update the min/max bounds of that group as required.
4740b57cec5SDimitry Andric
4750b57cec5SDimitry Andric CheckingGroups.clear();
4760b57cec5SDimitry Andric
4770b57cec5SDimitry Andric // If we need to check two pointers to the same underlying object
4780b57cec5SDimitry Andric // with a non-constant difference, we shouldn't perform any pointer
4790b57cec5SDimitry Andric // grouping with those pointers. This is because we can easily get
4800b57cec5SDimitry Andric // into cases where the resulting check would return false, even when
4810b57cec5SDimitry Andric // the accesses are safe.
4820b57cec5SDimitry Andric //
4830b57cec5SDimitry Andric // The following example shows this:
4840b57cec5SDimitry Andric // for (i = 0; i < 1000; ++i)
4850b57cec5SDimitry Andric // a[5000 + i * m] = a[i] + a[i + 9000]
4860b57cec5SDimitry Andric //
4870b57cec5SDimitry Andric // Here grouping gives a check of (5000, 5000 + 1000 * m) against
4880b57cec5SDimitry Andric // (0, 10000) which is always false. However, if m is 1, there is no
4890b57cec5SDimitry Andric // dependence. Not grouping the checks for a[i] and a[i + 9000] allows
4900b57cec5SDimitry Andric // us to perform an accurate check in this case.
4910b57cec5SDimitry Andric //
4920b57cec5SDimitry Andric // The above case requires that we have an UnknownDependence between
4930b57cec5SDimitry Andric // accesses to the same underlying object. This cannot happen unless
4940b57cec5SDimitry Andric // FoundNonConstantDistanceDependence is set, and therefore UseDependencies
4950b57cec5SDimitry Andric // is also false. In this case we will use the fallback path and create
4960b57cec5SDimitry Andric // separate checking groups for all pointers.
4970b57cec5SDimitry Andric
4980b57cec5SDimitry Andric // If we don't have the dependency partitions, construct a new
4990b57cec5SDimitry Andric // checking pointer group for each pointer. This is also required
5000b57cec5SDimitry Andric // for correctness, because in this case we can have checking between
5010b57cec5SDimitry Andric // pointers to the same underlying object.
5020b57cec5SDimitry Andric if (!UseDependencies) {
5030b57cec5SDimitry Andric for (unsigned I = 0; I < Pointers.size(); ++I)
5045ffd83dbSDimitry Andric CheckingGroups.push_back(RuntimeCheckingPtrGroup(I, *this));
5050b57cec5SDimitry Andric return;
5060b57cec5SDimitry Andric }
5070b57cec5SDimitry Andric
5080b57cec5SDimitry Andric unsigned TotalComparisons = 0;
5090b57cec5SDimitry Andric
51081ad6265SDimitry Andric DenseMap<Value *, SmallVector<unsigned>> PositionMap;
51181ad6265SDimitry Andric for (unsigned Index = 0; Index < Pointers.size(); ++Index) {
51281ad6265SDimitry Andric auto Iter = PositionMap.insert({Pointers[Index].PointerValue, {}});
51381ad6265SDimitry Andric Iter.first->second.push_back(Index);
51481ad6265SDimitry Andric }
5150b57cec5SDimitry Andric
5160b57cec5SDimitry Andric // We need to keep track of what pointers we've already seen so we
5170b57cec5SDimitry Andric // don't process them twice.
5180b57cec5SDimitry Andric SmallSet<unsigned, 2> Seen;
5190b57cec5SDimitry Andric
5200b57cec5SDimitry Andric // Go through all equivalence classes, get the "pointer check groups"
5210b57cec5SDimitry Andric // and add them to the overall solution. We use the order in which accesses
5220b57cec5SDimitry Andric // appear in 'Pointers' to enforce determinism.
5230b57cec5SDimitry Andric for (unsigned I = 0; I < Pointers.size(); ++I) {
5240b57cec5SDimitry Andric // We've seen this pointer before, and therefore already processed
5250b57cec5SDimitry Andric // its equivalence class.
5260b57cec5SDimitry Andric if (Seen.count(I))
5270b57cec5SDimitry Andric continue;
5280b57cec5SDimitry Andric
5290b57cec5SDimitry Andric MemoryDepChecker::MemAccessInfo Access(Pointers[I].PointerValue,
5300b57cec5SDimitry Andric Pointers[I].IsWritePtr);
5310b57cec5SDimitry Andric
5325ffd83dbSDimitry Andric SmallVector<RuntimeCheckingPtrGroup, 2> Groups;
5330b57cec5SDimitry Andric auto LeaderI = DepCands.findValue(DepCands.getLeaderValue(Access));
5340b57cec5SDimitry Andric
5350b57cec5SDimitry Andric // Because DepCands is constructed by visiting accesses in the order in
5360b57cec5SDimitry Andric // which they appear in alias sets (which is deterministic) and the
5370b57cec5SDimitry Andric // iteration order within an equivalence class member is only dependent on
5380b57cec5SDimitry Andric // the order in which unions and insertions are performed on the
5390b57cec5SDimitry Andric // equivalence class, the iteration order is deterministic.
5400b57cec5SDimitry Andric for (auto MI = DepCands.member_begin(LeaderI), ME = DepCands.member_end();
5410b57cec5SDimitry Andric MI != ME; ++MI) {
5421106035dSDimitry Andric auto PointerI = PositionMap.find(MI->getPointer());
5431106035dSDimitry Andric assert(PointerI != PositionMap.end() &&
5441106035dSDimitry Andric "pointer in equivalence class not found in PositionMap");
54581ad6265SDimitry Andric for (unsigned Pointer : PointerI->second) {
5460b57cec5SDimitry Andric bool Merged = false;
5470b57cec5SDimitry Andric // Mark this pointer as seen.
5480b57cec5SDimitry Andric Seen.insert(Pointer);
5490b57cec5SDimitry Andric
5500b57cec5SDimitry Andric // Go through all the existing sets and see if we can find one
5510b57cec5SDimitry Andric // which can include this pointer.
5525ffd83dbSDimitry Andric for (RuntimeCheckingPtrGroup &Group : Groups) {
5530b57cec5SDimitry Andric // Don't perform more than a certain amount of comparisons.
5540b57cec5SDimitry Andric // This should limit the cost of grouping the pointers to something
5550b57cec5SDimitry Andric // reasonable. If we do end up hitting this threshold, the algorithm
5560b57cec5SDimitry Andric // will create separate groups for all remaining pointers.
5570b57cec5SDimitry Andric if (TotalComparisons > MemoryCheckMergeThreshold)
5580b57cec5SDimitry Andric break;
5590b57cec5SDimitry Andric
5600b57cec5SDimitry Andric TotalComparisons++;
5610b57cec5SDimitry Andric
562fe6060f1SDimitry Andric if (Group.addPointer(Pointer, *this)) {
5630b57cec5SDimitry Andric Merged = true;
5640b57cec5SDimitry Andric break;
5650b57cec5SDimitry Andric }
5660b57cec5SDimitry Andric }
5670b57cec5SDimitry Andric
5680b57cec5SDimitry Andric if (!Merged)
5690b57cec5SDimitry Andric // We couldn't add this pointer to any existing set or the threshold
5700b57cec5SDimitry Andric // for the number of comparisons has been reached. Create a new group
5710b57cec5SDimitry Andric // to hold the current pointer.
5725ffd83dbSDimitry Andric Groups.push_back(RuntimeCheckingPtrGroup(Pointer, *this));
5730b57cec5SDimitry Andric }
57481ad6265SDimitry Andric }
5750b57cec5SDimitry Andric
5760b57cec5SDimitry Andric // We've computed the grouped checks for this partition.
5770b57cec5SDimitry Andric // Save the results and continue with the next one.
5780b57cec5SDimitry Andric llvm::copy(Groups, std::back_inserter(CheckingGroups));
5790b57cec5SDimitry Andric }
5800b57cec5SDimitry Andric }
5810b57cec5SDimitry Andric
arePointersInSamePartition(const SmallVectorImpl<int> & PtrToPartition,unsigned PtrIdx1,unsigned PtrIdx2)5820b57cec5SDimitry Andric bool RuntimePointerChecking::arePointersInSamePartition(
5830b57cec5SDimitry Andric const SmallVectorImpl<int> &PtrToPartition, unsigned PtrIdx1,
5840b57cec5SDimitry Andric unsigned PtrIdx2) {
5850b57cec5SDimitry Andric return (PtrToPartition[PtrIdx1] != -1 &&
5860b57cec5SDimitry Andric PtrToPartition[PtrIdx1] == PtrToPartition[PtrIdx2]);
5870b57cec5SDimitry Andric }
5880b57cec5SDimitry Andric
needsChecking(unsigned I,unsigned J) const5890b57cec5SDimitry Andric bool RuntimePointerChecking::needsChecking(unsigned I, unsigned J) const {
5900b57cec5SDimitry Andric const PointerInfo &PointerI = Pointers[I];
5910b57cec5SDimitry Andric const PointerInfo &PointerJ = Pointers[J];
5920b57cec5SDimitry Andric
5930b57cec5SDimitry Andric // No need to check if two readonly pointers intersect.
5940b57cec5SDimitry Andric if (!PointerI.IsWritePtr && !PointerJ.IsWritePtr)
5950b57cec5SDimitry Andric return false;
5960b57cec5SDimitry Andric
5970b57cec5SDimitry Andric // Only need to check pointers between two different dependency sets.
5980b57cec5SDimitry Andric if (PointerI.DependencySetId == PointerJ.DependencySetId)
5990b57cec5SDimitry Andric return false;
6000b57cec5SDimitry Andric
6010b57cec5SDimitry Andric // Only need to check pointers in the same alias set.
6020b57cec5SDimitry Andric if (PointerI.AliasSetId != PointerJ.AliasSetId)
6030b57cec5SDimitry Andric return false;
6040b57cec5SDimitry Andric
6050b57cec5SDimitry Andric return true;
6060b57cec5SDimitry Andric }
6070b57cec5SDimitry Andric
printChecks(raw_ostream & OS,const SmallVectorImpl<RuntimePointerCheck> & Checks,unsigned Depth) const6080b57cec5SDimitry Andric void RuntimePointerChecking::printChecks(
6095ffd83dbSDimitry Andric raw_ostream &OS, const SmallVectorImpl<RuntimePointerCheck> &Checks,
6100b57cec5SDimitry Andric unsigned Depth) const {
6110b57cec5SDimitry Andric unsigned N = 0;
6120b57cec5SDimitry Andric for (const auto &Check : Checks) {
6130b57cec5SDimitry Andric const auto &First = Check.first->Members, &Second = Check.second->Members;
6140b57cec5SDimitry Andric
6150b57cec5SDimitry Andric OS.indent(Depth) << "Check " << N++ << ":\n";
6160b57cec5SDimitry Andric
6170b57cec5SDimitry Andric OS.indent(Depth + 2) << "Comparing group (" << Check.first << "):\n";
6180b57cec5SDimitry Andric for (unsigned K = 0; K < First.size(); ++K)
6190b57cec5SDimitry Andric OS.indent(Depth + 2) << *Pointers[First[K]].PointerValue << "\n";
6200b57cec5SDimitry Andric
6210b57cec5SDimitry Andric OS.indent(Depth + 2) << "Against group (" << Check.second << "):\n";
6220b57cec5SDimitry Andric for (unsigned K = 0; K < Second.size(); ++K)
6230b57cec5SDimitry Andric OS.indent(Depth + 2) << *Pointers[Second[K]].PointerValue << "\n";
6240b57cec5SDimitry Andric }
6250b57cec5SDimitry Andric }
6260b57cec5SDimitry Andric
print(raw_ostream & OS,unsigned Depth) const6270b57cec5SDimitry Andric void RuntimePointerChecking::print(raw_ostream &OS, unsigned Depth) const {
6280b57cec5SDimitry Andric
6290b57cec5SDimitry Andric OS.indent(Depth) << "Run-time memory checks:\n";
6300b57cec5SDimitry Andric printChecks(OS, Checks, Depth);
6310b57cec5SDimitry Andric
6320b57cec5SDimitry Andric OS.indent(Depth) << "Grouped accesses:\n";
6330b57cec5SDimitry Andric for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
6340b57cec5SDimitry Andric const auto &CG = CheckingGroups[I];
6350b57cec5SDimitry Andric
6360b57cec5SDimitry Andric OS.indent(Depth + 2) << "Group " << &CG << ":\n";
6370b57cec5SDimitry Andric OS.indent(Depth + 4) << "(Low: " << *CG.Low << " High: " << *CG.High
6380b57cec5SDimitry Andric << ")\n";
6390b57cec5SDimitry Andric for (unsigned J = 0; J < CG.Members.size(); ++J) {
6400b57cec5SDimitry Andric OS.indent(Depth + 6) << "Member: " << *Pointers[CG.Members[J]].Expr
6410b57cec5SDimitry Andric << "\n";
6420b57cec5SDimitry Andric }
6430b57cec5SDimitry Andric }
6440b57cec5SDimitry Andric }
6450b57cec5SDimitry Andric
6460b57cec5SDimitry Andric namespace {
6470b57cec5SDimitry Andric
6480b57cec5SDimitry Andric /// Analyses memory accesses in a loop.
6490b57cec5SDimitry Andric ///
6500b57cec5SDimitry Andric /// Checks whether run time pointer checks are needed and builds sets for data
6510b57cec5SDimitry Andric /// dependence checking.
6520b57cec5SDimitry Andric class AccessAnalysis {
6530b57cec5SDimitry Andric public:
6540b57cec5SDimitry Andric /// Read or write access location.
6550b57cec5SDimitry Andric typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
6560b57cec5SDimitry Andric typedef SmallVector<MemAccessInfo, 8> MemAccessInfoList;
6570b57cec5SDimitry Andric
AccessAnalysis(Loop * TheLoop,AAResults * AA,LoopInfo * LI,MemoryDepChecker::DepCandidates & DA,PredicatedScalarEvolution & PSE,SmallPtrSetImpl<MDNode * > & LoopAliasScopes)658e8d8bef9SDimitry Andric AccessAnalysis(Loop *TheLoop, AAResults *AA, LoopInfo *LI,
659e8d8bef9SDimitry Andric MemoryDepChecker::DepCandidates &DA,
660*b9d9368bSDimitry Andric PredicatedScalarEvolution &PSE,
661*b9d9368bSDimitry Andric SmallPtrSetImpl<MDNode *> &LoopAliasScopes)
662*b9d9368bSDimitry Andric : TheLoop(TheLoop), BAA(*AA), AST(BAA), LI(LI), DepCands(DA), PSE(PSE),
663*b9d9368bSDimitry Andric LoopAliasScopes(LoopAliasScopes) {
664bdd1243dSDimitry Andric // We're analyzing dependences across loop iterations.
665bdd1243dSDimitry Andric BAA.enableCrossIterationMode();
666bdd1243dSDimitry Andric }
6670b57cec5SDimitry Andric
6680b57cec5SDimitry Andric /// Register a load and whether it is only read from.
addLoad(MemoryLocation & Loc,Type * AccessTy,bool IsReadOnly)66981ad6265SDimitry Andric void addLoad(MemoryLocation &Loc, Type *AccessTy, bool IsReadOnly) {
6700b57cec5SDimitry Andric Value *Ptr = const_cast<Value *>(Loc.Ptr);
671*b9d9368bSDimitry Andric AST.add(adjustLoc(Loc));
67281ad6265SDimitry Andric Accesses[MemAccessInfo(Ptr, false)].insert(AccessTy);
6730b57cec5SDimitry Andric if (IsReadOnly)
6740b57cec5SDimitry Andric ReadOnlyPtr.insert(Ptr);
6750b57cec5SDimitry Andric }
6760b57cec5SDimitry Andric
6770b57cec5SDimitry Andric /// Register a store.
addStore(MemoryLocation & Loc,Type * AccessTy)67881ad6265SDimitry Andric void addStore(MemoryLocation &Loc, Type *AccessTy) {
6790b57cec5SDimitry Andric Value *Ptr = const_cast<Value *>(Loc.Ptr);
680*b9d9368bSDimitry Andric AST.add(adjustLoc(Loc));
68181ad6265SDimitry Andric Accesses[MemAccessInfo(Ptr, true)].insert(AccessTy);
6820b57cec5SDimitry Andric }
6830b57cec5SDimitry Andric
6840b57cec5SDimitry Andric /// Check if we can emit a run-time no-alias check for \p Access.
6850b57cec5SDimitry Andric ///
6860b57cec5SDimitry Andric /// Returns true if we can emit a run-time no alias check for \p Access.
6870b57cec5SDimitry Andric /// If we can check this access, this also adds it to a dependence set and
6880b57cec5SDimitry Andric /// adds a run-time to check for it to \p RtCheck. If \p Assume is true,
6890b57cec5SDimitry Andric /// we will attempt to use additional run-time checks in order to get
6900b57cec5SDimitry Andric /// the bounds of the pointer.
6910b57cec5SDimitry Andric bool createCheckForAccess(RuntimePointerChecking &RtCheck,
69281ad6265SDimitry Andric MemAccessInfo Access, Type *AccessTy,
693fe013be4SDimitry Andric const DenseMap<Value *, const SCEV *> &Strides,
6940b57cec5SDimitry Andric DenseMap<Value *, unsigned> &DepSetId,
6950b57cec5SDimitry Andric Loop *TheLoop, unsigned &RunningDepId,
69681ad6265SDimitry Andric unsigned ASId, bool ShouldCheckStride, bool Assume);
6970b57cec5SDimitry Andric
6980b57cec5SDimitry Andric /// Check whether we can check the pointers at runtime for
6990b57cec5SDimitry Andric /// non-intersection.
7000b57cec5SDimitry Andric ///
7010b57cec5SDimitry Andric /// Returns true if we need no check or if we do and we can generate them
7020b57cec5SDimitry Andric /// (i.e. the pointers have computable bounds).
7030b57cec5SDimitry Andric bool canCheckPtrAtRT(RuntimePointerChecking &RtCheck, ScalarEvolution *SE,
704fe013be4SDimitry Andric Loop *TheLoop, const DenseMap<Value *, const SCEV *> &Strides,
70581ad6265SDimitry Andric Value *&UncomputablePtr, bool ShouldCheckWrap = false);
7060b57cec5SDimitry Andric
7070b57cec5SDimitry Andric /// Goes over all memory accesses, checks whether a RT check is needed
7080b57cec5SDimitry Andric /// and builds sets of dependent accesses.
buildDependenceSets()7090b57cec5SDimitry Andric void buildDependenceSets() {
7100b57cec5SDimitry Andric processMemAccesses();
7110b57cec5SDimitry Andric }
7120b57cec5SDimitry Andric
7130b57cec5SDimitry Andric /// Initial processing of memory accesses determined that we need to
7140b57cec5SDimitry Andric /// perform dependency checking.
7150b57cec5SDimitry Andric ///
7160b57cec5SDimitry Andric /// Note that this can later be cleared if we retry memcheck analysis without
7170b57cec5SDimitry Andric /// dependency checking (i.e. FoundNonConstantDistanceDependence).
isDependencyCheckNeeded()7180b57cec5SDimitry Andric bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
7190b57cec5SDimitry Andric
7200b57cec5SDimitry Andric /// We decided that no dependence analysis would be used. Reset the state.
resetDepChecks(MemoryDepChecker & DepChecker)7210b57cec5SDimitry Andric void resetDepChecks(MemoryDepChecker &DepChecker) {
7220b57cec5SDimitry Andric CheckDeps.clear();
7230b57cec5SDimitry Andric DepChecker.clearDependences();
7240b57cec5SDimitry Andric }
7250b57cec5SDimitry Andric
getDependenciesToCheck()7260b57cec5SDimitry Andric MemAccessInfoList &getDependenciesToCheck() { return CheckDeps; }
7270b57cec5SDimitry Andric
728c9157d92SDimitry Andric const DenseMap<Value *, SmallVector<const Value *, 16>> &
getUnderlyingObjects()729c9157d92SDimitry Andric getUnderlyingObjects() {
730c9157d92SDimitry Andric return UnderlyingObjects;
731c9157d92SDimitry Andric }
732c9157d92SDimitry Andric
7330b57cec5SDimitry Andric private:
73481ad6265SDimitry Andric typedef MapVector<MemAccessInfo, SmallSetVector<Type *, 1>> PtrAccessMap;
7350b57cec5SDimitry Andric
736*b9d9368bSDimitry Andric /// Adjust the MemoryLocation so that it represents accesses to this
737*b9d9368bSDimitry Andric /// location across all iterations, rather than a single one.
adjustLoc(MemoryLocation Loc) const738*b9d9368bSDimitry Andric MemoryLocation adjustLoc(MemoryLocation Loc) const {
739*b9d9368bSDimitry Andric // The accessed location varies within the loop, but remains within the
740*b9d9368bSDimitry Andric // underlying object.
741*b9d9368bSDimitry Andric Loc.Size = LocationSize::beforeOrAfterPointer();
742*b9d9368bSDimitry Andric Loc.AATags.Scope = adjustAliasScopeList(Loc.AATags.Scope);
743*b9d9368bSDimitry Andric Loc.AATags.NoAlias = adjustAliasScopeList(Loc.AATags.NoAlias);
744*b9d9368bSDimitry Andric return Loc;
745*b9d9368bSDimitry Andric }
746*b9d9368bSDimitry Andric
747*b9d9368bSDimitry Andric /// Drop alias scopes that are only valid within a single loop iteration.
adjustAliasScopeList(MDNode * ScopeList) const748*b9d9368bSDimitry Andric MDNode *adjustAliasScopeList(MDNode *ScopeList) const {
749*b9d9368bSDimitry Andric if (!ScopeList)
750*b9d9368bSDimitry Andric return nullptr;
751*b9d9368bSDimitry Andric
752*b9d9368bSDimitry Andric // For the sake of simplicity, drop the whole scope list if any scope is
753*b9d9368bSDimitry Andric // iteration-local.
754*b9d9368bSDimitry Andric if (any_of(ScopeList->operands(), [&](Metadata *Scope) {
755*b9d9368bSDimitry Andric return LoopAliasScopes.contains(cast<MDNode>(Scope));
756*b9d9368bSDimitry Andric }))
757*b9d9368bSDimitry Andric return nullptr;
758*b9d9368bSDimitry Andric
759*b9d9368bSDimitry Andric return ScopeList;
760*b9d9368bSDimitry Andric }
761*b9d9368bSDimitry Andric
7620b57cec5SDimitry Andric /// Go over all memory access and check whether runtime pointer checks
7630b57cec5SDimitry Andric /// are needed and build sets of dependency check candidates.
7640b57cec5SDimitry Andric void processMemAccesses();
7650b57cec5SDimitry Andric
76681ad6265SDimitry Andric /// Map of all accesses. Values are the types used to access memory pointed to
76781ad6265SDimitry Andric /// by the pointer.
76881ad6265SDimitry Andric PtrAccessMap Accesses;
7690b57cec5SDimitry Andric
7700b57cec5SDimitry Andric /// The loop being checked.
7710b57cec5SDimitry Andric const Loop *TheLoop;
7720b57cec5SDimitry Andric
7730b57cec5SDimitry Andric /// List of accesses that need a further dependence check.
7740b57cec5SDimitry Andric MemAccessInfoList CheckDeps;
7750b57cec5SDimitry Andric
7760b57cec5SDimitry Andric /// Set of pointers that are read only.
7770b57cec5SDimitry Andric SmallPtrSet<Value*, 16> ReadOnlyPtr;
7780b57cec5SDimitry Andric
779bdd1243dSDimitry Andric /// Batched alias analysis results.
780bdd1243dSDimitry Andric BatchAAResults BAA;
781bdd1243dSDimitry Andric
7820b57cec5SDimitry Andric /// An alias set tracker to partition the access set by underlying object and
7830b57cec5SDimitry Andric //intrinsic property (such as TBAA metadata).
7840b57cec5SDimitry Andric AliasSetTracker AST;
7850b57cec5SDimitry Andric
7860b57cec5SDimitry Andric LoopInfo *LI;
7870b57cec5SDimitry Andric
7880b57cec5SDimitry Andric /// Sets of potentially dependent accesses - members of one set share an
7890b57cec5SDimitry Andric /// underlying pointer. The set "CheckDeps" identfies which sets really need a
7900b57cec5SDimitry Andric /// dependence check.
7910b57cec5SDimitry Andric MemoryDepChecker::DepCandidates &DepCands;
7920b57cec5SDimitry Andric
7930b57cec5SDimitry Andric /// Initial processing of memory accesses determined that we may need
7940b57cec5SDimitry Andric /// to add memchecks. Perform the analysis to determine the necessary checks.
7950b57cec5SDimitry Andric ///
7960b57cec5SDimitry Andric /// Note that, this is different from isDependencyCheckNeeded. When we retry
7970b57cec5SDimitry Andric /// memcheck analysis without dependency checking
7980b57cec5SDimitry Andric /// (i.e. FoundNonConstantDistanceDependence), isDependencyCheckNeeded is
7990b57cec5SDimitry Andric /// cleared while this remains set if we have potentially dependent accesses.
80004eeddc0SDimitry Andric bool IsRTCheckAnalysisNeeded = false;
8010b57cec5SDimitry Andric
8020b57cec5SDimitry Andric /// The SCEV predicate containing all the SCEV-related assumptions.
8030b57cec5SDimitry Andric PredicatedScalarEvolution &PSE;
804c9157d92SDimitry Andric
805c9157d92SDimitry Andric DenseMap<Value *, SmallVector<const Value *, 16>> UnderlyingObjects;
806*b9d9368bSDimitry Andric
807*b9d9368bSDimitry Andric /// Alias scopes that are declared inside the loop, and as such not valid
808*b9d9368bSDimitry Andric /// across iterations.
809*b9d9368bSDimitry Andric SmallPtrSetImpl<MDNode *> &LoopAliasScopes;
8100b57cec5SDimitry Andric };
8110b57cec5SDimitry Andric
8120b57cec5SDimitry Andric } // end anonymous namespace
8130b57cec5SDimitry Andric
8140b57cec5SDimitry Andric /// Check whether a pointer can participate in a runtime bounds check.
8150b57cec5SDimitry Andric /// If \p Assume, try harder to prove that we can compute the bounds of \p Ptr
8160b57cec5SDimitry Andric /// by adding run-time checks (overflow checks) if necessary.
hasComputableBounds(PredicatedScalarEvolution & PSE,Value * Ptr,const SCEV * PtrScev,Loop * L,bool Assume)81781ad6265SDimitry Andric static bool hasComputableBounds(PredicatedScalarEvolution &PSE, Value *Ptr,
81881ad6265SDimitry Andric const SCEV *PtrScev, Loop *L, bool Assume) {
8190b57cec5SDimitry Andric // The bounds for loop-invariant pointer is trivial.
8200b57cec5SDimitry Andric if (PSE.getSE()->isLoopInvariant(PtrScev, L))
8210b57cec5SDimitry Andric return true;
8220b57cec5SDimitry Andric
8230b57cec5SDimitry Andric const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
8240b57cec5SDimitry Andric
8250b57cec5SDimitry Andric if (!AR && Assume)
8260b57cec5SDimitry Andric AR = PSE.getAsAddRec(Ptr);
8270b57cec5SDimitry Andric
8280b57cec5SDimitry Andric if (!AR)
8290b57cec5SDimitry Andric return false;
8300b57cec5SDimitry Andric
8310b57cec5SDimitry Andric return AR->isAffine();
8320b57cec5SDimitry Andric }
8330b57cec5SDimitry Andric
8340b57cec5SDimitry Andric /// Check whether a pointer address cannot wrap.
isNoWrap(PredicatedScalarEvolution & PSE,const DenseMap<Value *,const SCEV * > & Strides,Value * Ptr,Type * AccessTy,Loop * L)8350b57cec5SDimitry Andric static bool isNoWrap(PredicatedScalarEvolution &PSE,
836fe013be4SDimitry Andric const DenseMap<Value *, const SCEV *> &Strides, Value *Ptr, Type *AccessTy,
83781ad6265SDimitry Andric Loop *L) {
8380b57cec5SDimitry Andric const SCEV *PtrScev = PSE.getSCEV(Ptr);
8390b57cec5SDimitry Andric if (PSE.getSE()->isLoopInvariant(PtrScev, L))
8400b57cec5SDimitry Andric return true;
8410b57cec5SDimitry Andric
842bdd1243dSDimitry Andric int64_t Stride = getPtrStride(PSE, AccessTy, Ptr, L, Strides).value_or(0);
8430b57cec5SDimitry Andric if (Stride == 1 || PSE.hasNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW))
8440b57cec5SDimitry Andric return true;
8450b57cec5SDimitry Andric
8460b57cec5SDimitry Andric return false;
8470b57cec5SDimitry Andric }
8480b57cec5SDimitry Andric
visitPointers(Value * StartPtr,const Loop & InnermostLoop,function_ref<void (Value *)> AddPointer)8494824e7fdSDimitry Andric static void visitPointers(Value *StartPtr, const Loop &InnermostLoop,
8504824e7fdSDimitry Andric function_ref<void(Value *)> AddPointer) {
8514824e7fdSDimitry Andric SmallPtrSet<Value *, 8> Visited;
8524824e7fdSDimitry Andric SmallVector<Value *> WorkList;
8534824e7fdSDimitry Andric WorkList.push_back(StartPtr);
8544824e7fdSDimitry Andric
8554824e7fdSDimitry Andric while (!WorkList.empty()) {
8564824e7fdSDimitry Andric Value *Ptr = WorkList.pop_back_val();
8574824e7fdSDimitry Andric if (!Visited.insert(Ptr).second)
8584824e7fdSDimitry Andric continue;
8594824e7fdSDimitry Andric auto *PN = dyn_cast<PHINode>(Ptr);
8604824e7fdSDimitry Andric // SCEV does not look through non-header PHIs inside the loop. Such phis
8614824e7fdSDimitry Andric // can be analyzed by adding separate accesses for each incoming pointer
8624824e7fdSDimitry Andric // value.
8634824e7fdSDimitry Andric if (PN && InnermostLoop.contains(PN->getParent()) &&
8644824e7fdSDimitry Andric PN->getParent() != InnermostLoop.getHeader()) {
8654824e7fdSDimitry Andric for (const Use &Inc : PN->incoming_values())
8664824e7fdSDimitry Andric WorkList.push_back(Inc);
8674824e7fdSDimitry Andric } else
8684824e7fdSDimitry Andric AddPointer(Ptr);
8694824e7fdSDimitry Andric }
8704824e7fdSDimitry Andric }
8714824e7fdSDimitry Andric
872fcaf7f86SDimitry Andric // Walk back through the IR for a pointer, looking for a select like the
873fcaf7f86SDimitry Andric // following:
874fcaf7f86SDimitry Andric //
875fcaf7f86SDimitry Andric // %offset = select i1 %cmp, i64 %a, i64 %b
876fcaf7f86SDimitry Andric // %addr = getelementptr double, double* %base, i64 %offset
877fcaf7f86SDimitry Andric // %ld = load double, double* %addr, align 8
878fcaf7f86SDimitry Andric //
879fcaf7f86SDimitry Andric // We won't be able to form a single SCEVAddRecExpr from this since the
880fcaf7f86SDimitry Andric // address for each loop iteration depends on %cmp. We could potentially
881fcaf7f86SDimitry Andric // produce multiple valid SCEVAddRecExprs, though, and check all of them for
882fcaf7f86SDimitry Andric // memory safety/aliasing if needed.
883fcaf7f86SDimitry Andric //
884fcaf7f86SDimitry Andric // If we encounter some IR we don't yet handle, or something obviously fine
885fcaf7f86SDimitry Andric // like a constant, then we just add the SCEV for that term to the list passed
886fcaf7f86SDimitry Andric // in by the caller. If we have a node that may potentially yield a valid
887fcaf7f86SDimitry Andric // SCEVAddRecExpr then we decompose it into parts and build the SCEV terms
888fcaf7f86SDimitry Andric // ourselves before adding to the list.
findForkedSCEVs(ScalarEvolution * SE,const Loop * L,Value * Ptr,SmallVectorImpl<PointerIntPair<const SCEV *,1,bool>> & ScevList,unsigned Depth)889bdd1243dSDimitry Andric static void findForkedSCEVs(
890bdd1243dSDimitry Andric ScalarEvolution *SE, const Loop *L, Value *Ptr,
891bdd1243dSDimitry Andric SmallVectorImpl<PointerIntPair<const SCEV *, 1, bool>> &ScevList,
892fcaf7f86SDimitry Andric unsigned Depth) {
893fcaf7f86SDimitry Andric // If our Value is a SCEVAddRecExpr, loop invariant, not an instruction, or
894fcaf7f86SDimitry Andric // we've exceeded our limit on recursion, just return whatever we have
895fcaf7f86SDimitry Andric // regardless of whether it can be used for a forked pointer or not, along
896fcaf7f86SDimitry Andric // with an indication of whether it might be a poison or undef value.
897fcaf7f86SDimitry Andric const SCEV *Scev = SE->getSCEV(Ptr);
898fcaf7f86SDimitry Andric if (isa<SCEVAddRecExpr>(Scev) || L->isLoopInvariant(Ptr) ||
899fcaf7f86SDimitry Andric !isa<Instruction>(Ptr) || Depth == 0) {
900bdd1243dSDimitry Andric ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr));
901fcaf7f86SDimitry Andric return;
902fcaf7f86SDimitry Andric }
903fcaf7f86SDimitry Andric
904fcaf7f86SDimitry Andric Depth--;
905fcaf7f86SDimitry Andric
906bdd1243dSDimitry Andric auto UndefPoisonCheck = [](PointerIntPair<const SCEV *, 1, bool> S) {
907bdd1243dSDimitry Andric return get<1>(S);
908bdd1243dSDimitry Andric };
909bdd1243dSDimitry Andric
910bdd1243dSDimitry Andric auto GetBinOpExpr = [&SE](unsigned Opcode, const SCEV *L, const SCEV *R) {
911bdd1243dSDimitry Andric switch (Opcode) {
912bdd1243dSDimitry Andric case Instruction::Add:
913bdd1243dSDimitry Andric return SE->getAddExpr(L, R);
914bdd1243dSDimitry Andric case Instruction::Sub:
915bdd1243dSDimitry Andric return SE->getMinusSCEV(L, R);
916bdd1243dSDimitry Andric default:
917bdd1243dSDimitry Andric llvm_unreachable("Unexpected binary operator when walking ForkedPtrs");
918bdd1243dSDimitry Andric }
919fcaf7f86SDimitry Andric };
920fcaf7f86SDimitry Andric
921fcaf7f86SDimitry Andric Instruction *I = cast<Instruction>(Ptr);
922fcaf7f86SDimitry Andric unsigned Opcode = I->getOpcode();
923fcaf7f86SDimitry Andric switch (Opcode) {
924fcaf7f86SDimitry Andric case Instruction::GetElementPtr: {
925fcaf7f86SDimitry Andric GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
926fcaf7f86SDimitry Andric Type *SourceTy = GEP->getSourceElementType();
927fcaf7f86SDimitry Andric // We only handle base + single offset GEPs here for now.
928fcaf7f86SDimitry Andric // Not dealing with preexisting gathers yet, so no vectors.
929fcaf7f86SDimitry Andric if (I->getNumOperands() != 2 || SourceTy->isVectorTy()) {
930bdd1243dSDimitry Andric ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(GEP));
931fcaf7f86SDimitry Andric break;
932fcaf7f86SDimitry Andric }
933bdd1243dSDimitry Andric SmallVector<PointerIntPair<const SCEV *, 1, bool>, 2> BaseScevs;
934bdd1243dSDimitry Andric SmallVector<PointerIntPair<const SCEV *, 1, bool>, 2> OffsetScevs;
935fcaf7f86SDimitry Andric findForkedSCEVs(SE, L, I->getOperand(0), BaseScevs, Depth);
936fcaf7f86SDimitry Andric findForkedSCEVs(SE, L, I->getOperand(1), OffsetScevs, Depth);
937fcaf7f86SDimitry Andric
938fcaf7f86SDimitry Andric // See if we need to freeze our fork...
939fcaf7f86SDimitry Andric bool NeedsFreeze = any_of(BaseScevs, UndefPoisonCheck) ||
940fcaf7f86SDimitry Andric any_of(OffsetScevs, UndefPoisonCheck);
941fcaf7f86SDimitry Andric
942fcaf7f86SDimitry Andric // Check that we only have a single fork, on either the base or the offset.
943fcaf7f86SDimitry Andric // Copy the SCEV across for the one without a fork in order to generate
944fcaf7f86SDimitry Andric // the full SCEV for both sides of the GEP.
945fcaf7f86SDimitry Andric if (OffsetScevs.size() == 2 && BaseScevs.size() == 1)
946fcaf7f86SDimitry Andric BaseScevs.push_back(BaseScevs[0]);
947fcaf7f86SDimitry Andric else if (BaseScevs.size() == 2 && OffsetScevs.size() == 1)
948fcaf7f86SDimitry Andric OffsetScevs.push_back(OffsetScevs[0]);
949fcaf7f86SDimitry Andric else {
950bdd1243dSDimitry Andric ScevList.emplace_back(Scev, NeedsFreeze);
951fcaf7f86SDimitry Andric break;
952fcaf7f86SDimitry Andric }
953fcaf7f86SDimitry Andric
954fcaf7f86SDimitry Andric // Find the pointer type we need to extend to.
955fcaf7f86SDimitry Andric Type *IntPtrTy = SE->getEffectiveSCEVType(
956fcaf7f86SDimitry Andric SE->getSCEV(GEP->getPointerOperand())->getType());
957fcaf7f86SDimitry Andric
958fcaf7f86SDimitry Andric // Find the size of the type being pointed to. We only have a single
959fcaf7f86SDimitry Andric // index term (guarded above) so we don't need to index into arrays or
960fcaf7f86SDimitry Andric // structures, just get the size of the scalar value.
961fcaf7f86SDimitry Andric const SCEV *Size = SE->getSizeOfExpr(IntPtrTy, SourceTy);
962fcaf7f86SDimitry Andric
963fcaf7f86SDimitry Andric // Scale up the offsets by the size of the type, then add to the bases.
964fcaf7f86SDimitry Andric const SCEV *Scaled1 = SE->getMulExpr(
965bdd1243dSDimitry Andric Size, SE->getTruncateOrSignExtend(get<0>(OffsetScevs[0]), IntPtrTy));
966fcaf7f86SDimitry Andric const SCEV *Scaled2 = SE->getMulExpr(
967bdd1243dSDimitry Andric Size, SE->getTruncateOrSignExtend(get<0>(OffsetScevs[1]), IntPtrTy));
968bdd1243dSDimitry Andric ScevList.emplace_back(SE->getAddExpr(get<0>(BaseScevs[0]), Scaled1),
969bdd1243dSDimitry Andric NeedsFreeze);
970bdd1243dSDimitry Andric ScevList.emplace_back(SE->getAddExpr(get<0>(BaseScevs[1]), Scaled2),
971bdd1243dSDimitry Andric NeedsFreeze);
972fcaf7f86SDimitry Andric break;
973fcaf7f86SDimitry Andric }
974fcaf7f86SDimitry Andric case Instruction::Select: {
975bdd1243dSDimitry Andric SmallVector<PointerIntPair<const SCEV *, 1, bool>, 2> ChildScevs;
976fcaf7f86SDimitry Andric // A select means we've found a forked pointer, but we currently only
977fcaf7f86SDimitry Andric // support a single select per pointer so if there's another behind this
978fcaf7f86SDimitry Andric // then we just bail out and return the generic SCEV.
979fcaf7f86SDimitry Andric findForkedSCEVs(SE, L, I->getOperand(1), ChildScevs, Depth);
980fcaf7f86SDimitry Andric findForkedSCEVs(SE, L, I->getOperand(2), ChildScevs, Depth);
981fcaf7f86SDimitry Andric if (ChildScevs.size() == 2) {
982fcaf7f86SDimitry Andric ScevList.push_back(ChildScevs[0]);
983fcaf7f86SDimitry Andric ScevList.push_back(ChildScevs[1]);
984fcaf7f86SDimitry Andric } else
985bdd1243dSDimitry Andric ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr));
986bdd1243dSDimitry Andric break;
987bdd1243dSDimitry Andric }
988c9157d92SDimitry Andric case Instruction::PHI: {
989c9157d92SDimitry Andric SmallVector<PointerIntPair<const SCEV *, 1, bool>, 2> ChildScevs;
990c9157d92SDimitry Andric // A phi means we've found a forked pointer, but we currently only
991c9157d92SDimitry Andric // support a single phi per pointer so if there's another behind this
992c9157d92SDimitry Andric // then we just bail out and return the generic SCEV.
993c9157d92SDimitry Andric if (I->getNumOperands() == 2) {
994c9157d92SDimitry Andric findForkedSCEVs(SE, L, I->getOperand(0), ChildScevs, Depth);
995c9157d92SDimitry Andric findForkedSCEVs(SE, L, I->getOperand(1), ChildScevs, Depth);
996c9157d92SDimitry Andric }
997c9157d92SDimitry Andric if (ChildScevs.size() == 2) {
998c9157d92SDimitry Andric ScevList.push_back(ChildScevs[0]);
999c9157d92SDimitry Andric ScevList.push_back(ChildScevs[1]);
1000c9157d92SDimitry Andric } else
1001c9157d92SDimitry Andric ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr));
1002c9157d92SDimitry Andric break;
1003c9157d92SDimitry Andric }
1004bdd1243dSDimitry Andric case Instruction::Add:
1005bdd1243dSDimitry Andric case Instruction::Sub: {
1006bdd1243dSDimitry Andric SmallVector<PointerIntPair<const SCEV *, 1, bool>> LScevs;
1007bdd1243dSDimitry Andric SmallVector<PointerIntPair<const SCEV *, 1, bool>> RScevs;
1008bdd1243dSDimitry Andric findForkedSCEVs(SE, L, I->getOperand(0), LScevs, Depth);
1009bdd1243dSDimitry Andric findForkedSCEVs(SE, L, I->getOperand(1), RScevs, Depth);
1010bdd1243dSDimitry Andric
1011bdd1243dSDimitry Andric // See if we need to freeze our fork...
1012bdd1243dSDimitry Andric bool NeedsFreeze =
1013bdd1243dSDimitry Andric any_of(LScevs, UndefPoisonCheck) || any_of(RScevs, UndefPoisonCheck);
1014bdd1243dSDimitry Andric
1015bdd1243dSDimitry Andric // Check that we only have a single fork, on either the left or right side.
1016bdd1243dSDimitry Andric // Copy the SCEV across for the one without a fork in order to generate
1017bdd1243dSDimitry Andric // the full SCEV for both sides of the BinOp.
1018bdd1243dSDimitry Andric if (LScevs.size() == 2 && RScevs.size() == 1)
1019bdd1243dSDimitry Andric RScevs.push_back(RScevs[0]);
1020bdd1243dSDimitry Andric else if (RScevs.size() == 2 && LScevs.size() == 1)
1021bdd1243dSDimitry Andric LScevs.push_back(LScevs[0]);
1022bdd1243dSDimitry Andric else {
1023bdd1243dSDimitry Andric ScevList.emplace_back(Scev, NeedsFreeze);
1024bdd1243dSDimitry Andric break;
1025bdd1243dSDimitry Andric }
1026bdd1243dSDimitry Andric
1027bdd1243dSDimitry Andric ScevList.emplace_back(
1028bdd1243dSDimitry Andric GetBinOpExpr(Opcode, get<0>(LScevs[0]), get<0>(RScevs[0])),
1029bdd1243dSDimitry Andric NeedsFreeze);
1030bdd1243dSDimitry Andric ScevList.emplace_back(
1031bdd1243dSDimitry Andric GetBinOpExpr(Opcode, get<0>(LScevs[1]), get<0>(RScevs[1])),
1032bdd1243dSDimitry Andric NeedsFreeze);
1033fcaf7f86SDimitry Andric break;
1034fcaf7f86SDimitry Andric }
1035fcaf7f86SDimitry Andric default:
1036fcaf7f86SDimitry Andric // Just return the current SCEV if we haven't handled the instruction yet.
1037fcaf7f86SDimitry Andric LLVM_DEBUG(dbgs() << "ForkedPtr unhandled instruction: " << *I << "\n");
1038bdd1243dSDimitry Andric ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr));
1039fcaf7f86SDimitry Andric break;
1040fcaf7f86SDimitry Andric }
1041fcaf7f86SDimitry Andric }
1042fcaf7f86SDimitry Andric
1043bdd1243dSDimitry Andric static SmallVector<PointerIntPair<const SCEV *, 1, bool>>
findForkedPointer(PredicatedScalarEvolution & PSE,const DenseMap<Value *,const SCEV * > & StridesMap,Value * Ptr,const Loop * L)1044fcaf7f86SDimitry Andric findForkedPointer(PredicatedScalarEvolution &PSE,
1045fe013be4SDimitry Andric const DenseMap<Value *, const SCEV *> &StridesMap, Value *Ptr,
1046fcaf7f86SDimitry Andric const Loop *L) {
1047fcaf7f86SDimitry Andric ScalarEvolution *SE = PSE.getSE();
1048fcaf7f86SDimitry Andric assert(SE->isSCEVable(Ptr->getType()) && "Value is not SCEVable!");
1049bdd1243dSDimitry Andric SmallVector<PointerIntPair<const SCEV *, 1, bool>> Scevs;
1050fcaf7f86SDimitry Andric findForkedSCEVs(SE, L, Ptr, Scevs, MaxForkedSCEVDepth);
1051fcaf7f86SDimitry Andric
1052bdd1243dSDimitry Andric // For now, we will only accept a forked pointer with two possible SCEVs
1053bdd1243dSDimitry Andric // that are either SCEVAddRecExprs or loop invariant.
1054bdd1243dSDimitry Andric if (Scevs.size() == 2 &&
1055bdd1243dSDimitry Andric (isa<SCEVAddRecExpr>(get<0>(Scevs[0])) ||
1056bdd1243dSDimitry Andric SE->isLoopInvariant(get<0>(Scevs[0]), L)) &&
1057bdd1243dSDimitry Andric (isa<SCEVAddRecExpr>(get<0>(Scevs[1])) ||
1058bdd1243dSDimitry Andric SE->isLoopInvariant(get<0>(Scevs[1]), L))) {
1059bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Found forked pointer: " << *Ptr << "\n");
1060bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << "\t(1) " << *get<0>(Scevs[0]) << "\n");
1061bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << "\t(2) " << *get<0>(Scevs[1]) << "\n");
1062fcaf7f86SDimitry Andric return Scevs;
1063bdd1243dSDimitry Andric }
1064fcaf7f86SDimitry Andric
1065bdd1243dSDimitry Andric return {{replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr), false}};
1066fcaf7f86SDimitry Andric }
1067fcaf7f86SDimitry Andric
createCheckForAccess(RuntimePointerChecking & RtCheck,MemAccessInfo Access,Type * AccessTy,const DenseMap<Value *,const SCEV * > & StridesMap,DenseMap<Value *,unsigned> & DepSetId,Loop * TheLoop,unsigned & RunningDepId,unsigned ASId,bool ShouldCheckWrap,bool Assume)10680b57cec5SDimitry Andric bool AccessAnalysis::createCheckForAccess(RuntimePointerChecking &RtCheck,
106981ad6265SDimitry Andric MemAccessInfo Access, Type *AccessTy,
1070fe013be4SDimitry Andric const DenseMap<Value *, const SCEV *> &StridesMap,
10710b57cec5SDimitry Andric DenseMap<Value *, unsigned> &DepSetId,
10720b57cec5SDimitry Andric Loop *TheLoop, unsigned &RunningDepId,
10730b57cec5SDimitry Andric unsigned ASId, bool ShouldCheckWrap,
10740b57cec5SDimitry Andric bool Assume) {
10750b57cec5SDimitry Andric Value *Ptr = Access.getPointer();
10760b57cec5SDimitry Andric
1077bdd1243dSDimitry Andric SmallVector<PointerIntPair<const SCEV *, 1, bool>> TranslatedPtrs =
1078fcaf7f86SDimitry Andric findForkedPointer(PSE, StridesMap, Ptr, TheLoop);
107981ad6265SDimitry Andric
108081ad6265SDimitry Andric for (auto &P : TranslatedPtrs) {
1081bdd1243dSDimitry Andric const SCEV *PtrExpr = get<0>(P);
108281ad6265SDimitry Andric if (!hasComputableBounds(PSE, Ptr, PtrExpr, TheLoop, Assume))
10830b57cec5SDimitry Andric return false;
10840b57cec5SDimitry Andric
10850b57cec5SDimitry Andric // When we run after a failing dependency check we have to make sure
10860b57cec5SDimitry Andric // we don't have wrapping pointers.
108781ad6265SDimitry Andric if (ShouldCheckWrap) {
108881ad6265SDimitry Andric // Skip wrap checking when translating pointers.
108981ad6265SDimitry Andric if (TranslatedPtrs.size() > 1)
109081ad6265SDimitry Andric return false;
109181ad6265SDimitry Andric
109281ad6265SDimitry Andric if (!isNoWrap(PSE, StridesMap, Ptr, AccessTy, TheLoop)) {
10930b57cec5SDimitry Andric auto *Expr = PSE.getSCEV(Ptr);
10940b57cec5SDimitry Andric if (!Assume || !isa<SCEVAddRecExpr>(Expr))
10950b57cec5SDimitry Andric return false;
10960b57cec5SDimitry Andric PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
10970b57cec5SDimitry Andric }
109881ad6265SDimitry Andric }
109981ad6265SDimitry Andric // If there's only one option for Ptr, look it up after bounds and wrap
110081ad6265SDimitry Andric // checking, because assumptions might have been added to PSE.
110181ad6265SDimitry Andric if (TranslatedPtrs.size() == 1)
1102bdd1243dSDimitry Andric TranslatedPtrs[0] = {replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr),
1103bdd1243dSDimitry Andric false};
110481ad6265SDimitry Andric }
110581ad6265SDimitry Andric
1106bdd1243dSDimitry Andric for (auto [PtrExpr, NeedsFreeze] : TranslatedPtrs) {
11070b57cec5SDimitry Andric // The id of the dependence set.
11080b57cec5SDimitry Andric unsigned DepId;
11090b57cec5SDimitry Andric
11100b57cec5SDimitry Andric if (isDependencyCheckNeeded()) {
11110b57cec5SDimitry Andric Value *Leader = DepCands.getLeaderValue(Access).getPointer();
11120b57cec5SDimitry Andric unsigned &LeaderId = DepSetId[Leader];
11130b57cec5SDimitry Andric if (!LeaderId)
11140b57cec5SDimitry Andric LeaderId = RunningDepId++;
11150b57cec5SDimitry Andric DepId = LeaderId;
11160b57cec5SDimitry Andric } else
11170b57cec5SDimitry Andric // Each access has its own dependence set.
11180b57cec5SDimitry Andric DepId = RunningDepId++;
11190b57cec5SDimitry Andric
11200b57cec5SDimitry Andric bool IsWrite = Access.getInt();
112181ad6265SDimitry Andric RtCheck.insert(TheLoop, Ptr, PtrExpr, AccessTy, IsWrite, DepId, ASId, PSE,
1122bdd1243dSDimitry Andric NeedsFreeze);
11230b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
112481ad6265SDimitry Andric }
11250b57cec5SDimitry Andric
11260b57cec5SDimitry Andric return true;
11270b57cec5SDimitry Andric }
11280b57cec5SDimitry Andric
canCheckPtrAtRT(RuntimePointerChecking & RtCheck,ScalarEvolution * SE,Loop * TheLoop,const DenseMap<Value *,const SCEV * > & StridesMap,Value * & UncomputablePtr,bool ShouldCheckWrap)11290b57cec5SDimitry Andric bool AccessAnalysis::canCheckPtrAtRT(RuntimePointerChecking &RtCheck,
11300b57cec5SDimitry Andric ScalarEvolution *SE, Loop *TheLoop,
1131fe013be4SDimitry Andric const DenseMap<Value *, const SCEV *> &StridesMap,
113281ad6265SDimitry Andric Value *&UncomputablePtr, bool ShouldCheckWrap) {
11330b57cec5SDimitry Andric // Find pointers with computable bounds. We are going to use this information
11340b57cec5SDimitry Andric // to place a runtime bound check.
11350b57cec5SDimitry Andric bool CanDoRT = true;
11360b57cec5SDimitry Andric
11375ffd83dbSDimitry Andric bool MayNeedRTCheck = false;
11380b57cec5SDimitry Andric if (!IsRTCheckAnalysisNeeded) return true;
11390b57cec5SDimitry Andric
11400b57cec5SDimitry Andric bool IsDepCheckNeeded = isDependencyCheckNeeded();
11410b57cec5SDimitry Andric
11420b57cec5SDimitry Andric // We assign a consecutive id to access from different alias sets.
11430b57cec5SDimitry Andric // Accesses between different groups doesn't need to be checked.
11445ffd83dbSDimitry Andric unsigned ASId = 0;
11450b57cec5SDimitry Andric for (auto &AS : AST) {
11460b57cec5SDimitry Andric int NumReadPtrChecks = 0;
11470b57cec5SDimitry Andric int NumWritePtrChecks = 0;
11480b57cec5SDimitry Andric bool CanDoAliasSetRT = true;
11495ffd83dbSDimitry Andric ++ASId;
1150a58f00eaSDimitry Andric auto ASPointers = AS.getPointers();
11510b57cec5SDimitry Andric
11520b57cec5SDimitry Andric // We assign consecutive id to access from different dependence sets.
11530b57cec5SDimitry Andric // Accesses within the same set don't need a runtime check.
11540b57cec5SDimitry Andric unsigned RunningDepId = 1;
11550b57cec5SDimitry Andric DenseMap<Value *, unsigned> DepSetId;
11560b57cec5SDimitry Andric
1157fcaf7f86SDimitry Andric SmallVector<std::pair<MemAccessInfo, Type *>, 4> Retries;
11580b57cec5SDimitry Andric
11591106035dSDimitry Andric // First, count how many write and read accesses are in the alias set. Also
11601106035dSDimitry Andric // collect MemAccessInfos for later.
11611106035dSDimitry Andric SmallVector<MemAccessInfo, 4> AccessInfos;
1162a58f00eaSDimitry Andric for (const Value *Ptr_ : ASPointers) {
1163a58f00eaSDimitry Andric Value *Ptr = const_cast<Value *>(Ptr_);
11640b57cec5SDimitry Andric bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
11650b57cec5SDimitry Andric if (IsWrite)
11660b57cec5SDimitry Andric ++NumWritePtrChecks;
11670b57cec5SDimitry Andric else
11680b57cec5SDimitry Andric ++NumReadPtrChecks;
11691106035dSDimitry Andric AccessInfos.emplace_back(Ptr, IsWrite);
11700b57cec5SDimitry Andric }
11710b57cec5SDimitry Andric
11721106035dSDimitry Andric // We do not need runtime checks for this alias set, if there are no writes
11731106035dSDimitry Andric // or a single write and no reads.
11741106035dSDimitry Andric if (NumWritePtrChecks == 0 ||
11751106035dSDimitry Andric (NumWritePtrChecks == 1 && NumReadPtrChecks == 0)) {
1176a58f00eaSDimitry Andric assert((ASPointers.size() <= 1 ||
1177a58f00eaSDimitry Andric all_of(ASPointers,
1178a58f00eaSDimitry Andric [this](const Value *Ptr) {
1179a58f00eaSDimitry Andric MemAccessInfo AccessWrite(const_cast<Value *>(Ptr),
1180a58f00eaSDimitry Andric true);
11811106035dSDimitry Andric return DepCands.findValue(AccessWrite) == DepCands.end();
11825ffd83dbSDimitry Andric })) &&
11835ffd83dbSDimitry Andric "Can only skip updating CanDoRT below, if all entries in AS "
11845ffd83dbSDimitry Andric "are reads or there is at most 1 entry");
11855ffd83dbSDimitry Andric continue;
11865ffd83dbSDimitry Andric }
11871106035dSDimitry Andric
11881106035dSDimitry Andric for (auto &Access : AccessInfos) {
1189fcaf7f86SDimitry Andric for (const auto &AccessTy : Accesses[Access]) {
119081ad6265SDimitry Andric if (!createCheckForAccess(RtCheck, Access, AccessTy, StridesMap,
119181ad6265SDimitry Andric DepSetId, TheLoop, RunningDepId, ASId,
119281ad6265SDimitry Andric ShouldCheckWrap, false)) {
11931106035dSDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Can't find bounds for ptr:"
11941106035dSDimitry Andric << *Access.getPointer() << '\n');
1195fcaf7f86SDimitry Andric Retries.push_back({Access, AccessTy});
11961106035dSDimitry Andric CanDoAliasSetRT = false;
11975ffd83dbSDimitry Andric }
11981106035dSDimitry Andric }
119981ad6265SDimitry Andric }
12001106035dSDimitry Andric
12011106035dSDimitry Andric // Note that this function computes CanDoRT and MayNeedRTCheck
12021106035dSDimitry Andric // independently. For example CanDoRT=false, MayNeedRTCheck=false means that
12031106035dSDimitry Andric // we have a pointer for which we couldn't find the bounds but we don't
12041106035dSDimitry Andric // actually need to emit any checks so it does not matter.
12051106035dSDimitry Andric //
12061106035dSDimitry Andric // We need runtime checks for this alias set, if there are at least 2
12071106035dSDimitry Andric // dependence sets (in which case RunningDepId > 2) or if we need to re-try
12081106035dSDimitry Andric // any bound checks (because in that case the number of dependence sets is
12091106035dSDimitry Andric // incomplete).
12101106035dSDimitry Andric bool NeedsAliasSetRTCheck = RunningDepId > 2 || !Retries.empty();
12110b57cec5SDimitry Andric
12120b57cec5SDimitry Andric // We need to perform run-time alias checks, but some pointers had bounds
12130b57cec5SDimitry Andric // that couldn't be checked.
12140b57cec5SDimitry Andric if (NeedsAliasSetRTCheck && !CanDoAliasSetRT) {
12150b57cec5SDimitry Andric // Reset the CanDoSetRt flag and retry all accesses that have failed.
12160b57cec5SDimitry Andric // We know that we need these checks, so we can now be more aggressive
12170b57cec5SDimitry Andric // and add further checks if required (overflow checks).
12180b57cec5SDimitry Andric CanDoAliasSetRT = true;
1219fcaf7f86SDimitry Andric for (auto Retry : Retries) {
1220fcaf7f86SDimitry Andric MemAccessInfo Access = Retry.first;
1221fcaf7f86SDimitry Andric Type *AccessTy = Retry.second;
122281ad6265SDimitry Andric if (!createCheckForAccess(RtCheck, Access, AccessTy, StridesMap,
122381ad6265SDimitry Andric DepSetId, TheLoop, RunningDepId, ASId,
12240b57cec5SDimitry Andric ShouldCheckWrap, /*Assume=*/true)) {
12250b57cec5SDimitry Andric CanDoAliasSetRT = false;
122681ad6265SDimitry Andric UncomputablePtr = Access.getPointer();
12270b57cec5SDimitry Andric break;
12280b57cec5SDimitry Andric }
12290b57cec5SDimitry Andric }
123081ad6265SDimitry Andric }
12310b57cec5SDimitry Andric
12320b57cec5SDimitry Andric CanDoRT &= CanDoAliasSetRT;
12335ffd83dbSDimitry Andric MayNeedRTCheck |= NeedsAliasSetRTCheck;
12340b57cec5SDimitry Andric ++ASId;
12350b57cec5SDimitry Andric }
12360b57cec5SDimitry Andric
12370b57cec5SDimitry Andric // If the pointers that we would use for the bounds comparison have different
12380b57cec5SDimitry Andric // address spaces, assume the values aren't directly comparable, so we can't
12390b57cec5SDimitry Andric // use them for the runtime check. We also have to assume they could
12400b57cec5SDimitry Andric // overlap. In the future there should be metadata for whether address spaces
12410b57cec5SDimitry Andric // are disjoint.
12420b57cec5SDimitry Andric unsigned NumPointers = RtCheck.Pointers.size();
12430b57cec5SDimitry Andric for (unsigned i = 0; i < NumPointers; ++i) {
12440b57cec5SDimitry Andric for (unsigned j = i + 1; j < NumPointers; ++j) {
12450b57cec5SDimitry Andric // Only need to check pointers between two different dependency sets.
12460b57cec5SDimitry Andric if (RtCheck.Pointers[i].DependencySetId ==
12470b57cec5SDimitry Andric RtCheck.Pointers[j].DependencySetId)
12480b57cec5SDimitry Andric continue;
12490b57cec5SDimitry Andric // Only need to check pointers in the same alias set.
12500b57cec5SDimitry Andric if (RtCheck.Pointers[i].AliasSetId != RtCheck.Pointers[j].AliasSetId)
12510b57cec5SDimitry Andric continue;
12520b57cec5SDimitry Andric
12530b57cec5SDimitry Andric Value *PtrI = RtCheck.Pointers[i].PointerValue;
12540b57cec5SDimitry Andric Value *PtrJ = RtCheck.Pointers[j].PointerValue;
12550b57cec5SDimitry Andric
12560b57cec5SDimitry Andric unsigned ASi = PtrI->getType()->getPointerAddressSpace();
12570b57cec5SDimitry Andric unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
12580b57cec5SDimitry Andric if (ASi != ASj) {
12590b57cec5SDimitry Andric LLVM_DEBUG(
12600b57cec5SDimitry Andric dbgs() << "LAA: Runtime check would require comparison between"
12610b57cec5SDimitry Andric " different address spaces\n");
12620b57cec5SDimitry Andric return false;
12630b57cec5SDimitry Andric }
12640b57cec5SDimitry Andric }
12650b57cec5SDimitry Andric }
12660b57cec5SDimitry Andric
12675ffd83dbSDimitry Andric if (MayNeedRTCheck && CanDoRT)
12680b57cec5SDimitry Andric RtCheck.generateChecks(DepCands, IsDepCheckNeeded);
12690b57cec5SDimitry Andric
12700b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: We need to do " << RtCheck.getNumberOfChecks()
12710b57cec5SDimitry Andric << " pointer comparisons.\n");
12720b57cec5SDimitry Andric
12735ffd83dbSDimitry Andric // If we can do run-time checks, but there are no checks, no runtime checks
12745ffd83dbSDimitry Andric // are needed. This can happen when all pointers point to the same underlying
12755ffd83dbSDimitry Andric // object for example.
12765ffd83dbSDimitry Andric RtCheck.Need = CanDoRT ? RtCheck.getNumberOfChecks() != 0 : MayNeedRTCheck;
12770b57cec5SDimitry Andric
12785ffd83dbSDimitry Andric bool CanDoRTIfNeeded = !RtCheck.Need || CanDoRT;
12790b57cec5SDimitry Andric if (!CanDoRTIfNeeded)
12800b57cec5SDimitry Andric RtCheck.reset();
12810b57cec5SDimitry Andric return CanDoRTIfNeeded;
12820b57cec5SDimitry Andric }
12830b57cec5SDimitry Andric
processMemAccesses()12840b57cec5SDimitry Andric void AccessAnalysis::processMemAccesses() {
12850b57cec5SDimitry Andric // We process the set twice: first we process read-write pointers, last we
12860b57cec5SDimitry Andric // process read-only pointers. This allows us to skip dependence tests for
12870b57cec5SDimitry Andric // read-only pointers.
12880b57cec5SDimitry Andric
12890b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
12900b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " AST: "; AST.dump());
12910b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Accesses(" << Accesses.size() << "):\n");
12920b57cec5SDimitry Andric LLVM_DEBUG({
12930b57cec5SDimitry Andric for (auto A : Accesses)
129481ad6265SDimitry Andric dbgs() << "\t" << *A.first.getPointer() << " ("
129581ad6265SDimitry Andric << (A.first.getInt()
129681ad6265SDimitry Andric ? "write"
129781ad6265SDimitry Andric : (ReadOnlyPtr.count(A.first.getPointer()) ? "read-only"
129881ad6265SDimitry Andric : "read"))
129981ad6265SDimitry Andric << ")\n";
13000b57cec5SDimitry Andric });
13010b57cec5SDimitry Andric
13020b57cec5SDimitry Andric // The AliasSetTracker has nicely partitioned our pointers by metadata
13030b57cec5SDimitry Andric // compatibility and potential for underlying-object overlap. As a result, we
13040b57cec5SDimitry Andric // only need to check for potential pointer dependencies within each alias
13050b57cec5SDimitry Andric // set.
1306e8d8bef9SDimitry Andric for (const auto &AS : AST) {
13070b57cec5SDimitry Andric // Note that both the alias-set tracker and the alias sets themselves used
1308a58f00eaSDimitry Andric // ordered collections internally and so the iteration order here is
1309a58f00eaSDimitry Andric // deterministic.
1310a58f00eaSDimitry Andric auto ASPointers = AS.getPointers();
13110b57cec5SDimitry Andric
13120b57cec5SDimitry Andric bool SetHasWrite = false;
13130b57cec5SDimitry Andric
13140b57cec5SDimitry Andric // Map of pointers to last access encountered.
13150b57cec5SDimitry Andric typedef DenseMap<const Value*, MemAccessInfo> UnderlyingObjToAccessMap;
13160b57cec5SDimitry Andric UnderlyingObjToAccessMap ObjToLastAccess;
13170b57cec5SDimitry Andric
13180b57cec5SDimitry Andric // Set of access to check after all writes have been processed.
131981ad6265SDimitry Andric PtrAccessMap DeferredAccesses;
13200b57cec5SDimitry Andric
13210b57cec5SDimitry Andric // Iterate over each alias set twice, once to process read/write pointers,
13220b57cec5SDimitry Andric // and then to process read-only pointers.
13230b57cec5SDimitry Andric for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
13240b57cec5SDimitry Andric bool UseDeferred = SetIteration > 0;
132581ad6265SDimitry Andric PtrAccessMap &S = UseDeferred ? DeferredAccesses : Accesses;
13260b57cec5SDimitry Andric
1327a58f00eaSDimitry Andric for (const Value *Ptr_ : ASPointers) {
1328a58f00eaSDimitry Andric Value *Ptr = const_cast<Value *>(Ptr_);
13290b57cec5SDimitry Andric
13300b57cec5SDimitry Andric // For a single memory access in AliasSetTracker, Accesses may contain
13310b57cec5SDimitry Andric // both read and write, and they both need to be handled for CheckDeps.
1332e8d8bef9SDimitry Andric for (const auto &AC : S) {
133381ad6265SDimitry Andric if (AC.first.getPointer() != Ptr)
13340b57cec5SDimitry Andric continue;
13350b57cec5SDimitry Andric
133681ad6265SDimitry Andric bool IsWrite = AC.first.getInt();
13370b57cec5SDimitry Andric
13380b57cec5SDimitry Andric // If we're using the deferred access set, then it contains only
13390b57cec5SDimitry Andric // reads.
13400b57cec5SDimitry Andric bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
13410b57cec5SDimitry Andric if (UseDeferred && !IsReadOnlyPtr)
13420b57cec5SDimitry Andric continue;
13430b57cec5SDimitry Andric // Otherwise, the pointer must be in the PtrAccessSet, either as a
13440b57cec5SDimitry Andric // read or a write.
13450b57cec5SDimitry Andric assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
13460b57cec5SDimitry Andric S.count(MemAccessInfo(Ptr, false))) &&
13470b57cec5SDimitry Andric "Alias-set pointer not in the access set?");
13480b57cec5SDimitry Andric
13490b57cec5SDimitry Andric MemAccessInfo Access(Ptr, IsWrite);
13500b57cec5SDimitry Andric DepCands.insert(Access);
13510b57cec5SDimitry Andric
13520b57cec5SDimitry Andric // Memorize read-only pointers for later processing and skip them in
13530b57cec5SDimitry Andric // the first round (they need to be checked after we have seen all
13540b57cec5SDimitry Andric // write pointers). Note: we also mark pointer that are not
13550b57cec5SDimitry Andric // consecutive as "read-only" pointers (so that we check
13560b57cec5SDimitry Andric // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
13570b57cec5SDimitry Andric if (!UseDeferred && IsReadOnlyPtr) {
135881ad6265SDimitry Andric // We only use the pointer keys, the types vector values don't
135981ad6265SDimitry Andric // matter.
136081ad6265SDimitry Andric DeferredAccesses.insert({Access, {}});
13610b57cec5SDimitry Andric continue;
13620b57cec5SDimitry Andric }
13630b57cec5SDimitry Andric
13640b57cec5SDimitry Andric // If this is a write - check other reads and writes for conflicts. If
13650b57cec5SDimitry Andric // this is a read only check other writes for conflicts (but only if
13660b57cec5SDimitry Andric // there is no other write to the ptr - this is an optimization to
13670b57cec5SDimitry Andric // catch "a[i] = a[i] + " without having to do a dependence check).
13680b57cec5SDimitry Andric if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
13690b57cec5SDimitry Andric CheckDeps.push_back(Access);
13700b57cec5SDimitry Andric IsRTCheckAnalysisNeeded = true;
13710b57cec5SDimitry Andric }
13720b57cec5SDimitry Andric
13730b57cec5SDimitry Andric if (IsWrite)
13740b57cec5SDimitry Andric SetHasWrite = true;
13750b57cec5SDimitry Andric
13760b57cec5SDimitry Andric // Create sets of pointers connected by a shared alias set and
13770b57cec5SDimitry Andric // underlying object.
13780b57cec5SDimitry Andric typedef SmallVector<const Value *, 16> ValueVector;
13790b57cec5SDimitry Andric ValueVector TempObjects;
13800b57cec5SDimitry Andric
1381c9157d92SDimitry Andric UnderlyingObjects[Ptr] = {};
1382c9157d92SDimitry Andric SmallVector<const Value *, 16> &UOs = UnderlyingObjects[Ptr];
1383c9157d92SDimitry Andric ::getUnderlyingObjects(Ptr, UOs, LI);
13840b57cec5SDimitry Andric LLVM_DEBUG(dbgs()
13850b57cec5SDimitry Andric << "Underlying objects for pointer " << *Ptr << "\n");
1386c9157d92SDimitry Andric for (const Value *UnderlyingObj : UOs) {
13870b57cec5SDimitry Andric // nullptr never alias, don't join sets for pointer that have "null"
13880b57cec5SDimitry Andric // in their UnderlyingObjects list.
13890b57cec5SDimitry Andric if (isa<ConstantPointerNull>(UnderlyingObj) &&
13900b57cec5SDimitry Andric !NullPointerIsDefined(
13910b57cec5SDimitry Andric TheLoop->getHeader()->getParent(),
13920b57cec5SDimitry Andric UnderlyingObj->getType()->getPointerAddressSpace()))
13930b57cec5SDimitry Andric continue;
13940b57cec5SDimitry Andric
13950b57cec5SDimitry Andric UnderlyingObjToAccessMap::iterator Prev =
13960b57cec5SDimitry Andric ObjToLastAccess.find(UnderlyingObj);
13970b57cec5SDimitry Andric if (Prev != ObjToLastAccess.end())
13980b57cec5SDimitry Andric DepCands.unionSets(Access, Prev->second);
13990b57cec5SDimitry Andric
14000b57cec5SDimitry Andric ObjToLastAccess[UnderlyingObj] = Access;
14010b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " " << *UnderlyingObj << "\n");
14020b57cec5SDimitry Andric }
14030b57cec5SDimitry Andric }
14040b57cec5SDimitry Andric }
14050b57cec5SDimitry Andric }
14060b57cec5SDimitry Andric }
14070b57cec5SDimitry Andric }
14080b57cec5SDimitry Andric
14090b57cec5SDimitry Andric /// Return true if an AddRec pointer \p Ptr is unsigned non-wrapping,
14100b57cec5SDimitry Andric /// i.e. monotonically increasing/decreasing.
isNoWrapAddRec(Value * Ptr,const SCEVAddRecExpr * AR,PredicatedScalarEvolution & PSE,const Loop * L)14110b57cec5SDimitry Andric static bool isNoWrapAddRec(Value *Ptr, const SCEVAddRecExpr *AR,
14120b57cec5SDimitry Andric PredicatedScalarEvolution &PSE, const Loop *L) {
1413fe013be4SDimitry Andric
14140b57cec5SDimitry Andric // FIXME: This should probably only return true for NUW.
14150b57cec5SDimitry Andric if (AR->getNoWrapFlags(SCEV::NoWrapMask))
14160b57cec5SDimitry Andric return true;
14170b57cec5SDimitry Andric
1418fe013be4SDimitry Andric if (PSE.hasNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW))
1419fe013be4SDimitry Andric return true;
1420fe013be4SDimitry Andric
14210b57cec5SDimitry Andric // Scalar evolution does not propagate the non-wrapping flags to values that
14220b57cec5SDimitry Andric // are derived from a non-wrapping induction variable because non-wrapping
14230b57cec5SDimitry Andric // could be flow-sensitive.
14240b57cec5SDimitry Andric //
14250b57cec5SDimitry Andric // Look through the potentially overflowing instruction to try to prove
14260b57cec5SDimitry Andric // non-wrapping for the *specific* value of Ptr.
14270b57cec5SDimitry Andric
14280b57cec5SDimitry Andric // The arithmetic implied by an inbounds GEP can't overflow.
14290b57cec5SDimitry Andric auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
14300b57cec5SDimitry Andric if (!GEP || !GEP->isInBounds())
14310b57cec5SDimitry Andric return false;
14320b57cec5SDimitry Andric
14330b57cec5SDimitry Andric // Make sure there is only one non-const index and analyze that.
14340b57cec5SDimitry Andric Value *NonConstIndex = nullptr;
1435e8d8bef9SDimitry Andric for (Value *Index : GEP->indices())
14360b57cec5SDimitry Andric if (!isa<ConstantInt>(Index)) {
14370b57cec5SDimitry Andric if (NonConstIndex)
14380b57cec5SDimitry Andric return false;
14390b57cec5SDimitry Andric NonConstIndex = Index;
14400b57cec5SDimitry Andric }
14410b57cec5SDimitry Andric if (!NonConstIndex)
14420b57cec5SDimitry Andric // The recurrence is on the pointer, ignore for now.
14430b57cec5SDimitry Andric return false;
14440b57cec5SDimitry Andric
14450b57cec5SDimitry Andric // The index in GEP is signed. It is non-wrapping if it's derived from a NSW
14460b57cec5SDimitry Andric // AddRec using a NSW operation.
14470b57cec5SDimitry Andric if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(NonConstIndex))
14480b57cec5SDimitry Andric if (OBO->hasNoSignedWrap() &&
14490b57cec5SDimitry Andric // Assume constant for other the operand so that the AddRec can be
14500b57cec5SDimitry Andric // easily found.
14510b57cec5SDimitry Andric isa<ConstantInt>(OBO->getOperand(1))) {
14520b57cec5SDimitry Andric auto *OpScev = PSE.getSCEV(OBO->getOperand(0));
14530b57cec5SDimitry Andric
14540b57cec5SDimitry Andric if (auto *OpAR = dyn_cast<SCEVAddRecExpr>(OpScev))
14550b57cec5SDimitry Andric return OpAR->getLoop() == L && OpAR->getNoWrapFlags(SCEV::FlagNSW);
14560b57cec5SDimitry Andric }
14570b57cec5SDimitry Andric
14580b57cec5SDimitry Andric return false;
14590b57cec5SDimitry Andric }
14600b57cec5SDimitry Andric
14610b57cec5SDimitry Andric /// Check whether the access through \p Ptr has a constant stride.
getPtrStride(PredicatedScalarEvolution & PSE,Type * AccessTy,Value * Ptr,const Loop * Lp,const DenseMap<Value *,const SCEV * > & StridesMap,bool Assume,bool ShouldCheckWrap)1462bdd1243dSDimitry Andric std::optional<int64_t> llvm::getPtrStride(PredicatedScalarEvolution &PSE,
1463bdd1243dSDimitry Andric Type *AccessTy, Value *Ptr,
1464bdd1243dSDimitry Andric const Loop *Lp,
1465fe013be4SDimitry Andric const DenseMap<Value *, const SCEV *> &StridesMap,
1466bdd1243dSDimitry Andric bool Assume, bool ShouldCheckWrap) {
14670b57cec5SDimitry Andric Type *Ty = Ptr->getType();
14680b57cec5SDimitry Andric assert(Ty->isPointerTy() && "Unexpected non-ptr");
14690b57cec5SDimitry Andric
14704824e7fdSDimitry Andric if (isa<ScalableVectorType>(AccessTy)) {
14714824e7fdSDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Bad stride - Scalable object: " << *AccessTy
14724824e7fdSDimitry Andric << "\n");
1473bdd1243dSDimitry Andric return std::nullopt;
14740b57cec5SDimitry Andric }
14750b57cec5SDimitry Andric
14760b57cec5SDimitry Andric const SCEV *PtrScev = replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr);
14770b57cec5SDimitry Andric
14780b57cec5SDimitry Andric const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
14790b57cec5SDimitry Andric if (Assume && !AR)
14800b57cec5SDimitry Andric AR = PSE.getAsAddRec(Ptr);
14810b57cec5SDimitry Andric
14820b57cec5SDimitry Andric if (!AR) {
14830b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer " << *Ptr
14840b57cec5SDimitry Andric << " SCEV: " << *PtrScev << "\n");
1485bdd1243dSDimitry Andric return std::nullopt;
14860b57cec5SDimitry Andric }
14870b57cec5SDimitry Andric
14880b57cec5SDimitry Andric // The access function must stride over the innermost loop.
14890b57cec5SDimitry Andric if (Lp != AR->getLoop()) {
14900b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop "
14910b57cec5SDimitry Andric << *Ptr << " SCEV: " << *AR << "\n");
1492bdd1243dSDimitry Andric return std::nullopt;
14930b57cec5SDimitry Andric }
14940b57cec5SDimitry Andric
14950b57cec5SDimitry Andric // Check the step is constant.
14960b57cec5SDimitry Andric const SCEV *Step = AR->getStepRecurrence(*PSE.getSE());
14970b57cec5SDimitry Andric
14980b57cec5SDimitry Andric // Calculate the pointer stride and check if it is constant.
14990b57cec5SDimitry Andric const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
15000b57cec5SDimitry Andric if (!C) {
15010b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr
15020b57cec5SDimitry Andric << " SCEV: " << *AR << "\n");
1503bdd1243dSDimitry Andric return std::nullopt;
15040b57cec5SDimitry Andric }
15050b57cec5SDimitry Andric
15060b57cec5SDimitry Andric auto &DL = Lp->getHeader()->getModule()->getDataLayout();
15074824e7fdSDimitry Andric TypeSize AllocSize = DL.getTypeAllocSize(AccessTy);
1508bdd1243dSDimitry Andric int64_t Size = AllocSize.getFixedValue();
15090b57cec5SDimitry Andric const APInt &APStepVal = C->getAPInt();
15100b57cec5SDimitry Andric
15110b57cec5SDimitry Andric // Huge step value - give up.
15120b57cec5SDimitry Andric if (APStepVal.getBitWidth() > 64)
1513bdd1243dSDimitry Andric return std::nullopt;
15140b57cec5SDimitry Andric
15150b57cec5SDimitry Andric int64_t StepVal = APStepVal.getSExtValue();
15160b57cec5SDimitry Andric
15170b57cec5SDimitry Andric // Strided access.
15180b57cec5SDimitry Andric int64_t Stride = StepVal / Size;
15190b57cec5SDimitry Andric int64_t Rem = StepVal % Size;
15200b57cec5SDimitry Andric if (Rem)
1521bdd1243dSDimitry Andric return std::nullopt;
15220b57cec5SDimitry Andric
1523fe013be4SDimitry Andric if (!ShouldCheckWrap)
1524fe013be4SDimitry Andric return Stride;
1525fe013be4SDimitry Andric
1526fe013be4SDimitry Andric // The address calculation must not wrap. Otherwise, a dependence could be
1527fe013be4SDimitry Andric // inverted.
1528fe013be4SDimitry Andric if (isNoWrapAddRec(Ptr, AR, PSE, Lp))
1529fe013be4SDimitry Andric return Stride;
1530fe013be4SDimitry Andric
1531fe013be4SDimitry Andric // An inbounds getelementptr that is a AddRec with a unit stride
1532fe013be4SDimitry Andric // cannot wrap per definition. If it did, the result would be poison
1533fe013be4SDimitry Andric // and any memory access dependent on it would be immediate UB
1534fe013be4SDimitry Andric // when executed.
1535fe013be4SDimitry Andric if (auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
1536fe013be4SDimitry Andric GEP && GEP->isInBounds() && (Stride == 1 || Stride == -1))
1537fe013be4SDimitry Andric return Stride;
1538fe013be4SDimitry Andric
1539fe013be4SDimitry Andric // If the null pointer is undefined, then a access sequence which would
1540fe013be4SDimitry Andric // otherwise access it can be assumed not to unsigned wrap. Note that this
1541fe013be4SDimitry Andric // assumes the object in memory is aligned to the natural alignment.
1542fe013be4SDimitry Andric unsigned AddrSpace = Ty->getPointerAddressSpace();
1543fe013be4SDimitry Andric if (!NullPointerIsDefined(Lp->getHeader()->getParent(), AddrSpace) &&
1544fe013be4SDimitry Andric (Stride == 1 || Stride == -1))
1545fe013be4SDimitry Andric return Stride;
1546fe013be4SDimitry Andric
15470b57cec5SDimitry Andric if (Assume) {
1548fe013be4SDimitry Andric PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
1549fe013be4SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Pointer may wrap:\n"
15500b57cec5SDimitry Andric << "LAA: Pointer: " << *Ptr << "\n"
15510b57cec5SDimitry Andric << "LAA: SCEV: " << *AR << "\n"
15520b57cec5SDimitry Andric << "LAA: Added an overflow assumption\n");
15530b57cec5SDimitry Andric return Stride;
15540b57cec5SDimitry Andric }
1555fe013be4SDimitry Andric LLVM_DEBUG(
1556fe013be4SDimitry Andric dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
1557fe013be4SDimitry Andric << *Ptr << " SCEV: " << *AR << "\n");
1558fe013be4SDimitry Andric return std::nullopt;
1559fe013be4SDimitry Andric }
15600b57cec5SDimitry Andric
getPointersDiff(Type * ElemTyA,Value * PtrA,Type * ElemTyB,Value * PtrB,const DataLayout & DL,ScalarEvolution & SE,bool StrictCheck,bool CheckType)1561bdd1243dSDimitry Andric std::optional<int> llvm::getPointersDiff(Type *ElemTyA, Value *PtrA,
1562bdd1243dSDimitry Andric Type *ElemTyB, Value *PtrB,
1563bdd1243dSDimitry Andric const DataLayout &DL,
1564fe6060f1SDimitry Andric ScalarEvolution &SE, bool StrictCheck,
1565fe6060f1SDimitry Andric bool CheckType) {
1566fe6060f1SDimitry Andric assert(PtrA && PtrB && "Expected non-nullptr pointers.");
1567fe6060f1SDimitry Andric
1568fe6060f1SDimitry Andric // Make sure that A and B are different pointers.
1569fe6060f1SDimitry Andric if (PtrA == PtrB)
1570fe6060f1SDimitry Andric return 0;
1571fe6060f1SDimitry Andric
1572fe6060f1SDimitry Andric // Make sure that the element types are the same if required.
1573fe6060f1SDimitry Andric if (CheckType && ElemTyA != ElemTyB)
1574bdd1243dSDimitry Andric return std::nullopt;
1575fe6060f1SDimitry Andric
1576fe6060f1SDimitry Andric unsigned ASA = PtrA->getType()->getPointerAddressSpace();
1577fe6060f1SDimitry Andric unsigned ASB = PtrB->getType()->getPointerAddressSpace();
1578fe6060f1SDimitry Andric
1579fe6060f1SDimitry Andric // Check that the address spaces match.
1580fe6060f1SDimitry Andric if (ASA != ASB)
1581bdd1243dSDimitry Andric return std::nullopt;
1582fe6060f1SDimitry Andric unsigned IdxWidth = DL.getIndexSizeInBits(ASA);
1583fe6060f1SDimitry Andric
1584fe6060f1SDimitry Andric APInt OffsetA(IdxWidth, 0), OffsetB(IdxWidth, 0);
1585fe6060f1SDimitry Andric Value *PtrA1 = PtrA->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetA);
1586fe6060f1SDimitry Andric Value *PtrB1 = PtrB->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetB);
1587fe6060f1SDimitry Andric
1588fe6060f1SDimitry Andric int Val;
1589fe6060f1SDimitry Andric if (PtrA1 == PtrB1) {
1590fe6060f1SDimitry Andric // Retrieve the address space again as pointer stripping now tracks through
1591fe6060f1SDimitry Andric // `addrspacecast`.
1592fe6060f1SDimitry Andric ASA = cast<PointerType>(PtrA1->getType())->getAddressSpace();
1593fe6060f1SDimitry Andric ASB = cast<PointerType>(PtrB1->getType())->getAddressSpace();
1594fe6060f1SDimitry Andric // Check that the address spaces match and that the pointers are valid.
1595fe6060f1SDimitry Andric if (ASA != ASB)
1596bdd1243dSDimitry Andric return std::nullopt;
1597fe6060f1SDimitry Andric
1598fe6060f1SDimitry Andric IdxWidth = DL.getIndexSizeInBits(ASA);
1599fe6060f1SDimitry Andric OffsetA = OffsetA.sextOrTrunc(IdxWidth);
1600fe6060f1SDimitry Andric OffsetB = OffsetB.sextOrTrunc(IdxWidth);
1601fe6060f1SDimitry Andric
1602fe6060f1SDimitry Andric OffsetB -= OffsetA;
1603fe6060f1SDimitry Andric Val = OffsetB.getSExtValue();
1604fe6060f1SDimitry Andric } else {
1605fe6060f1SDimitry Andric // Otherwise compute the distance with SCEV between the base pointers.
1606fe6060f1SDimitry Andric const SCEV *PtrSCEVA = SE.getSCEV(PtrA);
1607fe6060f1SDimitry Andric const SCEV *PtrSCEVB = SE.getSCEV(PtrB);
1608fe6060f1SDimitry Andric const auto *Diff =
1609fe6060f1SDimitry Andric dyn_cast<SCEVConstant>(SE.getMinusSCEV(PtrSCEVB, PtrSCEVA));
1610fe6060f1SDimitry Andric if (!Diff)
1611bdd1243dSDimitry Andric return std::nullopt;
1612fe6060f1SDimitry Andric Val = Diff->getAPInt().getSExtValue();
1613fe6060f1SDimitry Andric }
1614fe6060f1SDimitry Andric int Size = DL.getTypeStoreSize(ElemTyA);
1615fe6060f1SDimitry Andric int Dist = Val / Size;
1616fe6060f1SDimitry Andric
1617fe6060f1SDimitry Andric // Ensure that the calculated distance matches the type-based one after all
1618fe6060f1SDimitry Andric // the bitcasts removal in the provided pointers.
1619fe6060f1SDimitry Andric if (!StrictCheck || Dist * Size == Val)
1620fe6060f1SDimitry Andric return Dist;
1621bdd1243dSDimitry Andric return std::nullopt;
1622fe6060f1SDimitry Andric }
1623fe6060f1SDimitry Andric
sortPtrAccesses(ArrayRef<Value * > VL,Type * ElemTy,const DataLayout & DL,ScalarEvolution & SE,SmallVectorImpl<unsigned> & SortedIndices)1624fe6060f1SDimitry Andric bool llvm::sortPtrAccesses(ArrayRef<Value *> VL, Type *ElemTy,
1625fe6060f1SDimitry Andric const DataLayout &DL, ScalarEvolution &SE,
16260b57cec5SDimitry Andric SmallVectorImpl<unsigned> &SortedIndices) {
16270b57cec5SDimitry Andric assert(llvm::all_of(
16280b57cec5SDimitry Andric VL, [](const Value *V) { return V->getType()->isPointerTy(); }) &&
16290b57cec5SDimitry Andric "Expected list of pointer operands.");
16300b57cec5SDimitry Andric // Walk over the pointers, and map each of them to an offset relative to
16310b57cec5SDimitry Andric // first pointer in the array.
16320b57cec5SDimitry Andric Value *Ptr0 = VL[0];
16330b57cec5SDimitry Andric
1634fe6060f1SDimitry Andric using DistOrdPair = std::pair<int64_t, int>;
1635972a253aSDimitry Andric auto Compare = llvm::less_first();
1636fe6060f1SDimitry Andric std::set<DistOrdPair, decltype(Compare)> Offsets(Compare);
1637fe6060f1SDimitry Andric Offsets.emplace(0, 0);
1638fe6060f1SDimitry Andric int Cnt = 1;
1639fe6060f1SDimitry Andric bool IsConsecutive = true;
1640fe6060f1SDimitry Andric for (auto *Ptr : VL.drop_front()) {
1641bdd1243dSDimitry Andric std::optional<int> Diff = getPointersDiff(ElemTy, Ptr0, ElemTy, Ptr, DL, SE,
1642fe6060f1SDimitry Andric /*StrictCheck=*/true);
16430b57cec5SDimitry Andric if (!Diff)
16440b57cec5SDimitry Andric return false;
16450b57cec5SDimitry Andric
16460b57cec5SDimitry Andric // Check if the pointer with the same offset is found.
1647fe6060f1SDimitry Andric int64_t Offset = *Diff;
1648fe6060f1SDimitry Andric auto Res = Offsets.emplace(Offset, Cnt);
1649fe6060f1SDimitry Andric if (!Res.second)
16500b57cec5SDimitry Andric return false;
1651fe6060f1SDimitry Andric // Consecutive order if the inserted element is the last one.
1652fe6060f1SDimitry Andric IsConsecutive = IsConsecutive && std::next(Res.first) == Offsets.end();
1653fe6060f1SDimitry Andric ++Cnt;
16540b57cec5SDimitry Andric }
16550b57cec5SDimitry Andric SortedIndices.clear();
1656fe6060f1SDimitry Andric if (!IsConsecutive) {
1657fe6060f1SDimitry Andric // Fill SortedIndices array only if it is non-consecutive.
16580b57cec5SDimitry Andric SortedIndices.resize(VL.size());
1659fe6060f1SDimitry Andric Cnt = 0;
1660fe6060f1SDimitry Andric for (const std::pair<int64_t, int> &Pair : Offsets) {
1661fe6060f1SDimitry Andric SortedIndices[Cnt] = Pair.second;
1662fe6060f1SDimitry Andric ++Cnt;
16630b57cec5SDimitry Andric }
1664fe6060f1SDimitry Andric }
1665fe6060f1SDimitry Andric return true;
16660b57cec5SDimitry Andric }
16670b57cec5SDimitry Andric
16680b57cec5SDimitry Andric /// Returns true if the memory operations \p A and \p B are consecutive.
isConsecutiveAccess(Value * A,Value * B,const DataLayout & DL,ScalarEvolution & SE,bool CheckType)16690b57cec5SDimitry Andric bool llvm::isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL,
16700b57cec5SDimitry Andric ScalarEvolution &SE, bool CheckType) {
16710b57cec5SDimitry Andric Value *PtrA = getLoadStorePointerOperand(A);
16720b57cec5SDimitry Andric Value *PtrB = getLoadStorePointerOperand(B);
1673fe6060f1SDimitry Andric if (!PtrA || !PtrB)
16740b57cec5SDimitry Andric return false;
1675fe6060f1SDimitry Andric Type *ElemTyA = getLoadStoreType(A);
1676fe6060f1SDimitry Andric Type *ElemTyB = getLoadStoreType(B);
1677bdd1243dSDimitry Andric std::optional<int> Diff =
1678bdd1243dSDimitry Andric getPointersDiff(ElemTyA, PtrA, ElemTyB, PtrB, DL, SE,
1679fe6060f1SDimitry Andric /*StrictCheck=*/true, CheckType);
1680fe6060f1SDimitry Andric return Diff && *Diff == 1;
16810b57cec5SDimitry Andric }
16820b57cec5SDimitry Andric
addAccess(StoreInst * SI)1683349cc55cSDimitry Andric void MemoryDepChecker::addAccess(StoreInst *SI) {
1684349cc55cSDimitry Andric visitPointers(SI->getPointerOperand(), *InnermostLoop,
1685349cc55cSDimitry Andric [this, SI](Value *Ptr) {
1686349cc55cSDimitry Andric Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
1687349cc55cSDimitry Andric InstMap.push_back(SI);
1688349cc55cSDimitry Andric ++AccessIdx;
1689349cc55cSDimitry Andric });
1690349cc55cSDimitry Andric }
1691349cc55cSDimitry Andric
addAccess(LoadInst * LI)1692349cc55cSDimitry Andric void MemoryDepChecker::addAccess(LoadInst *LI) {
1693349cc55cSDimitry Andric visitPointers(LI->getPointerOperand(), *InnermostLoop,
1694349cc55cSDimitry Andric [this, LI](Value *Ptr) {
1695349cc55cSDimitry Andric Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
1696349cc55cSDimitry Andric InstMap.push_back(LI);
1697349cc55cSDimitry Andric ++AccessIdx;
1698349cc55cSDimitry Andric });
1699349cc55cSDimitry Andric }
1700349cc55cSDimitry Andric
17010b57cec5SDimitry Andric MemoryDepChecker::VectorizationSafetyStatus
isSafeForVectorization(DepType Type)17020b57cec5SDimitry Andric MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
17030b57cec5SDimitry Andric switch (Type) {
17040b57cec5SDimitry Andric case NoDep:
17050b57cec5SDimitry Andric case Forward:
17060b57cec5SDimitry Andric case BackwardVectorizable:
17070b57cec5SDimitry Andric return VectorizationSafetyStatus::Safe;
17080b57cec5SDimitry Andric
17090b57cec5SDimitry Andric case Unknown:
17100b57cec5SDimitry Andric return VectorizationSafetyStatus::PossiblySafeWithRtChecks;
17110b57cec5SDimitry Andric case ForwardButPreventsForwarding:
17120b57cec5SDimitry Andric case Backward:
17130b57cec5SDimitry Andric case BackwardVectorizableButPreventsForwarding:
1714c9157d92SDimitry Andric case IndirectUnsafe:
17150b57cec5SDimitry Andric return VectorizationSafetyStatus::Unsafe;
17160b57cec5SDimitry Andric }
17170b57cec5SDimitry Andric llvm_unreachable("unexpected DepType!");
17180b57cec5SDimitry Andric }
17190b57cec5SDimitry Andric
isBackward() const17200b57cec5SDimitry Andric bool MemoryDepChecker::Dependence::isBackward() const {
17210b57cec5SDimitry Andric switch (Type) {
17220b57cec5SDimitry Andric case NoDep:
17230b57cec5SDimitry Andric case Forward:
17240b57cec5SDimitry Andric case ForwardButPreventsForwarding:
17250b57cec5SDimitry Andric case Unknown:
1726c9157d92SDimitry Andric case IndirectUnsafe:
17270b57cec5SDimitry Andric return false;
17280b57cec5SDimitry Andric
17290b57cec5SDimitry Andric case BackwardVectorizable:
17300b57cec5SDimitry Andric case Backward:
17310b57cec5SDimitry Andric case BackwardVectorizableButPreventsForwarding:
17320b57cec5SDimitry Andric return true;
17330b57cec5SDimitry Andric }
17340b57cec5SDimitry Andric llvm_unreachable("unexpected DepType!");
17350b57cec5SDimitry Andric }
17360b57cec5SDimitry Andric
isPossiblyBackward() const17370b57cec5SDimitry Andric bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
17380b57cec5SDimitry Andric return isBackward() || Type == Unknown;
17390b57cec5SDimitry Andric }
17400b57cec5SDimitry Andric
isForward() const17410b57cec5SDimitry Andric bool MemoryDepChecker::Dependence::isForward() const {
17420b57cec5SDimitry Andric switch (Type) {
17430b57cec5SDimitry Andric case Forward:
17440b57cec5SDimitry Andric case ForwardButPreventsForwarding:
17450b57cec5SDimitry Andric return true;
17460b57cec5SDimitry Andric
17470b57cec5SDimitry Andric case NoDep:
17480b57cec5SDimitry Andric case Unknown:
17490b57cec5SDimitry Andric case BackwardVectorizable:
17500b57cec5SDimitry Andric case Backward:
17510b57cec5SDimitry Andric case BackwardVectorizableButPreventsForwarding:
1752c9157d92SDimitry Andric case IndirectUnsafe:
17530b57cec5SDimitry Andric return false;
17540b57cec5SDimitry Andric }
17550b57cec5SDimitry Andric llvm_unreachable("unexpected DepType!");
17560b57cec5SDimitry Andric }
17570b57cec5SDimitry Andric
couldPreventStoreLoadForward(uint64_t Distance,uint64_t TypeByteSize)17580b57cec5SDimitry Andric bool MemoryDepChecker::couldPreventStoreLoadForward(uint64_t Distance,
17590b57cec5SDimitry Andric uint64_t TypeByteSize) {
17600b57cec5SDimitry Andric // If loads occur at a distance that is not a multiple of a feasible vector
17610b57cec5SDimitry Andric // factor store-load forwarding does not take place.
17620b57cec5SDimitry Andric // Positive dependences might cause troubles because vectorizing them might
17630b57cec5SDimitry Andric // prevent store-load forwarding making vectorized code run a lot slower.
17640b57cec5SDimitry Andric // a[i] = a[i-3] ^ a[i-8];
17650b57cec5SDimitry Andric // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
17660b57cec5SDimitry Andric // hence on your typical architecture store-load forwarding does not take
17670b57cec5SDimitry Andric // place. Vectorizing in such cases does not make sense.
17680b57cec5SDimitry Andric // Store-load forwarding distance.
17690b57cec5SDimitry Andric
17700b57cec5SDimitry Andric // After this many iterations store-to-load forwarding conflicts should not
17710b57cec5SDimitry Andric // cause any slowdowns.
17720b57cec5SDimitry Andric const uint64_t NumItersForStoreLoadThroughMemory = 8 * TypeByteSize;
17730b57cec5SDimitry Andric // Maximum vector factor.
17740b57cec5SDimitry Andric uint64_t MaxVFWithoutSLForwardIssues = std::min(
1775c9157d92SDimitry Andric VectorizerParams::MaxVectorWidth * TypeByteSize, MinDepDistBytes);
17760b57cec5SDimitry Andric
17770b57cec5SDimitry Andric // Compute the smallest VF at which the store and load would be misaligned.
17780b57cec5SDimitry Andric for (uint64_t VF = 2 * TypeByteSize; VF <= MaxVFWithoutSLForwardIssues;
17790b57cec5SDimitry Andric VF *= 2) {
17800b57cec5SDimitry Andric // If the number of vector iteration between the store and the load are
17810b57cec5SDimitry Andric // small we could incur conflicts.
17820b57cec5SDimitry Andric if (Distance % VF && Distance / VF < NumItersForStoreLoadThroughMemory) {
1783e8d8bef9SDimitry Andric MaxVFWithoutSLForwardIssues = (VF >> 1);
17840b57cec5SDimitry Andric break;
17850b57cec5SDimitry Andric }
17860b57cec5SDimitry Andric }
17870b57cec5SDimitry Andric
17880b57cec5SDimitry Andric if (MaxVFWithoutSLForwardIssues < 2 * TypeByteSize) {
17890b57cec5SDimitry Andric LLVM_DEBUG(
17900b57cec5SDimitry Andric dbgs() << "LAA: Distance " << Distance
17910b57cec5SDimitry Andric << " that could cause a store-load forwarding conflict\n");
17920b57cec5SDimitry Andric return true;
17930b57cec5SDimitry Andric }
17940b57cec5SDimitry Andric
1795c9157d92SDimitry Andric if (MaxVFWithoutSLForwardIssues < MinDepDistBytes &&
17960b57cec5SDimitry Andric MaxVFWithoutSLForwardIssues !=
17970b57cec5SDimitry Andric VectorizerParams::MaxVectorWidth * TypeByteSize)
1798c9157d92SDimitry Andric MinDepDistBytes = MaxVFWithoutSLForwardIssues;
17990b57cec5SDimitry Andric return false;
18000b57cec5SDimitry Andric }
18010b57cec5SDimitry Andric
mergeInStatus(VectorizationSafetyStatus S)18020b57cec5SDimitry Andric void MemoryDepChecker::mergeInStatus(VectorizationSafetyStatus S) {
18030b57cec5SDimitry Andric if (Status < S)
18040b57cec5SDimitry Andric Status = S;
18050b57cec5SDimitry Andric }
18060b57cec5SDimitry Andric
1807bdd1243dSDimitry Andric /// Given a dependence-distance \p Dist between two
18080b57cec5SDimitry Andric /// memory accesses, that have the same stride whose absolute value is given
18090b57cec5SDimitry Andric /// in \p Stride, and that have the same type size \p TypeByteSize,
18100b57cec5SDimitry Andric /// in a loop whose takenCount is \p BackedgeTakenCount, check if it is
18110b57cec5SDimitry Andric /// possible to prove statically that the dependence distance is larger
18120b57cec5SDimitry Andric /// than the range that the accesses will travel through the execution of
18130b57cec5SDimitry Andric /// the loop. If so, return true; false otherwise. This is useful for
18140b57cec5SDimitry Andric /// example in loops such as the following (PR31098):
18150b57cec5SDimitry Andric /// for (i = 0; i < D; ++i) {
18160b57cec5SDimitry Andric /// = out[i];
18170b57cec5SDimitry Andric /// out[i+D] =
18180b57cec5SDimitry Andric /// }
isSafeDependenceDistance(const DataLayout & DL,ScalarEvolution & SE,const SCEV & BackedgeTakenCount,const SCEV & Dist,uint64_t Stride,uint64_t TypeByteSize)18190b57cec5SDimitry Andric static bool isSafeDependenceDistance(const DataLayout &DL, ScalarEvolution &SE,
18200b57cec5SDimitry Andric const SCEV &BackedgeTakenCount,
18210b57cec5SDimitry Andric const SCEV &Dist, uint64_t Stride,
18220b57cec5SDimitry Andric uint64_t TypeByteSize) {
18230b57cec5SDimitry Andric
18240b57cec5SDimitry Andric // If we can prove that
18250b57cec5SDimitry Andric // (**) |Dist| > BackedgeTakenCount * Step
18260b57cec5SDimitry Andric // where Step is the absolute stride of the memory accesses in bytes,
18270b57cec5SDimitry Andric // then there is no dependence.
18280b57cec5SDimitry Andric //
18290b57cec5SDimitry Andric // Rationale:
18300b57cec5SDimitry Andric // We basically want to check if the absolute distance (|Dist/Step|)
18310b57cec5SDimitry Andric // is >= the loop iteration count (or > BackedgeTakenCount).
18320b57cec5SDimitry Andric // This is equivalent to the Strong SIV Test (Practical Dependence Testing,
18330b57cec5SDimitry Andric // Section 4.2.1); Note, that for vectorization it is sufficient to prove
18340b57cec5SDimitry Andric // that the dependence distance is >= VF; This is checked elsewhere.
1835bdd1243dSDimitry Andric // But in some cases we can prune dependence distances early, and
18360b57cec5SDimitry Andric // even before selecting the VF, and without a runtime test, by comparing
18370b57cec5SDimitry Andric // the distance against the loop iteration count. Since the vectorized code
18380b57cec5SDimitry Andric // will be executed only if LoopCount >= VF, proving distance >= LoopCount
18390b57cec5SDimitry Andric // also guarantees that distance >= VF.
18400b57cec5SDimitry Andric //
18410b57cec5SDimitry Andric const uint64_t ByteStride = Stride * TypeByteSize;
18420b57cec5SDimitry Andric const SCEV *Step = SE.getConstant(BackedgeTakenCount.getType(), ByteStride);
18430b57cec5SDimitry Andric const SCEV *Product = SE.getMulExpr(&BackedgeTakenCount, Step);
18440b57cec5SDimitry Andric
18450b57cec5SDimitry Andric const SCEV *CastedDist = &Dist;
18460b57cec5SDimitry Andric const SCEV *CastedProduct = Product;
184781ad6265SDimitry Andric uint64_t DistTypeSizeBits = DL.getTypeSizeInBits(Dist.getType());
184881ad6265SDimitry Andric uint64_t ProductTypeSizeBits = DL.getTypeSizeInBits(Product->getType());
18490b57cec5SDimitry Andric
18500b57cec5SDimitry Andric // The dependence distance can be positive/negative, so we sign extend Dist;
18510b57cec5SDimitry Andric // The multiplication of the absolute stride in bytes and the
18520b57cec5SDimitry Andric // backedgeTakenCount is non-negative, so we zero extend Product.
185381ad6265SDimitry Andric if (DistTypeSizeBits > ProductTypeSizeBits)
18540b57cec5SDimitry Andric CastedProduct = SE.getZeroExtendExpr(Product, Dist.getType());
18550b57cec5SDimitry Andric else
18560b57cec5SDimitry Andric CastedDist = SE.getNoopOrSignExtend(&Dist, Product->getType());
18570b57cec5SDimitry Andric
18580b57cec5SDimitry Andric // Is Dist - (BackedgeTakenCount * Step) > 0 ?
18590b57cec5SDimitry Andric // (If so, then we have proven (**) because |Dist| >= Dist)
18600b57cec5SDimitry Andric const SCEV *Minus = SE.getMinusSCEV(CastedDist, CastedProduct);
18610b57cec5SDimitry Andric if (SE.isKnownPositive(Minus))
18620b57cec5SDimitry Andric return true;
18630b57cec5SDimitry Andric
18640b57cec5SDimitry Andric // Second try: Is -Dist - (BackedgeTakenCount * Step) > 0 ?
18650b57cec5SDimitry Andric // (If so, then we have proven (**) because |Dist| >= -1*Dist)
18660b57cec5SDimitry Andric const SCEV *NegDist = SE.getNegativeSCEV(CastedDist);
18670b57cec5SDimitry Andric Minus = SE.getMinusSCEV(NegDist, CastedProduct);
18680b57cec5SDimitry Andric if (SE.isKnownPositive(Minus))
18690b57cec5SDimitry Andric return true;
18700b57cec5SDimitry Andric
18710b57cec5SDimitry Andric return false;
18720b57cec5SDimitry Andric }
18730b57cec5SDimitry Andric
18740b57cec5SDimitry Andric /// Check the dependence for two accesses with the same stride \p Stride.
18750b57cec5SDimitry Andric /// \p Distance is the positive distance and \p TypeByteSize is type size in
18760b57cec5SDimitry Andric /// bytes.
18770b57cec5SDimitry Andric ///
18780b57cec5SDimitry Andric /// \returns true if they are independent.
areStridedAccessesIndependent(uint64_t Distance,uint64_t Stride,uint64_t TypeByteSize)18790b57cec5SDimitry Andric static bool areStridedAccessesIndependent(uint64_t Distance, uint64_t Stride,
18800b57cec5SDimitry Andric uint64_t TypeByteSize) {
18810b57cec5SDimitry Andric assert(Stride > 1 && "The stride must be greater than 1");
18820b57cec5SDimitry Andric assert(TypeByteSize > 0 && "The type size in byte must be non-zero");
18830b57cec5SDimitry Andric assert(Distance > 0 && "The distance must be non-zero");
18840b57cec5SDimitry Andric
18850b57cec5SDimitry Andric // Skip if the distance is not multiple of type byte size.
18860b57cec5SDimitry Andric if (Distance % TypeByteSize)
18870b57cec5SDimitry Andric return false;
18880b57cec5SDimitry Andric
18890b57cec5SDimitry Andric uint64_t ScaledDist = Distance / TypeByteSize;
18900b57cec5SDimitry Andric
18910b57cec5SDimitry Andric // No dependence if the scaled distance is not multiple of the stride.
18920b57cec5SDimitry Andric // E.g.
18930b57cec5SDimitry Andric // for (i = 0; i < 1024 ; i += 4)
18940b57cec5SDimitry Andric // A[i+2] = A[i] + 1;
18950b57cec5SDimitry Andric //
18960b57cec5SDimitry Andric // Two accesses in memory (scaled distance is 2, stride is 4):
18970b57cec5SDimitry Andric // | A[0] | | | | A[4] | | | |
18980b57cec5SDimitry Andric // | | | A[2] | | | | A[6] | |
18990b57cec5SDimitry Andric //
19000b57cec5SDimitry Andric // E.g.
19010b57cec5SDimitry Andric // for (i = 0; i < 1024 ; i += 3)
19020b57cec5SDimitry Andric // A[i+4] = A[i] + 1;
19030b57cec5SDimitry Andric //
19040b57cec5SDimitry Andric // Two accesses in memory (scaled distance is 4, stride is 3):
19050b57cec5SDimitry Andric // | A[0] | | | A[3] | | | A[6] | | |
19060b57cec5SDimitry Andric // | | | | | A[4] | | | A[7] | |
19070b57cec5SDimitry Andric return ScaledDist % Stride;
19080b57cec5SDimitry Andric }
19090b57cec5SDimitry Andric
1910c9157d92SDimitry Andric /// Returns true if any of the underlying objects has a loop varying address,
1911c9157d92SDimitry Andric /// i.e. may change in \p L.
1912c9157d92SDimitry Andric static bool
isLoopVariantIndirectAddress(ArrayRef<const Value * > UnderlyingObjects,ScalarEvolution & SE,const Loop * L)1913c9157d92SDimitry Andric isLoopVariantIndirectAddress(ArrayRef<const Value *> UnderlyingObjects,
1914c9157d92SDimitry Andric ScalarEvolution &SE, const Loop *L) {
1915c9157d92SDimitry Andric return any_of(UnderlyingObjects, [&SE, L](const Value *UO) {
1916c9157d92SDimitry Andric return !SE.isLoopInvariant(SE.getSCEV(const_cast<Value *>(UO)), L);
1917c9157d92SDimitry Andric });
1918c9157d92SDimitry Andric }
19190b57cec5SDimitry Andric
1920c9157d92SDimitry Andric // Get the dependence distance, stride, type size in whether i is a write for
1921c9157d92SDimitry Andric // the dependence between A and B. Returns a DepType, if we can prove there's
1922c9157d92SDimitry Andric // no dependence or the analysis fails. Outlined to lambda to limit he scope
1923c9157d92SDimitry Andric // of various temporary variables, like A/BPtr, StrideA/BPtr and others.
1924c9157d92SDimitry Andric // Returns either the dependence result, if it could already be determined, or a
1925c9157d92SDimitry Andric // tuple with (Distance, Stride, TypeSize, AIsWrite, BIsWrite).
1926c9157d92SDimitry Andric static std::variant<MemoryDepChecker::Dependence::DepType,
1927c9157d92SDimitry Andric std::tuple<const SCEV *, uint64_t, uint64_t, bool, bool>>
getDependenceDistanceStrideAndSize(const AccessAnalysis::MemAccessInfo & A,Instruction * AInst,const AccessAnalysis::MemAccessInfo & B,Instruction * BInst,const DenseMap<Value *,const SCEV * > & Strides,const DenseMap<Value *,SmallVector<const Value *,16>> & UnderlyingObjects,PredicatedScalarEvolution & PSE,const Loop * InnermostLoop)1928c9157d92SDimitry Andric getDependenceDistanceStrideAndSize(
1929c9157d92SDimitry Andric const AccessAnalysis::MemAccessInfo &A, Instruction *AInst,
1930c9157d92SDimitry Andric const AccessAnalysis::MemAccessInfo &B, Instruction *BInst,
1931c9157d92SDimitry Andric const DenseMap<Value *, const SCEV *> &Strides,
1932c9157d92SDimitry Andric const DenseMap<Value *, SmallVector<const Value *, 16>> &UnderlyingObjects,
1933c9157d92SDimitry Andric PredicatedScalarEvolution &PSE, const Loop *InnermostLoop) {
1934c9157d92SDimitry Andric auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
1935c9157d92SDimitry Andric auto &SE = *PSE.getSE();
1936bdd1243dSDimitry Andric auto [APtr, AIsWrite] = A;
1937bdd1243dSDimitry Andric auto [BPtr, BIsWrite] = B;
19380b57cec5SDimitry Andric
19390b57cec5SDimitry Andric // Two reads are independent.
19400b57cec5SDimitry Andric if (!AIsWrite && !BIsWrite)
1941c9157d92SDimitry Andric return MemoryDepChecker::Dependence::NoDep;
1942c9157d92SDimitry Andric
1943c9157d92SDimitry Andric Type *ATy = getLoadStoreType(AInst);
1944c9157d92SDimitry Andric Type *BTy = getLoadStoreType(BInst);
19450b57cec5SDimitry Andric
19460b57cec5SDimitry Andric // We cannot check pointers in different address spaces.
19470b57cec5SDimitry Andric if (APtr->getType()->getPointerAddressSpace() !=
19480b57cec5SDimitry Andric BPtr->getType()->getPointerAddressSpace())
1949c9157d92SDimitry Andric return MemoryDepChecker::Dependence::Unknown;
19500b57cec5SDimitry Andric
1951349cc55cSDimitry Andric int64_t StrideAPtr =
1952bdd1243dSDimitry Andric getPtrStride(PSE, ATy, APtr, InnermostLoop, Strides, true).value_or(0);
1953349cc55cSDimitry Andric int64_t StrideBPtr =
1954bdd1243dSDimitry Andric getPtrStride(PSE, BTy, BPtr, InnermostLoop, Strides, true).value_or(0);
19550b57cec5SDimitry Andric
19560b57cec5SDimitry Andric const SCEV *Src = PSE.getSCEV(APtr);
19570b57cec5SDimitry Andric const SCEV *Sink = PSE.getSCEV(BPtr);
19580b57cec5SDimitry Andric
19590b57cec5SDimitry Andric // If the induction step is negative we have to invert source and sink of the
1960c9157d92SDimitry Andric // dependence when measuring the distance between them. We should not swap
1961c9157d92SDimitry Andric // AIsWrite with BIsWrite, as their uses expect them in program order.
19620b57cec5SDimitry Andric if (StrideAPtr < 0) {
19630b57cec5SDimitry Andric std::swap(Src, Sink);
1964c9157d92SDimitry Andric std::swap(AInst, BInst);
19650b57cec5SDimitry Andric }
19660b57cec5SDimitry Andric
1967bdd1243dSDimitry Andric const SCEV *Dist = SE.getMinusSCEV(Sink, Src);
19680b57cec5SDimitry Andric
19690b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
19700b57cec5SDimitry Andric << "(Induction step: " << StrideAPtr << ")\n");
1971c9157d92SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Distance for " << *AInst << " to " << *BInst
1972c9157d92SDimitry Andric << ": " << *Dist << "\n");
1973c9157d92SDimitry Andric
1974c9157d92SDimitry Andric // Needs accesses where the addresses of the accessed underlying objects do
1975c9157d92SDimitry Andric // not change within the loop.
1976c9157d92SDimitry Andric if (isLoopVariantIndirectAddress(UnderlyingObjects.find(APtr)->second, SE,
1977c9157d92SDimitry Andric InnermostLoop) ||
1978c9157d92SDimitry Andric isLoopVariantIndirectAddress(UnderlyingObjects.find(BPtr)->second, SE,
1979c9157d92SDimitry Andric InnermostLoop))
1980c9157d92SDimitry Andric return MemoryDepChecker::Dependence::IndirectUnsafe;
19810b57cec5SDimitry Andric
19820b57cec5SDimitry Andric // Need accesses with constant stride. We don't want to vectorize
1983c9157d92SDimitry Andric // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap
1984c9157d92SDimitry Andric // in the address space.
19850b57cec5SDimitry Andric if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr) {
19860b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Pointer access with non-constant stride\n");
1987c9157d92SDimitry Andric return MemoryDepChecker::Dependence::Unknown;
19880b57cec5SDimitry Andric }
19890b57cec5SDimitry Andric
19900b57cec5SDimitry Andric uint64_t TypeByteSize = DL.getTypeAllocSize(ATy);
19910eae32dcSDimitry Andric bool HasSameSize =
19920eae32dcSDimitry Andric DL.getTypeStoreSizeInBits(ATy) == DL.getTypeStoreSizeInBits(BTy);
1993c9157d92SDimitry Andric if (!HasSameSize)
1994c9157d92SDimitry Andric TypeByteSize = 0;
19950b57cec5SDimitry Andric uint64_t Stride = std::abs(StrideAPtr);
1996c9157d92SDimitry Andric return std::make_tuple(Dist, Stride, TypeByteSize, AIsWrite, BIsWrite);
1997c9157d92SDimitry Andric }
1998bdd1243dSDimitry Andric
isDependent(const MemAccessInfo & A,unsigned AIdx,const MemAccessInfo & B,unsigned BIdx,const DenseMap<Value *,const SCEV * > & Strides,const DenseMap<Value *,SmallVector<const Value *,16>> & UnderlyingObjects)1999c9157d92SDimitry Andric MemoryDepChecker::Dependence::DepType MemoryDepChecker::isDependent(
2000c9157d92SDimitry Andric const MemAccessInfo &A, unsigned AIdx, const MemAccessInfo &B,
2001c9157d92SDimitry Andric unsigned BIdx, const DenseMap<Value *, const SCEV *> &Strides,
2002c9157d92SDimitry Andric const DenseMap<Value *, SmallVector<const Value *, 16>>
2003c9157d92SDimitry Andric &UnderlyingObjects) {
2004c9157d92SDimitry Andric assert(AIdx < BIdx && "Must pass arguments in program order");
2005c9157d92SDimitry Andric
2006c9157d92SDimitry Andric // Get the dependence distance, stride, type size and what access writes for
2007c9157d92SDimitry Andric // the dependence between A and B.
2008c9157d92SDimitry Andric auto Res = getDependenceDistanceStrideAndSize(
2009c9157d92SDimitry Andric A, InstMap[AIdx], B, InstMap[BIdx], Strides, UnderlyingObjects, PSE,
2010c9157d92SDimitry Andric InnermostLoop);
2011c9157d92SDimitry Andric if (std::holds_alternative<Dependence::DepType>(Res))
2012c9157d92SDimitry Andric return std::get<Dependence::DepType>(Res);
2013c9157d92SDimitry Andric
2014c9157d92SDimitry Andric const auto &[Dist, Stride, TypeByteSize, AIsWrite, BIsWrite] =
2015c9157d92SDimitry Andric std::get<std::tuple<const SCEV *, uint64_t, uint64_t, bool, bool>>(Res);
2016c9157d92SDimitry Andric bool HasSameSize = TypeByteSize > 0;
2017c9157d92SDimitry Andric
2018c9157d92SDimitry Andric ScalarEvolution &SE = *PSE.getSE();
2019c9157d92SDimitry Andric auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
20200eae32dcSDimitry Andric if (!isa<SCEVCouldNotCompute>(Dist) && HasSameSize &&
2021bdd1243dSDimitry Andric isSafeDependenceDistance(DL, SE, *(PSE.getBackedgeTakenCount()), *Dist,
2022bdd1243dSDimitry Andric Stride, TypeByteSize))
20230b57cec5SDimitry Andric return Dependence::NoDep;
20240b57cec5SDimitry Andric
2025bdd1243dSDimitry Andric const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
2026bdd1243dSDimitry Andric if (!C) {
20270b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
20280b57cec5SDimitry Andric FoundNonConstantDistanceDependence = true;
20290b57cec5SDimitry Andric return Dependence::Unknown;
20300b57cec5SDimitry Andric }
20310b57cec5SDimitry Andric
20320b57cec5SDimitry Andric const APInt &Val = C->getAPInt();
20330b57cec5SDimitry Andric int64_t Distance = Val.getSExtValue();
20340b57cec5SDimitry Andric
20350b57cec5SDimitry Andric // Attempt to prove strided accesses independent.
20360eae32dcSDimitry Andric if (std::abs(Distance) > 0 && Stride > 1 && HasSameSize &&
20370b57cec5SDimitry Andric areStridedAccessesIndependent(std::abs(Distance), Stride, TypeByteSize)) {
20380b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Strided accesses are independent\n");
20390b57cec5SDimitry Andric return Dependence::NoDep;
20400b57cec5SDimitry Andric }
20410b57cec5SDimitry Andric
20420b57cec5SDimitry Andric // Negative distances are not plausible dependencies.
20430b57cec5SDimitry Andric if (Val.isNegative()) {
20440b57cec5SDimitry Andric bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
2045c9157d92SDimitry Andric // There is no need to update MaxSafeVectorWidthInBits after call to
2046c9157d92SDimitry Andric // couldPreventStoreLoadForward, even if it changed MinDepDistBytes,
2047c9157d92SDimitry Andric // since a forward dependency will allow vectorization using any width.
20480b57cec5SDimitry Andric if (IsTrueDataDependence && EnableForwardingConflictDetection &&
2049c9157d92SDimitry Andric (!HasSameSize || couldPreventStoreLoadForward(Val.abs().getZExtValue(),
2050c9157d92SDimitry Andric TypeByteSize))) {
20510b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Forward but may prevent st->ld forwarding\n");
20520b57cec5SDimitry Andric return Dependence::ForwardButPreventsForwarding;
20530b57cec5SDimitry Andric }
20540b57cec5SDimitry Andric
20550b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Dependence is negative\n");
20560b57cec5SDimitry Andric return Dependence::Forward;
20570b57cec5SDimitry Andric }
20580b57cec5SDimitry Andric
20590b57cec5SDimitry Andric // Write to the same location with the same size.
20600b57cec5SDimitry Andric if (Val == 0) {
20610eae32dcSDimitry Andric if (HasSameSize)
20620b57cec5SDimitry Andric return Dependence::Forward;
20630b57cec5SDimitry Andric LLVM_DEBUG(
20640eae32dcSDimitry Andric dbgs() << "LAA: Zero dependence difference but different type sizes\n");
20650b57cec5SDimitry Andric return Dependence::Unknown;
20660b57cec5SDimitry Andric }
20670b57cec5SDimitry Andric
20680b57cec5SDimitry Andric assert(Val.isStrictlyPositive() && "Expect a positive value");
20690b57cec5SDimitry Andric
20700eae32dcSDimitry Andric if (!HasSameSize) {
20710eae32dcSDimitry Andric LLVM_DEBUG(dbgs() << "LAA: ReadWrite-Write positive dependency with "
20720eae32dcSDimitry Andric "different type sizes\n");
20730b57cec5SDimitry Andric return Dependence::Unknown;
20740b57cec5SDimitry Andric }
20750b57cec5SDimitry Andric
20760b57cec5SDimitry Andric // Bail out early if passed-in parameters make vectorization not feasible.
20770b57cec5SDimitry Andric unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
20780b57cec5SDimitry Andric VectorizerParams::VectorizationFactor : 1);
20790b57cec5SDimitry Andric unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
20800b57cec5SDimitry Andric VectorizerParams::VectorizationInterleave : 1);
20810b57cec5SDimitry Andric // The minimum number of iterations for a vectorized/unrolled version.
20820b57cec5SDimitry Andric unsigned MinNumIter = std::max(ForcedFactor * ForcedUnroll, 2U);
20830b57cec5SDimitry Andric
20840b57cec5SDimitry Andric // It's not vectorizable if the distance is smaller than the minimum distance
20850b57cec5SDimitry Andric // needed for a vectroized/unrolled version. Vectorizing one iteration in
20860b57cec5SDimitry Andric // front needs TypeByteSize * Stride. Vectorizing the last iteration needs
20870b57cec5SDimitry Andric // TypeByteSize (No need to plus the last gap distance).
20880b57cec5SDimitry Andric //
20890b57cec5SDimitry Andric // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
20900b57cec5SDimitry Andric // foo(int *A) {
20910b57cec5SDimitry Andric // int *B = (int *)((char *)A + 14);
20920b57cec5SDimitry Andric // for (i = 0 ; i < 1024 ; i += 2)
20930b57cec5SDimitry Andric // B[i] = A[i] + 1;
20940b57cec5SDimitry Andric // }
20950b57cec5SDimitry Andric //
20960b57cec5SDimitry Andric // Two accesses in memory (stride is 2):
20970b57cec5SDimitry Andric // | A[0] | | A[2] | | A[4] | | A[6] | |
20980b57cec5SDimitry Andric // | B[0] | | B[2] | | B[4] |
20990b57cec5SDimitry Andric //
21000b57cec5SDimitry Andric // Distance needs for vectorizing iterations except the last iteration:
21010b57cec5SDimitry Andric // 4 * 2 * (MinNumIter - 1). Distance needs for the last iteration: 4.
21020b57cec5SDimitry Andric // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4.
21030b57cec5SDimitry Andric //
21040b57cec5SDimitry Andric // If MinNumIter is 2, it is vectorizable as the minimum distance needed is
21050b57cec5SDimitry Andric // 12, which is less than distance.
21060b57cec5SDimitry Andric //
21070b57cec5SDimitry Andric // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4),
21080b57cec5SDimitry Andric // the minimum distance needed is 28, which is greater than distance. It is
21090b57cec5SDimitry Andric // not safe to do vectorization.
21100b57cec5SDimitry Andric uint64_t MinDistanceNeeded =
21110b57cec5SDimitry Andric TypeByteSize * Stride * (MinNumIter - 1) + TypeByteSize;
21120b57cec5SDimitry Andric if (MinDistanceNeeded > static_cast<uint64_t>(Distance)) {
21130b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Failure because of positive distance "
21140b57cec5SDimitry Andric << Distance << '\n');
21150b57cec5SDimitry Andric return Dependence::Backward;
21160b57cec5SDimitry Andric }
21170b57cec5SDimitry Andric
2118c9157d92SDimitry Andric // Unsafe if the minimum distance needed is greater than smallest dependence
2119c9157d92SDimitry Andric // distance distance.
2120c9157d92SDimitry Andric if (MinDistanceNeeded > MinDepDistBytes) {
21210b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Failure because it needs at least "
2122bdd1243dSDimitry Andric << MinDistanceNeeded << " size in bytes\n");
21230b57cec5SDimitry Andric return Dependence::Backward;
21240b57cec5SDimitry Andric }
21250b57cec5SDimitry Andric
21260b57cec5SDimitry Andric // Positive distance bigger than max vectorization factor.
21270b57cec5SDimitry Andric // FIXME: Should use max factor instead of max distance in bytes, which could
21280b57cec5SDimitry Andric // not handle different types.
21290b57cec5SDimitry Andric // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
21300b57cec5SDimitry Andric // void foo (int *A, char *B) {
21310b57cec5SDimitry Andric // for (unsigned i = 0; i < 1024; i++) {
21320b57cec5SDimitry Andric // A[i+2] = A[i] + 1;
21330b57cec5SDimitry Andric // B[i+2] = B[i] + 1;
21340b57cec5SDimitry Andric // }
21350b57cec5SDimitry Andric // }
21360b57cec5SDimitry Andric //
21370b57cec5SDimitry Andric // This case is currently unsafe according to the max safe distance. If we
21380b57cec5SDimitry Andric // analyze the two accesses on array B, the max safe dependence distance
21390b57cec5SDimitry Andric // is 2. Then we analyze the accesses on array A, the minimum distance needed
21400b57cec5SDimitry Andric // is 8, which is less than 2 and forbidden vectorization, But actually
21410b57cec5SDimitry Andric // both A and B could be vectorized by 2 iterations.
2142c9157d92SDimitry Andric MinDepDistBytes =
2143c9157d92SDimitry Andric std::min(static_cast<uint64_t>(Distance), MinDepDistBytes);
21440b57cec5SDimitry Andric
21450b57cec5SDimitry Andric bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
2146c9157d92SDimitry Andric uint64_t MinDepDistBytesOld = MinDepDistBytes;
21470b57cec5SDimitry Andric if (IsTrueDataDependence && EnableForwardingConflictDetection &&
2148c9157d92SDimitry Andric couldPreventStoreLoadForward(Distance, TypeByteSize)) {
2149c9157d92SDimitry Andric // Sanity check that we didn't update MinDepDistBytes when calling
2150c9157d92SDimitry Andric // couldPreventStoreLoadForward
2151c9157d92SDimitry Andric assert(MinDepDistBytes == MinDepDistBytesOld &&
2152c9157d92SDimitry Andric "An update to MinDepDistBytes requires an update to "
2153c9157d92SDimitry Andric "MaxSafeVectorWidthInBits");
2154c9157d92SDimitry Andric (void)MinDepDistBytesOld;
21550b57cec5SDimitry Andric return Dependence::BackwardVectorizableButPreventsForwarding;
2156c9157d92SDimitry Andric }
21570b57cec5SDimitry Andric
2158c9157d92SDimitry Andric // An update to MinDepDistBytes requires an update to MaxSafeVectorWidthInBits
2159c9157d92SDimitry Andric // since there is a backwards dependency.
2160c9157d92SDimitry Andric uint64_t MaxVF = MinDepDistBytes / (TypeByteSize * Stride);
21610b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue()
21620b57cec5SDimitry Andric << " with max VF = " << MaxVF << '\n');
21630b57cec5SDimitry Andric uint64_t MaxVFInBits = MaxVF * TypeByteSize * 8;
2164e8d8bef9SDimitry Andric MaxSafeVectorWidthInBits = std::min(MaxSafeVectorWidthInBits, MaxVFInBits);
21650b57cec5SDimitry Andric return Dependence::BackwardVectorizable;
21660b57cec5SDimitry Andric }
21670b57cec5SDimitry Andric
areDepsSafe(DepCandidates & AccessSets,MemAccessInfoList & CheckDeps,const DenseMap<Value *,const SCEV * > & Strides,const DenseMap<Value *,SmallVector<const Value *,16>> & UnderlyingObjects)2168c9157d92SDimitry Andric bool MemoryDepChecker::areDepsSafe(
2169c9157d92SDimitry Andric DepCandidates &AccessSets, MemAccessInfoList &CheckDeps,
2170c9157d92SDimitry Andric const DenseMap<Value *, const SCEV *> &Strides,
2171c9157d92SDimitry Andric const DenseMap<Value *, SmallVector<const Value *, 16>>
2172c9157d92SDimitry Andric &UnderlyingObjects) {
21730b57cec5SDimitry Andric
2174c9157d92SDimitry Andric MinDepDistBytes = -1;
21750b57cec5SDimitry Andric SmallPtrSet<MemAccessInfo, 8> Visited;
21760b57cec5SDimitry Andric for (MemAccessInfo CurAccess : CheckDeps) {
21770b57cec5SDimitry Andric if (Visited.count(CurAccess))
21780b57cec5SDimitry Andric continue;
21790b57cec5SDimitry Andric
21800b57cec5SDimitry Andric // Get the relevant memory access set.
21810b57cec5SDimitry Andric EquivalenceClasses<MemAccessInfo>::iterator I =
21820b57cec5SDimitry Andric AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
21830b57cec5SDimitry Andric
21840b57cec5SDimitry Andric // Check accesses within this set.
21850b57cec5SDimitry Andric EquivalenceClasses<MemAccessInfo>::member_iterator AI =
21860b57cec5SDimitry Andric AccessSets.member_begin(I);
21870b57cec5SDimitry Andric EquivalenceClasses<MemAccessInfo>::member_iterator AE =
21880b57cec5SDimitry Andric AccessSets.member_end();
21890b57cec5SDimitry Andric
21900b57cec5SDimitry Andric // Check every access pair.
21910b57cec5SDimitry Andric while (AI != AE) {
21920b57cec5SDimitry Andric Visited.insert(*AI);
21938bcb0991SDimitry Andric bool AIIsWrite = AI->getInt();
21948bcb0991SDimitry Andric // Check loads only against next equivalent class, but stores also against
21958bcb0991SDimitry Andric // other stores in the same equivalence class - to the same address.
21968bcb0991SDimitry Andric EquivalenceClasses<MemAccessInfo>::member_iterator OI =
21978bcb0991SDimitry Andric (AIIsWrite ? AI : std::next(AI));
21980b57cec5SDimitry Andric while (OI != AE) {
21990b57cec5SDimitry Andric // Check every accessing instruction pair in program order.
22000b57cec5SDimitry Andric for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
22010b57cec5SDimitry Andric I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
22028bcb0991SDimitry Andric // Scan all accesses of another equivalence class, but only the next
22038bcb0991SDimitry Andric // accesses of the same equivalent class.
22048bcb0991SDimitry Andric for (std::vector<unsigned>::iterator
22058bcb0991SDimitry Andric I2 = (OI == AI ? std::next(I1) : Accesses[*OI].begin()),
22068bcb0991SDimitry Andric I2E = (OI == AI ? I1E : Accesses[*OI].end());
22078bcb0991SDimitry Andric I2 != I2E; ++I2) {
22080b57cec5SDimitry Andric auto A = std::make_pair(&*AI, *I1);
22090b57cec5SDimitry Andric auto B = std::make_pair(&*OI, *I2);
22100b57cec5SDimitry Andric
22110b57cec5SDimitry Andric assert(*I1 != *I2);
22120b57cec5SDimitry Andric if (*I1 > *I2)
22130b57cec5SDimitry Andric std::swap(A, B);
22140b57cec5SDimitry Andric
22150b57cec5SDimitry Andric Dependence::DepType Type =
2216c9157d92SDimitry Andric isDependent(*A.first, A.second, *B.first, B.second, Strides,
2217c9157d92SDimitry Andric UnderlyingObjects);
22180b57cec5SDimitry Andric mergeInStatus(Dependence::isSafeForVectorization(Type));
22190b57cec5SDimitry Andric
22200b57cec5SDimitry Andric // Gather dependences unless we accumulated MaxDependences
22210b57cec5SDimitry Andric // dependences. In that case return as soon as we find the first
22220b57cec5SDimitry Andric // unsafe dependence. This puts a limit on this quadratic
22230b57cec5SDimitry Andric // algorithm.
22240b57cec5SDimitry Andric if (RecordDependences) {
22250b57cec5SDimitry Andric if (Type != Dependence::NoDep)
22260b57cec5SDimitry Andric Dependences.push_back(Dependence(A.second, B.second, Type));
22270b57cec5SDimitry Andric
22280b57cec5SDimitry Andric if (Dependences.size() >= MaxDependences) {
22290b57cec5SDimitry Andric RecordDependences = false;
22300b57cec5SDimitry Andric Dependences.clear();
22310b57cec5SDimitry Andric LLVM_DEBUG(dbgs()
22320b57cec5SDimitry Andric << "Too many dependences, stopped recording\n");
22330b57cec5SDimitry Andric }
22340b57cec5SDimitry Andric }
22350b57cec5SDimitry Andric if (!RecordDependences && !isSafeForVectorization())
22360b57cec5SDimitry Andric return false;
22370b57cec5SDimitry Andric }
22380b57cec5SDimitry Andric ++OI;
22390b57cec5SDimitry Andric }
22400b57cec5SDimitry Andric AI++;
22410b57cec5SDimitry Andric }
22420b57cec5SDimitry Andric }
22430b57cec5SDimitry Andric
22440b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Total Dependences: " << Dependences.size() << "\n");
22450b57cec5SDimitry Andric return isSafeForVectorization();
22460b57cec5SDimitry Andric }
22470b57cec5SDimitry Andric
22480b57cec5SDimitry Andric SmallVector<Instruction *, 4>
getInstructionsForAccess(Value * Ptr,bool isWrite) const22490b57cec5SDimitry Andric MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const {
22500b57cec5SDimitry Andric MemAccessInfo Access(Ptr, isWrite);
22510b57cec5SDimitry Andric auto &IndexVector = Accesses.find(Access)->second;
22520b57cec5SDimitry Andric
22530b57cec5SDimitry Andric SmallVector<Instruction *, 4> Insts;
22540b57cec5SDimitry Andric transform(IndexVector,
22550b57cec5SDimitry Andric std::back_inserter(Insts),
22560b57cec5SDimitry Andric [&](unsigned Idx) { return this->InstMap[Idx]; });
22570b57cec5SDimitry Andric return Insts;
22580b57cec5SDimitry Andric }
22590b57cec5SDimitry Andric
22600b57cec5SDimitry Andric const char *MemoryDepChecker::Dependence::DepName[] = {
2261c9157d92SDimitry Andric "NoDep",
2262c9157d92SDimitry Andric "Unknown",
2263c9157d92SDimitry Andric "IndidrectUnsafe",
2264c9157d92SDimitry Andric "Forward",
2265c9157d92SDimitry Andric "ForwardButPreventsForwarding",
2266c9157d92SDimitry Andric "Backward",
2267c9157d92SDimitry Andric "BackwardVectorizable",
2268c9157d92SDimitry Andric "BackwardVectorizableButPreventsForwarding"};
22690b57cec5SDimitry Andric
print(raw_ostream & OS,unsigned Depth,const SmallVectorImpl<Instruction * > & Instrs) const22700b57cec5SDimitry Andric void MemoryDepChecker::Dependence::print(
22710b57cec5SDimitry Andric raw_ostream &OS, unsigned Depth,
22720b57cec5SDimitry Andric const SmallVectorImpl<Instruction *> &Instrs) const {
22730b57cec5SDimitry Andric OS.indent(Depth) << DepName[Type] << ":\n";
22740b57cec5SDimitry Andric OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
22750b57cec5SDimitry Andric OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
22760b57cec5SDimitry Andric }
22770b57cec5SDimitry Andric
canAnalyzeLoop()22780b57cec5SDimitry Andric bool LoopAccessInfo::canAnalyzeLoop() {
22790b57cec5SDimitry Andric // We need to have a loop header.
22800b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Found a loop in "
22810b57cec5SDimitry Andric << TheLoop->getHeader()->getParent()->getName() << ": "
22820b57cec5SDimitry Andric << TheLoop->getHeader()->getName() << '\n');
22830b57cec5SDimitry Andric
22840b57cec5SDimitry Andric // We can only analyze innermost loops.
2285e8d8bef9SDimitry Andric if (!TheLoop->isInnermost()) {
22860b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
22870b57cec5SDimitry Andric recordAnalysis("NotInnerMostLoop") << "loop is not the innermost loop";
22880b57cec5SDimitry Andric return false;
22890b57cec5SDimitry Andric }
22900b57cec5SDimitry Andric
22910b57cec5SDimitry Andric // We must have a single backedge.
22920b57cec5SDimitry Andric if (TheLoop->getNumBackEdges() != 1) {
22930b57cec5SDimitry Andric LLVM_DEBUG(
22940b57cec5SDimitry Andric dbgs() << "LAA: loop control flow is not understood by analyzer\n");
22950b57cec5SDimitry Andric recordAnalysis("CFGNotUnderstood")
22960b57cec5SDimitry Andric << "loop control flow is not understood by analyzer";
22970b57cec5SDimitry Andric return false;
22980b57cec5SDimitry Andric }
22990b57cec5SDimitry Andric
23000b57cec5SDimitry Andric // ScalarEvolution needs to be able to find the exit count.
23010b57cec5SDimitry Andric const SCEV *ExitCount = PSE->getBackedgeTakenCount();
2302e8d8bef9SDimitry Andric if (isa<SCEVCouldNotCompute>(ExitCount)) {
23030b57cec5SDimitry Andric recordAnalysis("CantComputeNumberOfIterations")
23040b57cec5SDimitry Andric << "could not determine number of loop iterations";
23050b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
23060b57cec5SDimitry Andric return false;
23070b57cec5SDimitry Andric }
23080b57cec5SDimitry Andric
23090b57cec5SDimitry Andric return true;
23100b57cec5SDimitry Andric }
23110b57cec5SDimitry Andric
analyzeLoop(AAResults * AA,LoopInfo * LI,const TargetLibraryInfo * TLI,DominatorTree * DT)23125ffd83dbSDimitry Andric void LoopAccessInfo::analyzeLoop(AAResults *AA, LoopInfo *LI,
23130b57cec5SDimitry Andric const TargetLibraryInfo *TLI,
23140b57cec5SDimitry Andric DominatorTree *DT) {
23150b57cec5SDimitry Andric // Holds the Load and Store instructions.
23160b57cec5SDimitry Andric SmallVector<LoadInst *, 16> Loads;
23170b57cec5SDimitry Andric SmallVector<StoreInst *, 16> Stores;
2318*b9d9368bSDimitry Andric SmallPtrSet<MDNode *, 8> LoopAliasScopes;
23190b57cec5SDimitry Andric
23200b57cec5SDimitry Andric // Holds all the different accesses in the loop.
23210b57cec5SDimitry Andric unsigned NumReads = 0;
23220b57cec5SDimitry Andric unsigned NumReadWrites = 0;
23230b57cec5SDimitry Andric
23240b57cec5SDimitry Andric bool HasComplexMemInst = false;
23250b57cec5SDimitry Andric
23260b57cec5SDimitry Andric // A runtime check is only legal to insert if there are no convergent calls.
23270b57cec5SDimitry Andric HasConvergentOp = false;
23280b57cec5SDimitry Andric
23290b57cec5SDimitry Andric PtrRtChecking->Pointers.clear();
23300b57cec5SDimitry Andric PtrRtChecking->Need = false;
23310b57cec5SDimitry Andric
23320b57cec5SDimitry Andric const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
23330b57cec5SDimitry Andric
23345ffd83dbSDimitry Andric const bool EnableMemAccessVersioningOfLoop =
23355ffd83dbSDimitry Andric EnableMemAccessVersioning &&
23365ffd83dbSDimitry Andric !TheLoop->getHeader()->getParent()->hasOptSize();
23375ffd83dbSDimitry Andric
2338bdd1243dSDimitry Andric // Traverse blocks in fixed RPOT order, regardless of their storage in the
2339bdd1243dSDimitry Andric // loop info, as it may be arbitrary.
2340bdd1243dSDimitry Andric LoopBlocksRPO RPOT(TheLoop);
2341bdd1243dSDimitry Andric RPOT.perform(LI);
2342bdd1243dSDimitry Andric for (BasicBlock *BB : RPOT) {
23430b57cec5SDimitry Andric // Scan the BB and collect legal loads and stores. Also detect any
23440b57cec5SDimitry Andric // convergent instructions.
23450b57cec5SDimitry Andric for (Instruction &I : *BB) {
23460b57cec5SDimitry Andric if (auto *Call = dyn_cast<CallBase>(&I)) {
23470b57cec5SDimitry Andric if (Call->isConvergent())
23480b57cec5SDimitry Andric HasConvergentOp = true;
23490b57cec5SDimitry Andric }
23500b57cec5SDimitry Andric
23510b57cec5SDimitry Andric // With both a non-vectorizable memory instruction and a convergent
23520b57cec5SDimitry Andric // operation, found in this loop, no reason to continue the search.
23530b57cec5SDimitry Andric if (HasComplexMemInst && HasConvergentOp) {
23540b57cec5SDimitry Andric CanVecMem = false;
23550b57cec5SDimitry Andric return;
23560b57cec5SDimitry Andric }
23570b57cec5SDimitry Andric
23580b57cec5SDimitry Andric // Avoid hitting recordAnalysis multiple times.
23590b57cec5SDimitry Andric if (HasComplexMemInst)
23600b57cec5SDimitry Andric continue;
23610b57cec5SDimitry Andric
2362*b9d9368bSDimitry Andric // Record alias scopes defined inside the loop.
2363*b9d9368bSDimitry Andric if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
2364*b9d9368bSDimitry Andric for (Metadata *Op : Decl->getScopeList()->operands())
2365*b9d9368bSDimitry Andric LoopAliasScopes.insert(cast<MDNode>(Op));
2366*b9d9368bSDimitry Andric
23670b57cec5SDimitry Andric // Many math library functions read the rounding mode. We will only
23680b57cec5SDimitry Andric // vectorize a loop if it contains known function calls that don't set
23690b57cec5SDimitry Andric // the flag. Therefore, it is safe to ignore this read from memory.
23700b57cec5SDimitry Andric auto *Call = dyn_cast<CallInst>(&I);
23710b57cec5SDimitry Andric if (Call && getVectorIntrinsicIDForCall(Call, TLI))
23720b57cec5SDimitry Andric continue;
23730b57cec5SDimitry Andric
2374c9157d92SDimitry Andric // If this is a load, save it. If this instruction can read from memory
2375c9157d92SDimitry Andric // but is not a load, then we quit. Notice that we don't handle function
2376c9157d92SDimitry Andric // calls that read or write.
2377c9157d92SDimitry Andric if (I.mayReadFromMemory()) {
23780b57cec5SDimitry Andric // If the function has an explicit vectorized counterpart, we can safely
23790b57cec5SDimitry Andric // assume that it can be vectorized.
23800b57cec5SDimitry Andric if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
23815ffd83dbSDimitry Andric !VFDatabase::getMappings(*Call).empty())
23820b57cec5SDimitry Andric continue;
23830b57cec5SDimitry Andric
23840b57cec5SDimitry Andric auto *Ld = dyn_cast<LoadInst>(&I);
23850b57cec5SDimitry Andric if (!Ld) {
23860b57cec5SDimitry Andric recordAnalysis("CantVectorizeInstruction", Ld)
23870b57cec5SDimitry Andric << "instruction cannot be vectorized";
23880b57cec5SDimitry Andric HasComplexMemInst = true;
23890b57cec5SDimitry Andric continue;
23900b57cec5SDimitry Andric }
23910b57cec5SDimitry Andric if (!Ld->isSimple() && !IsAnnotatedParallel) {
23920b57cec5SDimitry Andric recordAnalysis("NonSimpleLoad", Ld)
23930b57cec5SDimitry Andric << "read with atomic ordering or volatile read";
23940b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
23950b57cec5SDimitry Andric HasComplexMemInst = true;
23960b57cec5SDimitry Andric continue;
23970b57cec5SDimitry Andric }
23980b57cec5SDimitry Andric NumLoads++;
23990b57cec5SDimitry Andric Loads.push_back(Ld);
24000b57cec5SDimitry Andric DepChecker->addAccess(Ld);
24015ffd83dbSDimitry Andric if (EnableMemAccessVersioningOfLoop)
24020b57cec5SDimitry Andric collectStridedAccess(Ld);
24030b57cec5SDimitry Andric continue;
24040b57cec5SDimitry Andric }
24050b57cec5SDimitry Andric
24060b57cec5SDimitry Andric // Save 'store' instructions. Abort if other instructions write to memory.
24070b57cec5SDimitry Andric if (I.mayWriteToMemory()) {
24080b57cec5SDimitry Andric auto *St = dyn_cast<StoreInst>(&I);
24090b57cec5SDimitry Andric if (!St) {
24100b57cec5SDimitry Andric recordAnalysis("CantVectorizeInstruction", St)
24110b57cec5SDimitry Andric << "instruction cannot be vectorized";
24120b57cec5SDimitry Andric HasComplexMemInst = true;
24130b57cec5SDimitry Andric continue;
24140b57cec5SDimitry Andric }
24150b57cec5SDimitry Andric if (!St->isSimple() && !IsAnnotatedParallel) {
24160b57cec5SDimitry Andric recordAnalysis("NonSimpleStore", St)
24170b57cec5SDimitry Andric << "write with atomic ordering or volatile write";
24180b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
24190b57cec5SDimitry Andric HasComplexMemInst = true;
24200b57cec5SDimitry Andric continue;
24210b57cec5SDimitry Andric }
24220b57cec5SDimitry Andric NumStores++;
24230b57cec5SDimitry Andric Stores.push_back(St);
24240b57cec5SDimitry Andric DepChecker->addAccess(St);
24255ffd83dbSDimitry Andric if (EnableMemAccessVersioningOfLoop)
24260b57cec5SDimitry Andric collectStridedAccess(St);
24270b57cec5SDimitry Andric }
24280b57cec5SDimitry Andric } // Next instr.
24290b57cec5SDimitry Andric } // Next block.
24300b57cec5SDimitry Andric
24310b57cec5SDimitry Andric if (HasComplexMemInst) {
24320b57cec5SDimitry Andric CanVecMem = false;
24330b57cec5SDimitry Andric return;
24340b57cec5SDimitry Andric }
24350b57cec5SDimitry Andric
24360b57cec5SDimitry Andric // Now we have two lists that hold the loads and the stores.
24370b57cec5SDimitry Andric // Next, we find the pointers that they use.
24380b57cec5SDimitry Andric
24390b57cec5SDimitry Andric // Check if we see any stores. If there are no stores, then we don't
24400b57cec5SDimitry Andric // care if the pointers are *restrict*.
24410b57cec5SDimitry Andric if (!Stores.size()) {
24420b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
24430b57cec5SDimitry Andric CanVecMem = true;
24440b57cec5SDimitry Andric return;
24450b57cec5SDimitry Andric }
24460b57cec5SDimitry Andric
24470b57cec5SDimitry Andric MemoryDepChecker::DepCandidates DependentAccesses;
2448*b9d9368bSDimitry Andric AccessAnalysis Accesses(TheLoop, AA, LI, DependentAccesses, *PSE,
2449*b9d9368bSDimitry Andric LoopAliasScopes);
24500b57cec5SDimitry Andric
2451e8d8bef9SDimitry Andric // Holds the analyzed pointers. We don't want to call getUnderlyingObjects
24520b57cec5SDimitry Andric // multiple times on the same object. If the ptr is accessed twice, once
24530b57cec5SDimitry Andric // for read and once for write, it will only appear once (on the write
24540b57cec5SDimitry Andric // list). This is okay, since we are going to check for conflicts between
24550b57cec5SDimitry Andric // writes and between reads and writes, but not between reads and reads.
245681ad6265SDimitry Andric SmallSet<std::pair<Value *, Type *>, 16> Seen;
24570b57cec5SDimitry Andric
24580b57cec5SDimitry Andric // Record uniform store addresses to identify if we have multiple stores
24590b57cec5SDimitry Andric // to the same address.
246081ad6265SDimitry Andric SmallPtrSet<Value *, 16> UniformStores;
24610b57cec5SDimitry Andric
24620b57cec5SDimitry Andric for (StoreInst *ST : Stores) {
24630b57cec5SDimitry Andric Value *Ptr = ST->getPointerOperand();
24640b57cec5SDimitry Andric
2465fe013be4SDimitry Andric if (isInvariant(Ptr)) {
246681ad6265SDimitry Andric // Record store instructions to loop invariant addresses
246781ad6265SDimitry Andric StoresToInvariantAddresses.push_back(ST);
24680b57cec5SDimitry Andric HasDependenceInvolvingLoopInvariantAddress |=
24690b57cec5SDimitry Andric !UniformStores.insert(Ptr).second;
247081ad6265SDimitry Andric }
24710b57cec5SDimitry Andric
24720b57cec5SDimitry Andric // If we did *not* see this pointer before, insert it to the read-write
24730b57cec5SDimitry Andric // list. At this phase it is only a 'write' list.
247481ad6265SDimitry Andric Type *AccessTy = getLoadStoreType(ST);
247581ad6265SDimitry Andric if (Seen.insert({Ptr, AccessTy}).second) {
24760b57cec5SDimitry Andric ++NumReadWrites;
24770b57cec5SDimitry Andric
24780b57cec5SDimitry Andric MemoryLocation Loc = MemoryLocation::get(ST);
24790b57cec5SDimitry Andric // The TBAA metadata could have a control dependency on the predication
24800b57cec5SDimitry Andric // condition, so we cannot rely on it when determining whether or not we
24810b57cec5SDimitry Andric // need runtime pointer checks.
24820b57cec5SDimitry Andric if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
24830b57cec5SDimitry Andric Loc.AATags.TBAA = nullptr;
24840b57cec5SDimitry Andric
2485349cc55cSDimitry Andric visitPointers(const_cast<Value *>(Loc.Ptr), *TheLoop,
248681ad6265SDimitry Andric [&Accesses, AccessTy, Loc](Value *Ptr) {
2487349cc55cSDimitry Andric MemoryLocation NewLoc = Loc.getWithNewPtr(Ptr);
248881ad6265SDimitry Andric Accesses.addStore(NewLoc, AccessTy);
2489349cc55cSDimitry Andric });
24900b57cec5SDimitry Andric }
24910b57cec5SDimitry Andric }
24920b57cec5SDimitry Andric
24930b57cec5SDimitry Andric if (IsAnnotatedParallel) {
24940b57cec5SDimitry Andric LLVM_DEBUG(
24950b57cec5SDimitry Andric dbgs() << "LAA: A loop annotated parallel, ignore memory dependency "
24960b57cec5SDimitry Andric << "checks.\n");
24970b57cec5SDimitry Andric CanVecMem = true;
24980b57cec5SDimitry Andric return;
24990b57cec5SDimitry Andric }
25000b57cec5SDimitry Andric
25010b57cec5SDimitry Andric for (LoadInst *LD : Loads) {
25020b57cec5SDimitry Andric Value *Ptr = LD->getPointerOperand();
25030b57cec5SDimitry Andric // If we did *not* see this pointer before, insert it to the
25040b57cec5SDimitry Andric // read list. If we *did* see it before, then it is already in
25050b57cec5SDimitry Andric // the read-write list. This allows us to vectorize expressions
25060b57cec5SDimitry Andric // such as A[i] += x; Because the address of A[i] is a read-write
25070b57cec5SDimitry Andric // pointer. This only works if the index of A[i] is consecutive.
25080b57cec5SDimitry Andric // If the address of i is unknown (for example A[B[i]]) then we may
25090b57cec5SDimitry Andric // read a few words, modify, and write a few words, and some of the
25100b57cec5SDimitry Andric // words may be written to the same address.
25110b57cec5SDimitry Andric bool IsReadOnlyPtr = false;
251281ad6265SDimitry Andric Type *AccessTy = getLoadStoreType(LD);
251381ad6265SDimitry Andric if (Seen.insert({Ptr, AccessTy}).second ||
2514bdd1243dSDimitry Andric !getPtrStride(*PSE, LD->getType(), Ptr, TheLoop, SymbolicStrides).value_or(0)) {
25150b57cec5SDimitry Andric ++NumReads;
25160b57cec5SDimitry Andric IsReadOnlyPtr = true;
25170b57cec5SDimitry Andric }
25180b57cec5SDimitry Andric
25190b57cec5SDimitry Andric // See if there is an unsafe dependency between a load to a uniform address and
25200b57cec5SDimitry Andric // store to the same uniform address.
25210b57cec5SDimitry Andric if (UniformStores.count(Ptr)) {
25220b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Found an unsafe dependency between a uniform "
25230b57cec5SDimitry Andric "load and uniform store to the same address!\n");
25240b57cec5SDimitry Andric HasDependenceInvolvingLoopInvariantAddress = true;
25250b57cec5SDimitry Andric }
25260b57cec5SDimitry Andric
25270b57cec5SDimitry Andric MemoryLocation Loc = MemoryLocation::get(LD);
25280b57cec5SDimitry Andric // The TBAA metadata could have a control dependency on the predication
25290b57cec5SDimitry Andric // condition, so we cannot rely on it when determining whether or not we
25300b57cec5SDimitry Andric // need runtime pointer checks.
25310b57cec5SDimitry Andric if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
25320b57cec5SDimitry Andric Loc.AATags.TBAA = nullptr;
25330b57cec5SDimitry Andric
2534349cc55cSDimitry Andric visitPointers(const_cast<Value *>(Loc.Ptr), *TheLoop,
253581ad6265SDimitry Andric [&Accesses, AccessTy, Loc, IsReadOnlyPtr](Value *Ptr) {
2536349cc55cSDimitry Andric MemoryLocation NewLoc = Loc.getWithNewPtr(Ptr);
253781ad6265SDimitry Andric Accesses.addLoad(NewLoc, AccessTy, IsReadOnlyPtr);
2538349cc55cSDimitry Andric });
25390b57cec5SDimitry Andric }
25400b57cec5SDimitry Andric
25410b57cec5SDimitry Andric // If we write (or read-write) to a single destination and there are no
25420b57cec5SDimitry Andric // other reads in this loop then is it safe to vectorize.
25430b57cec5SDimitry Andric if (NumReadWrites == 1 && NumReads == 0) {
25440b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
25450b57cec5SDimitry Andric CanVecMem = true;
25460b57cec5SDimitry Andric return;
25470b57cec5SDimitry Andric }
25480b57cec5SDimitry Andric
25490b57cec5SDimitry Andric // Build dependence sets and check whether we need a runtime pointer bounds
25500b57cec5SDimitry Andric // check.
25510b57cec5SDimitry Andric Accesses.buildDependenceSets();
25520b57cec5SDimitry Andric
25530b57cec5SDimitry Andric // Find pointers with computable bounds. We are going to use this information
25540b57cec5SDimitry Andric // to place a runtime bound check.
255581ad6265SDimitry Andric Value *UncomputablePtr = nullptr;
255681ad6265SDimitry Andric bool CanDoRTIfNeeded =
255781ad6265SDimitry Andric Accesses.canCheckPtrAtRT(*PtrRtChecking, PSE->getSE(), TheLoop,
255881ad6265SDimitry Andric SymbolicStrides, UncomputablePtr, false);
25590b57cec5SDimitry Andric if (!CanDoRTIfNeeded) {
256081ad6265SDimitry Andric auto *I = dyn_cast_or_null<Instruction>(UncomputablePtr);
256181ad6265SDimitry Andric recordAnalysis("CantIdentifyArrayBounds", I)
256281ad6265SDimitry Andric << "cannot identify array bounds";
25630b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: We can't vectorize because we can't find "
25640b57cec5SDimitry Andric << "the array bounds.\n");
25650b57cec5SDimitry Andric CanVecMem = false;
25660b57cec5SDimitry Andric return;
25670b57cec5SDimitry Andric }
25680b57cec5SDimitry Andric
25690b57cec5SDimitry Andric LLVM_DEBUG(
25700b57cec5SDimitry Andric dbgs() << "LAA: May be able to perform a memory runtime check if needed.\n");
25710b57cec5SDimitry Andric
25720b57cec5SDimitry Andric CanVecMem = true;
25730b57cec5SDimitry Andric if (Accesses.isDependencyCheckNeeded()) {
25740b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
25750b57cec5SDimitry Andric CanVecMem = DepChecker->areDepsSafe(
2576c9157d92SDimitry Andric DependentAccesses, Accesses.getDependenciesToCheck(), SymbolicStrides,
2577c9157d92SDimitry Andric Accesses.getUnderlyingObjects());
25780b57cec5SDimitry Andric
25790b57cec5SDimitry Andric if (!CanVecMem && DepChecker->shouldRetryWithRuntimeCheck()) {
25800b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
25810b57cec5SDimitry Andric
25820b57cec5SDimitry Andric // Clear the dependency checks. We assume they are not needed.
25830b57cec5SDimitry Andric Accesses.resetDepChecks(*DepChecker);
25840b57cec5SDimitry Andric
25850b57cec5SDimitry Andric PtrRtChecking->reset();
25860b57cec5SDimitry Andric PtrRtChecking->Need = true;
25870b57cec5SDimitry Andric
25880b57cec5SDimitry Andric auto *SE = PSE->getSE();
258981ad6265SDimitry Andric UncomputablePtr = nullptr;
259081ad6265SDimitry Andric CanDoRTIfNeeded = Accesses.canCheckPtrAtRT(
259181ad6265SDimitry Andric *PtrRtChecking, SE, TheLoop, SymbolicStrides, UncomputablePtr, true);
25920b57cec5SDimitry Andric
25930b57cec5SDimitry Andric // Check that we found the bounds for the pointer.
25940b57cec5SDimitry Andric if (!CanDoRTIfNeeded) {
259581ad6265SDimitry Andric auto *I = dyn_cast_or_null<Instruction>(UncomputablePtr);
259681ad6265SDimitry Andric recordAnalysis("CantCheckMemDepsAtRunTime", I)
25970b57cec5SDimitry Andric << "cannot check memory dependencies at runtime";
25980b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
25990b57cec5SDimitry Andric CanVecMem = false;
26000b57cec5SDimitry Andric return;
26010b57cec5SDimitry Andric }
26020b57cec5SDimitry Andric
26030b57cec5SDimitry Andric CanVecMem = true;
26040b57cec5SDimitry Andric }
26050b57cec5SDimitry Andric }
26060b57cec5SDimitry Andric
26070b57cec5SDimitry Andric if (HasConvergentOp) {
26080b57cec5SDimitry Andric recordAnalysis("CantInsertRuntimeCheckWithConvergent")
26090b57cec5SDimitry Andric << "cannot add control dependency to convergent operation";
26100b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: We can't vectorize because a runtime check "
26110b57cec5SDimitry Andric "would be needed with a convergent operation\n");
26120b57cec5SDimitry Andric CanVecMem = false;
26130b57cec5SDimitry Andric return;
26140b57cec5SDimitry Andric }
26150b57cec5SDimitry Andric
26160b57cec5SDimitry Andric if (CanVecMem)
26170b57cec5SDimitry Andric LLVM_DEBUG(
26180b57cec5SDimitry Andric dbgs() << "LAA: No unsafe dependent memory operations in loop. We"
26190b57cec5SDimitry Andric << (PtrRtChecking->Need ? "" : " don't")
26200b57cec5SDimitry Andric << " need runtime memory checks.\n");
262181ad6265SDimitry Andric else
262281ad6265SDimitry Andric emitUnsafeDependenceRemark();
262381ad6265SDimitry Andric }
262481ad6265SDimitry Andric
emitUnsafeDependenceRemark()262581ad6265SDimitry Andric void LoopAccessInfo::emitUnsafeDependenceRemark() {
262681ad6265SDimitry Andric auto Deps = getDepChecker().getDependences();
262781ad6265SDimitry Andric if (!Deps)
262881ad6265SDimitry Andric return;
2629bdd1243dSDimitry Andric auto Found = llvm::find_if(*Deps, [](const MemoryDepChecker::Dependence &D) {
263081ad6265SDimitry Andric return MemoryDepChecker::Dependence::isSafeForVectorization(D.Type) !=
263181ad6265SDimitry Andric MemoryDepChecker::VectorizationSafetyStatus::Safe;
263281ad6265SDimitry Andric });
263381ad6265SDimitry Andric if (Found == Deps->end())
263481ad6265SDimitry Andric return;
263581ad6265SDimitry Andric MemoryDepChecker::Dependence Dep = *Found;
263681ad6265SDimitry Andric
263781ad6265SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
263881ad6265SDimitry Andric
263981ad6265SDimitry Andric // Emit remark for first unsafe dependence
2640c9157d92SDimitry Andric bool HasForcedDistribution = false;
2641c9157d92SDimitry Andric std::optional<const MDOperand *> Value =
2642c9157d92SDimitry Andric findStringMetadataForLoop(TheLoop, "llvm.loop.distribute.enable");
2643c9157d92SDimitry Andric if (Value) {
2644c9157d92SDimitry Andric const MDOperand *Op = *Value;
2645c9157d92SDimitry Andric assert(Op && mdconst::hasa<ConstantInt>(*Op) && "invalid metadata");
2646c9157d92SDimitry Andric HasForcedDistribution = mdconst::extract<ConstantInt>(*Op)->getZExtValue();
2647c9157d92SDimitry Andric }
2648c9157d92SDimitry Andric
2649c9157d92SDimitry Andric const std::string Info =
2650c9157d92SDimitry Andric HasForcedDistribution
2651c9157d92SDimitry Andric ? "unsafe dependent memory operations in loop."
2652c9157d92SDimitry Andric : "unsafe dependent memory operations in loop. Use "
2653c9157d92SDimitry Andric "#pragma clang loop distribute(enable) to allow loop distribution "
26540b57cec5SDimitry Andric "to attempt to isolate the offending operations into a separate "
26550b57cec5SDimitry Andric "loop";
2656c9157d92SDimitry Andric OptimizationRemarkAnalysis &R =
2657c9157d92SDimitry Andric recordAnalysis("UnsafeDep", Dep.getDestination(*this)) << Info;
265881ad6265SDimitry Andric
265981ad6265SDimitry Andric switch (Dep.Type) {
266081ad6265SDimitry Andric case MemoryDepChecker::Dependence::NoDep:
266181ad6265SDimitry Andric case MemoryDepChecker::Dependence::Forward:
266281ad6265SDimitry Andric case MemoryDepChecker::Dependence::BackwardVectorizable:
266381ad6265SDimitry Andric llvm_unreachable("Unexpected dependence");
266481ad6265SDimitry Andric case MemoryDepChecker::Dependence::Backward:
266581ad6265SDimitry Andric R << "\nBackward loop carried data dependence.";
266681ad6265SDimitry Andric break;
266781ad6265SDimitry Andric case MemoryDepChecker::Dependence::ForwardButPreventsForwarding:
266881ad6265SDimitry Andric R << "\nForward loop carried data dependence that prevents "
266981ad6265SDimitry Andric "store-to-load forwarding.";
267081ad6265SDimitry Andric break;
267181ad6265SDimitry Andric case MemoryDepChecker::Dependence::BackwardVectorizableButPreventsForwarding:
267281ad6265SDimitry Andric R << "\nBackward loop carried data dependence that prevents "
267381ad6265SDimitry Andric "store-to-load forwarding.";
267481ad6265SDimitry Andric break;
2675c9157d92SDimitry Andric case MemoryDepChecker::Dependence::IndirectUnsafe:
2676c9157d92SDimitry Andric R << "\nUnsafe indirect dependence.";
2677c9157d92SDimitry Andric break;
267881ad6265SDimitry Andric case MemoryDepChecker::Dependence::Unknown:
267981ad6265SDimitry Andric R << "\nUnknown data dependence.";
268081ad6265SDimitry Andric break;
268181ad6265SDimitry Andric }
268281ad6265SDimitry Andric
268381ad6265SDimitry Andric if (Instruction *I = Dep.getSource(*this)) {
268481ad6265SDimitry Andric DebugLoc SourceLoc = I->getDebugLoc();
268581ad6265SDimitry Andric if (auto *DD = dyn_cast_or_null<Instruction>(getPointerOperand(I)))
268681ad6265SDimitry Andric SourceLoc = DD->getDebugLoc();
268781ad6265SDimitry Andric if (SourceLoc)
268881ad6265SDimitry Andric R << " Memory location is the same as accessed at "
268981ad6265SDimitry Andric << ore::NV("Location", SourceLoc);
26900b57cec5SDimitry Andric }
26910b57cec5SDimitry Andric }
26920b57cec5SDimitry Andric
blockNeedsPredication(BasicBlock * BB,Loop * TheLoop,DominatorTree * DT)26930b57cec5SDimitry Andric bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
26940b57cec5SDimitry Andric DominatorTree *DT) {
26950b57cec5SDimitry Andric assert(TheLoop->contains(BB) && "Unknown block used");
26960b57cec5SDimitry Andric
26970b57cec5SDimitry Andric // Blocks that do not dominate the latch need predication.
26980b57cec5SDimitry Andric BasicBlock* Latch = TheLoop->getLoopLatch();
26990b57cec5SDimitry Andric return !DT->dominates(BB, Latch);
27000b57cec5SDimitry Andric }
27010b57cec5SDimitry Andric
recordAnalysis(StringRef RemarkName,Instruction * I)27020b57cec5SDimitry Andric OptimizationRemarkAnalysis &LoopAccessInfo::recordAnalysis(StringRef RemarkName,
27030b57cec5SDimitry Andric Instruction *I) {
27040b57cec5SDimitry Andric assert(!Report && "Multiple reports generated");
27050b57cec5SDimitry Andric
27060b57cec5SDimitry Andric Value *CodeRegion = TheLoop->getHeader();
27070b57cec5SDimitry Andric DebugLoc DL = TheLoop->getStartLoc();
27080b57cec5SDimitry Andric
27090b57cec5SDimitry Andric if (I) {
27100b57cec5SDimitry Andric CodeRegion = I->getParent();
27110b57cec5SDimitry Andric // If there is no debug location attached to the instruction, revert back to
27120b57cec5SDimitry Andric // using the loop's.
27130b57cec5SDimitry Andric if (I->getDebugLoc())
27140b57cec5SDimitry Andric DL = I->getDebugLoc();
27150b57cec5SDimitry Andric }
27160b57cec5SDimitry Andric
27178bcb0991SDimitry Andric Report = std::make_unique<OptimizationRemarkAnalysis>(DEBUG_TYPE, RemarkName, DL,
27180b57cec5SDimitry Andric CodeRegion);
27190b57cec5SDimitry Andric return *Report;
27200b57cec5SDimitry Andric }
27210b57cec5SDimitry Andric
isInvariant(Value * V) const2722fe013be4SDimitry Andric bool LoopAccessInfo::isInvariant(Value *V) const {
27230b57cec5SDimitry Andric auto *SE = PSE->getSE();
27240b57cec5SDimitry Andric // TODO: Is this really what we want? Even without FP SCEV, we may want some
2725fe013be4SDimitry Andric // trivially loop-invariant FP values to be considered invariant.
27260b57cec5SDimitry Andric if (!SE->isSCEVable(V->getType()))
27270b57cec5SDimitry Andric return false;
2728fe013be4SDimitry Andric const SCEV *S = SE->getSCEV(V);
2729fe013be4SDimitry Andric return SE->isLoopInvariant(S, TheLoop);
2730fe013be4SDimitry Andric }
2731fe013be4SDimitry Andric
2732fe013be4SDimitry Andric /// Find the operand of the GEP that should be checked for consecutive
2733fe013be4SDimitry Andric /// stores. This ignores trailing indices that have no effect on the final
2734fe013be4SDimitry Andric /// pointer.
getGEPInductionOperand(const GetElementPtrInst * Gep)2735fe013be4SDimitry Andric static unsigned getGEPInductionOperand(const GetElementPtrInst *Gep) {
2736fe013be4SDimitry Andric const DataLayout &DL = Gep->getModule()->getDataLayout();
2737fe013be4SDimitry Andric unsigned LastOperand = Gep->getNumOperands() - 1;
2738fe013be4SDimitry Andric TypeSize GEPAllocSize = DL.getTypeAllocSize(Gep->getResultElementType());
2739fe013be4SDimitry Andric
2740fe013be4SDimitry Andric // Walk backwards and try to peel off zeros.
2741fe013be4SDimitry Andric while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
2742fe013be4SDimitry Andric // Find the type we're currently indexing into.
2743fe013be4SDimitry Andric gep_type_iterator GEPTI = gep_type_begin(Gep);
2744fe013be4SDimitry Andric std::advance(GEPTI, LastOperand - 2);
2745fe013be4SDimitry Andric
2746fe013be4SDimitry Andric // If it's a type with the same allocation size as the result of the GEP we
2747fe013be4SDimitry Andric // can peel off the zero index.
2748cdc20ff6SDimitry Andric TypeSize ElemSize = GEPTI.isStruct()
2749cdc20ff6SDimitry Andric ? DL.getTypeAllocSize(GEPTI.getIndexedType())
2750cdc20ff6SDimitry Andric : GEPTI.getSequentialElementStride(DL);
2751cdc20ff6SDimitry Andric if (ElemSize != GEPAllocSize)
2752fe013be4SDimitry Andric break;
2753fe013be4SDimitry Andric --LastOperand;
2754fe013be4SDimitry Andric }
2755fe013be4SDimitry Andric
2756fe013be4SDimitry Andric return LastOperand;
2757fe013be4SDimitry Andric }
2758fe013be4SDimitry Andric
2759fe013be4SDimitry Andric /// If the argument is a GEP, then returns the operand identified by
2760fe013be4SDimitry Andric /// getGEPInductionOperand. However, if there is some other non-loop-invariant
2761fe013be4SDimitry Andric /// operand, it returns that instead.
stripGetElementPtr(Value * Ptr,ScalarEvolution * SE,Loop * Lp)2762fe013be4SDimitry Andric static Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
2763fe013be4SDimitry Andric GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
2764fe013be4SDimitry Andric if (!GEP)
2765fe013be4SDimitry Andric return Ptr;
2766fe013be4SDimitry Andric
2767fe013be4SDimitry Andric unsigned InductionOperand = getGEPInductionOperand(GEP);
2768fe013be4SDimitry Andric
2769fe013be4SDimitry Andric // Check that all of the gep indices are uniform except for our induction
2770fe013be4SDimitry Andric // operand.
2771fe013be4SDimitry Andric for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
2772fe013be4SDimitry Andric if (i != InductionOperand &&
2773fe013be4SDimitry Andric !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
2774fe013be4SDimitry Andric return Ptr;
2775fe013be4SDimitry Andric return GEP->getOperand(InductionOperand);
2776fe013be4SDimitry Andric }
2777fe013be4SDimitry Andric
2778fe013be4SDimitry Andric /// If a value has only one user that is a CastInst, return it.
getUniqueCastUse(Value * Ptr,Loop * Lp,Type * Ty)2779fe013be4SDimitry Andric static Value *getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
2780fe013be4SDimitry Andric Value *UniqueCast = nullptr;
2781fe013be4SDimitry Andric for (User *U : Ptr->users()) {
2782fe013be4SDimitry Andric CastInst *CI = dyn_cast<CastInst>(U);
2783fe013be4SDimitry Andric if (CI && CI->getType() == Ty) {
2784fe013be4SDimitry Andric if (!UniqueCast)
2785fe013be4SDimitry Andric UniqueCast = CI;
2786fe013be4SDimitry Andric else
2787fe013be4SDimitry Andric return nullptr;
2788fe013be4SDimitry Andric }
2789fe013be4SDimitry Andric }
2790fe013be4SDimitry Andric return UniqueCast;
2791fe013be4SDimitry Andric }
2792fe013be4SDimitry Andric
2793fe013be4SDimitry Andric /// Get the stride of a pointer access in a loop. Looks for symbolic
2794fe013be4SDimitry Andric /// strides "a[i*stride]". Returns the symbolic stride, or null otherwise.
getStrideFromPointer(Value * Ptr,ScalarEvolution * SE,Loop * Lp)2795fe013be4SDimitry Andric static const SCEV *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
2796fe013be4SDimitry Andric auto *PtrTy = dyn_cast<PointerType>(Ptr->getType());
2797fe013be4SDimitry Andric if (!PtrTy || PtrTy->isAggregateType())
2798fe013be4SDimitry Andric return nullptr;
2799fe013be4SDimitry Andric
2800fe013be4SDimitry Andric // Try to remove a gep instruction to make the pointer (actually index at this
2801fe013be4SDimitry Andric // point) easier analyzable. If OrigPtr is equal to Ptr we are analyzing the
2802fe013be4SDimitry Andric // pointer, otherwise, we are analyzing the index.
2803fe013be4SDimitry Andric Value *OrigPtr = Ptr;
2804fe013be4SDimitry Andric
2805fe013be4SDimitry Andric // The size of the pointer access.
2806fe013be4SDimitry Andric int64_t PtrAccessSize = 1;
2807fe013be4SDimitry Andric
2808fe013be4SDimitry Andric Ptr = stripGetElementPtr(Ptr, SE, Lp);
2809fe013be4SDimitry Andric const SCEV *V = SE->getSCEV(Ptr);
2810fe013be4SDimitry Andric
2811fe013be4SDimitry Andric if (Ptr != OrigPtr)
2812fe013be4SDimitry Andric // Strip off casts.
2813fe013be4SDimitry Andric while (const SCEVIntegralCastExpr *C = dyn_cast<SCEVIntegralCastExpr>(V))
2814fe013be4SDimitry Andric V = C->getOperand();
2815fe013be4SDimitry Andric
2816fe013be4SDimitry Andric const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
2817fe013be4SDimitry Andric if (!S)
2818fe013be4SDimitry Andric return nullptr;
2819fe013be4SDimitry Andric
2820fe013be4SDimitry Andric // If the pointer is invariant then there is no stride and it makes no
2821fe013be4SDimitry Andric // sense to add it here.
2822fe013be4SDimitry Andric if (Lp != S->getLoop())
2823fe013be4SDimitry Andric return nullptr;
2824fe013be4SDimitry Andric
2825fe013be4SDimitry Andric V = S->getStepRecurrence(*SE);
2826fe013be4SDimitry Andric if (!V)
2827fe013be4SDimitry Andric return nullptr;
2828fe013be4SDimitry Andric
2829fe013be4SDimitry Andric // Strip off the size of access multiplication if we are still analyzing the
2830fe013be4SDimitry Andric // pointer.
2831fe013be4SDimitry Andric if (OrigPtr == Ptr) {
2832fe013be4SDimitry Andric if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
2833fe013be4SDimitry Andric if (M->getOperand(0)->getSCEVType() != scConstant)
2834fe013be4SDimitry Andric return nullptr;
2835fe013be4SDimitry Andric
2836fe013be4SDimitry Andric const APInt &APStepVal = cast<SCEVConstant>(M->getOperand(0))->getAPInt();
2837fe013be4SDimitry Andric
2838fe013be4SDimitry Andric // Huge step value - give up.
2839fe013be4SDimitry Andric if (APStepVal.getBitWidth() > 64)
2840fe013be4SDimitry Andric return nullptr;
2841fe013be4SDimitry Andric
2842fe013be4SDimitry Andric int64_t StepVal = APStepVal.getSExtValue();
2843fe013be4SDimitry Andric if (PtrAccessSize != StepVal)
2844fe013be4SDimitry Andric return nullptr;
2845fe013be4SDimitry Andric V = M->getOperand(1);
2846fe013be4SDimitry Andric }
2847fe013be4SDimitry Andric }
2848fe013be4SDimitry Andric
2849fe013be4SDimitry Andric // Note that the restriction after this loop invariant check are only
2850fe013be4SDimitry Andric // profitability restrictions.
2851fe013be4SDimitry Andric if (!SE->isLoopInvariant(V, Lp))
2852fe013be4SDimitry Andric return nullptr;
2853fe013be4SDimitry Andric
2854fe013be4SDimitry Andric // Look for the loop invariant symbolic value.
2855fe013be4SDimitry Andric const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
2856fe013be4SDimitry Andric if (!U) {
2857fe013be4SDimitry Andric const auto *C = dyn_cast<SCEVIntegralCastExpr>(V);
2858fe013be4SDimitry Andric if (!C)
2859fe013be4SDimitry Andric return nullptr;
2860fe013be4SDimitry Andric U = dyn_cast<SCEVUnknown>(C->getOperand());
2861fe013be4SDimitry Andric if (!U)
2862fe013be4SDimitry Andric return nullptr;
2863fe013be4SDimitry Andric
2864fe013be4SDimitry Andric // Match legacy behavior - this is not needed for correctness
2865fe013be4SDimitry Andric if (!getUniqueCastUse(U->getValue(), Lp, V->getType()))
2866fe013be4SDimitry Andric return nullptr;
2867fe013be4SDimitry Andric }
2868fe013be4SDimitry Andric
2869fe013be4SDimitry Andric return V;
28700b57cec5SDimitry Andric }
28710b57cec5SDimitry Andric
collectStridedAccess(Value * MemAccess)28720b57cec5SDimitry Andric void LoopAccessInfo::collectStridedAccess(Value *MemAccess) {
2873e8d8bef9SDimitry Andric Value *Ptr = getLoadStorePointerOperand(MemAccess);
2874e8d8bef9SDimitry Andric if (!Ptr)
28750b57cec5SDimitry Andric return;
28760b57cec5SDimitry Andric
2877fe013be4SDimitry Andric // Note: getStrideFromPointer is a *profitability* heuristic. We
2878fe013be4SDimitry Andric // could broaden the scope of values returned here - to anything
2879fe013be4SDimitry Andric // which happens to be loop invariant and contributes to the
2880fe013be4SDimitry Andric // computation of an interesting IV - but we chose not to as we
2881fe013be4SDimitry Andric // don't have a cost model here, and broadening the scope exposes
2882fe013be4SDimitry Andric // far too many unprofitable cases.
2883fe013be4SDimitry Andric const SCEV *StrideExpr = getStrideFromPointer(Ptr, PSE->getSE(), TheLoop);
2884fe013be4SDimitry Andric if (!StrideExpr)
28850b57cec5SDimitry Andric return;
28860b57cec5SDimitry Andric
28870b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Found a strided access that is a candidate for "
28880b57cec5SDimitry Andric "versioning:");
2889fe013be4SDimitry Andric LLVM_DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *StrideExpr << "\n");
2890fe013be4SDimitry Andric
2891fe013be4SDimitry Andric if (!SpeculateUnitStride) {
2892fe013be4SDimitry Andric LLVM_DEBUG(dbgs() << " Chose not to due to -laa-speculate-unit-stride\n");
2893fe013be4SDimitry Andric return;
2894fe013be4SDimitry Andric }
28950b57cec5SDimitry Andric
28960b57cec5SDimitry Andric // Avoid adding the "Stride == 1" predicate when we know that
28970b57cec5SDimitry Andric // Stride >= Trip-Count. Such a predicate will effectively optimize a single
28980b57cec5SDimitry Andric // or zero iteration loop, as Trip-Count <= Stride == 1.
28990b57cec5SDimitry Andric //
29000b57cec5SDimitry Andric // TODO: We are currently not making a very informed decision on when it is
29010b57cec5SDimitry Andric // beneficial to apply stride versioning. It might make more sense that the
29020b57cec5SDimitry Andric // users of this analysis (such as the vectorizer) will trigger it, based on
29030b57cec5SDimitry Andric // their specific cost considerations; For example, in cases where stride
29040b57cec5SDimitry Andric // versioning does not help resolving memory accesses/dependences, the
29050b57cec5SDimitry Andric // vectorizer should evaluate the cost of the runtime test, and the benefit
29060b57cec5SDimitry Andric // of various possible stride specializations, considering the alternatives
29070b57cec5SDimitry Andric // of using gather/scatters (if available).
29080b57cec5SDimitry Andric
29090b57cec5SDimitry Andric const SCEV *BETakenCount = PSE->getBackedgeTakenCount();
29100b57cec5SDimitry Andric
29110b57cec5SDimitry Andric // Match the types so we can compare the stride and the BETakenCount.
29120b57cec5SDimitry Andric // The Stride can be positive/negative, so we sign extend Stride;
29130b57cec5SDimitry Andric // The backedgeTakenCount is non-negative, so we zero extend BETakenCount.
29140b57cec5SDimitry Andric const DataLayout &DL = TheLoop->getHeader()->getModule()->getDataLayout();
291581ad6265SDimitry Andric uint64_t StrideTypeSizeBits = DL.getTypeSizeInBits(StrideExpr->getType());
291681ad6265SDimitry Andric uint64_t BETypeSizeBits = DL.getTypeSizeInBits(BETakenCount->getType());
29170b57cec5SDimitry Andric const SCEV *CastedStride = StrideExpr;
29180b57cec5SDimitry Andric const SCEV *CastedBECount = BETakenCount;
29190b57cec5SDimitry Andric ScalarEvolution *SE = PSE->getSE();
292081ad6265SDimitry Andric if (BETypeSizeBits >= StrideTypeSizeBits)
29210b57cec5SDimitry Andric CastedStride = SE->getNoopOrSignExtend(StrideExpr, BETakenCount->getType());
29220b57cec5SDimitry Andric else
29230b57cec5SDimitry Andric CastedBECount = SE->getZeroExtendExpr(BETakenCount, StrideExpr->getType());
29240b57cec5SDimitry Andric const SCEV *StrideMinusBETaken = SE->getMinusSCEV(CastedStride, CastedBECount);
29250b57cec5SDimitry Andric // Since TripCount == BackEdgeTakenCount + 1, checking:
29260b57cec5SDimitry Andric // "Stride >= TripCount" is equivalent to checking:
29270b57cec5SDimitry Andric // Stride - BETakenCount > 0
29280b57cec5SDimitry Andric if (SE->isKnownPositive(StrideMinusBETaken)) {
29290b57cec5SDimitry Andric LLVM_DEBUG(
29300b57cec5SDimitry Andric dbgs() << "LAA: Stride>=TripCount; No point in versioning as the "
29310b57cec5SDimitry Andric "Stride==1 predicate will imply that the loop executes "
29320b57cec5SDimitry Andric "at most once.\n");
29330b57cec5SDimitry Andric return;
29340b57cec5SDimitry Andric }
293581ad6265SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Found a strided access that we can version.\n");
29360b57cec5SDimitry Andric
2937fe013be4SDimitry Andric // Strip back off the integer cast, and check that our result is a
2938fe013be4SDimitry Andric // SCEVUnknown as we expect.
2939fe013be4SDimitry Andric const SCEV *StrideBase = StrideExpr;
2940fe013be4SDimitry Andric if (const auto *C = dyn_cast<SCEVIntegralCastExpr>(StrideBase))
2941fe013be4SDimitry Andric StrideBase = C->getOperand();
2942fe013be4SDimitry Andric SymbolicStrides[Ptr] = cast<SCEVUnknown>(StrideBase);
29430b57cec5SDimitry Andric }
29440b57cec5SDimitry Andric
LoopAccessInfo(Loop * L,ScalarEvolution * SE,const TargetLibraryInfo * TLI,AAResults * AA,DominatorTree * DT,LoopInfo * LI)29450b57cec5SDimitry Andric LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
29465ffd83dbSDimitry Andric const TargetLibraryInfo *TLI, AAResults *AA,
29470b57cec5SDimitry Andric DominatorTree *DT, LoopInfo *LI)
29488bcb0991SDimitry Andric : PSE(std::make_unique<PredicatedScalarEvolution>(*SE, *L)),
294981ad6265SDimitry Andric PtrRtChecking(nullptr),
295004eeddc0SDimitry Andric DepChecker(std::make_unique<MemoryDepChecker>(*PSE, L)), TheLoop(L) {
295181ad6265SDimitry Andric PtrRtChecking = std::make_unique<RuntimePointerChecking>(*DepChecker, SE);
295281ad6265SDimitry Andric if (canAnalyzeLoop()) {
29530b57cec5SDimitry Andric analyzeLoop(AA, LI, TLI, DT);
29540b57cec5SDimitry Andric }
295581ad6265SDimitry Andric }
29560b57cec5SDimitry Andric
print(raw_ostream & OS,unsigned Depth) const29570b57cec5SDimitry Andric void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
29580b57cec5SDimitry Andric if (CanVecMem) {
29590b57cec5SDimitry Andric OS.indent(Depth) << "Memory dependences are safe";
2960c9157d92SDimitry Andric const MemoryDepChecker &DC = getDepChecker();
2961c9157d92SDimitry Andric if (!DC.isSafeForAnyVectorWidth())
2962c9157d92SDimitry Andric OS << " with a maximum safe vector width of "
2963c9157d92SDimitry Andric << DC.getMaxSafeVectorWidthInBits() << " bits";
29640b57cec5SDimitry Andric if (PtrRtChecking->Need)
29650b57cec5SDimitry Andric OS << " with run-time checks";
29660b57cec5SDimitry Andric OS << "\n";
29670b57cec5SDimitry Andric }
29680b57cec5SDimitry Andric
29690b57cec5SDimitry Andric if (HasConvergentOp)
29700b57cec5SDimitry Andric OS.indent(Depth) << "Has convergent operation in loop\n";
29710b57cec5SDimitry Andric
29720b57cec5SDimitry Andric if (Report)
29730b57cec5SDimitry Andric OS.indent(Depth) << "Report: " << Report->getMsg() << "\n";
29740b57cec5SDimitry Andric
29750b57cec5SDimitry Andric if (auto *Dependences = DepChecker->getDependences()) {
29760b57cec5SDimitry Andric OS.indent(Depth) << "Dependences:\n";
2977fcaf7f86SDimitry Andric for (const auto &Dep : *Dependences) {
29780b57cec5SDimitry Andric Dep.print(OS, Depth + 2, DepChecker->getMemoryInstructions());
29790b57cec5SDimitry Andric OS << "\n";
29800b57cec5SDimitry Andric }
29810b57cec5SDimitry Andric } else
29820b57cec5SDimitry Andric OS.indent(Depth) << "Too many dependences, not recorded\n";
29830b57cec5SDimitry Andric
29840b57cec5SDimitry Andric // List the pair of accesses need run-time checks to prove independence.
29850b57cec5SDimitry Andric PtrRtChecking->print(OS, Depth);
29860b57cec5SDimitry Andric OS << "\n";
29870b57cec5SDimitry Andric
29880b57cec5SDimitry Andric OS.indent(Depth) << "Non vectorizable stores to invariant address were "
29890b57cec5SDimitry Andric << (HasDependenceInvolvingLoopInvariantAddress ? "" : "not ")
29900b57cec5SDimitry Andric << "found in loop.\n";
29910b57cec5SDimitry Andric
29920b57cec5SDimitry Andric OS.indent(Depth) << "SCEV assumptions:\n";
299381ad6265SDimitry Andric PSE->getPredicate().print(OS, Depth);
29940b57cec5SDimitry Andric
29950b57cec5SDimitry Andric OS << "\n";
29960b57cec5SDimitry Andric
29970b57cec5SDimitry Andric OS.indent(Depth) << "Expressions re-written:\n";
29980b57cec5SDimitry Andric PSE->print(OS, Depth);
29990b57cec5SDimitry Andric }
30000b57cec5SDimitry Andric
getInfo(Loop & L)3001bdd1243dSDimitry Andric const LoopAccessInfo &LoopAccessInfoManager::getInfo(Loop &L) {
3002bdd1243dSDimitry Andric auto I = LoopAccessInfoMap.insert({&L, nullptr});
3003bdd1243dSDimitry Andric
3004bdd1243dSDimitry Andric if (I.second)
3005bdd1243dSDimitry Andric I.first->second =
3006bdd1243dSDimitry Andric std::make_unique<LoopAccessInfo>(&L, &SE, TLI, &AA, &DT, &LI);
3007bdd1243dSDimitry Andric
3008bdd1243dSDimitry Andric return *I.first->second;
3009bdd1243dSDimitry Andric }
3010bdd1243dSDimitry Andric
invalidate(Function & F,const PreservedAnalyses & PA,FunctionAnalysisManager::Invalidator & Inv)3011fe013be4SDimitry Andric bool LoopAccessInfoManager::invalidate(
3012fe013be4SDimitry Andric Function &F, const PreservedAnalyses &PA,
3013fe013be4SDimitry Andric FunctionAnalysisManager::Invalidator &Inv) {
3014fe013be4SDimitry Andric // Check whether our analysis is preserved.
3015fe013be4SDimitry Andric auto PAC = PA.getChecker<LoopAccessAnalysis>();
3016fe013be4SDimitry Andric if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<Function>>())
3017fe013be4SDimitry Andric // If not, give up now.
3018fe013be4SDimitry Andric return true;
3019480093f4SDimitry Andric
3020fe013be4SDimitry Andric // Check whether the analyses we depend on became invalid for any reason.
3021fe013be4SDimitry Andric // Skip checking TargetLibraryAnalysis as it is immutable and can't become
3022fe013be4SDimitry Andric // invalid.
3023fe013be4SDimitry Andric return Inv.invalidate<AAManager>(F, PA) ||
3024fe013be4SDimitry Andric Inv.invalidate<ScalarEvolutionAnalysis>(F, PA) ||
3025fe013be4SDimitry Andric Inv.invalidate<LoopAnalysis>(F, PA) ||
3026fe013be4SDimitry Andric Inv.invalidate<DominatorTreeAnalysis>(F, PA);
30270b57cec5SDimitry Andric }
30280b57cec5SDimitry Andric
run(Function & F,FunctionAnalysisManager & FAM)3029bdd1243dSDimitry Andric LoopAccessInfoManager LoopAccessAnalysis::run(Function &F,
3030fe013be4SDimitry Andric FunctionAnalysisManager &FAM) {
3031fe013be4SDimitry Andric auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
3032fe013be4SDimitry Andric auto &AA = FAM.getResult<AAManager>(F);
3033fe013be4SDimitry Andric auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
3034fe013be4SDimitry Andric auto &LI = FAM.getResult<LoopAnalysis>(F);
3035fe013be4SDimitry Andric auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
3036fe013be4SDimitry Andric return LoopAccessInfoManager(SE, AA, DT, LI, &TLI);
3037bdd1243dSDimitry Andric }
3038bdd1243dSDimitry Andric
30390b57cec5SDimitry Andric AnalysisKey LoopAccessAnalysis::Key;
3040