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 1490b57cec5SDimitry Andric bool VectorizerParams::isInterleaveForced() { 1500b57cec5SDimitry Andric return ::VectorizationInterleave.getNumOccurrences() > 0; 1510b57cec5SDimitry Andric } 1520b57cec5SDimitry Andric 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 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) 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 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 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 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 3945ffd83dbSDimitry 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. 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 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 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 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 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 5890b57cec5SDimitry 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 6080b57cec5SDimitry 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 6270b57cec5SDimitry 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 658e8d8bef9SDimitry Andric AccessAnalysis(Loop *TheLoop, AAResults *AA, LoopInfo *LI, 659e8d8bef9SDimitry Andric MemoryDepChecker::DepCandidates &DA, 6600b57cec5SDimitry Andric PredicatedScalarEvolution &PSE) 661bdd1243dSDimitry Andric : TheLoop(TheLoop), BAA(*AA), AST(BAA), LI(LI), DepCands(DA), PSE(PSE) { 662bdd1243dSDimitry Andric // We're analyzing dependences across loop iterations. 663bdd1243dSDimitry Andric BAA.enableCrossIterationMode(); 664bdd1243dSDimitry Andric } 6650b57cec5SDimitry Andric 6660b57cec5SDimitry Andric /// Register a load and whether it is only read from. 66781ad6265SDimitry Andric void addLoad(MemoryLocation &Loc, Type *AccessTy, bool IsReadOnly) { 6680b57cec5SDimitry Andric Value *Ptr = const_cast<Value*>(Loc.Ptr); 669c9157d92SDimitry Andric AST.add(Loc.getWithNewSize(LocationSize::beforeOrAfterPointer())); 67081ad6265SDimitry Andric Accesses[MemAccessInfo(Ptr, false)].insert(AccessTy); 6710b57cec5SDimitry Andric if (IsReadOnly) 6720b57cec5SDimitry Andric ReadOnlyPtr.insert(Ptr); 6730b57cec5SDimitry Andric } 6740b57cec5SDimitry Andric 6750b57cec5SDimitry Andric /// Register a store. 67681ad6265SDimitry Andric void addStore(MemoryLocation &Loc, Type *AccessTy) { 6770b57cec5SDimitry Andric Value *Ptr = const_cast<Value*>(Loc.Ptr); 678c9157d92SDimitry Andric AST.add(Loc.getWithNewSize(LocationSize::beforeOrAfterPointer())); 67981ad6265SDimitry Andric Accesses[MemAccessInfo(Ptr, true)].insert(AccessTy); 6800b57cec5SDimitry Andric } 6810b57cec5SDimitry Andric 6820b57cec5SDimitry Andric /// Check if we can emit a run-time no-alias check for \p Access. 6830b57cec5SDimitry Andric /// 6840b57cec5SDimitry Andric /// Returns true if we can emit a run-time no alias check for \p Access. 6850b57cec5SDimitry Andric /// If we can check this access, this also adds it to a dependence set and 6860b57cec5SDimitry Andric /// adds a run-time to check for it to \p RtCheck. If \p Assume is true, 6870b57cec5SDimitry Andric /// we will attempt to use additional run-time checks in order to get 6880b57cec5SDimitry Andric /// the bounds of the pointer. 6890b57cec5SDimitry Andric bool createCheckForAccess(RuntimePointerChecking &RtCheck, 69081ad6265SDimitry Andric MemAccessInfo Access, Type *AccessTy, 691fe013be4SDimitry Andric const DenseMap<Value *, const SCEV *> &Strides, 6920b57cec5SDimitry Andric DenseMap<Value *, unsigned> &DepSetId, 6930b57cec5SDimitry Andric Loop *TheLoop, unsigned &RunningDepId, 69481ad6265SDimitry Andric unsigned ASId, bool ShouldCheckStride, bool Assume); 6950b57cec5SDimitry Andric 6960b57cec5SDimitry Andric /// Check whether we can check the pointers at runtime for 6970b57cec5SDimitry Andric /// non-intersection. 6980b57cec5SDimitry Andric /// 6990b57cec5SDimitry Andric /// Returns true if we need no check or if we do and we can generate them 7000b57cec5SDimitry Andric /// (i.e. the pointers have computable bounds). 7010b57cec5SDimitry Andric bool canCheckPtrAtRT(RuntimePointerChecking &RtCheck, ScalarEvolution *SE, 702fe013be4SDimitry Andric Loop *TheLoop, const DenseMap<Value *, const SCEV *> &Strides, 70381ad6265SDimitry Andric Value *&UncomputablePtr, bool ShouldCheckWrap = false); 7040b57cec5SDimitry Andric 7050b57cec5SDimitry Andric /// Goes over all memory accesses, checks whether a RT check is needed 7060b57cec5SDimitry Andric /// and builds sets of dependent accesses. 7070b57cec5SDimitry Andric void buildDependenceSets() { 7080b57cec5SDimitry Andric processMemAccesses(); 7090b57cec5SDimitry Andric } 7100b57cec5SDimitry Andric 7110b57cec5SDimitry Andric /// Initial processing of memory accesses determined that we need to 7120b57cec5SDimitry Andric /// perform dependency checking. 7130b57cec5SDimitry Andric /// 7140b57cec5SDimitry Andric /// Note that this can later be cleared if we retry memcheck analysis without 7150b57cec5SDimitry Andric /// dependency checking (i.e. FoundNonConstantDistanceDependence). 7160b57cec5SDimitry Andric bool isDependencyCheckNeeded() { return !CheckDeps.empty(); } 7170b57cec5SDimitry Andric 7180b57cec5SDimitry Andric /// We decided that no dependence analysis would be used. Reset the state. 7190b57cec5SDimitry Andric void resetDepChecks(MemoryDepChecker &DepChecker) { 7200b57cec5SDimitry Andric CheckDeps.clear(); 7210b57cec5SDimitry Andric DepChecker.clearDependences(); 7220b57cec5SDimitry Andric } 7230b57cec5SDimitry Andric 7240b57cec5SDimitry Andric MemAccessInfoList &getDependenciesToCheck() { return CheckDeps; } 7250b57cec5SDimitry Andric 726c9157d92SDimitry Andric const DenseMap<Value *, SmallVector<const Value *, 16>> & 727c9157d92SDimitry Andric getUnderlyingObjects() { 728c9157d92SDimitry Andric return UnderlyingObjects; 729c9157d92SDimitry Andric } 730c9157d92SDimitry Andric 7310b57cec5SDimitry Andric private: 73281ad6265SDimitry Andric typedef MapVector<MemAccessInfo, SmallSetVector<Type *, 1>> PtrAccessMap; 7330b57cec5SDimitry Andric 7340b57cec5SDimitry Andric /// Go over all memory access and check whether runtime pointer checks 7350b57cec5SDimitry Andric /// are needed and build sets of dependency check candidates. 7360b57cec5SDimitry Andric void processMemAccesses(); 7370b57cec5SDimitry Andric 73881ad6265SDimitry Andric /// Map of all accesses. Values are the types used to access memory pointed to 73981ad6265SDimitry Andric /// by the pointer. 74081ad6265SDimitry Andric PtrAccessMap Accesses; 7410b57cec5SDimitry Andric 7420b57cec5SDimitry Andric /// The loop being checked. 7430b57cec5SDimitry Andric const Loop *TheLoop; 7440b57cec5SDimitry Andric 7450b57cec5SDimitry Andric /// List of accesses that need a further dependence check. 7460b57cec5SDimitry Andric MemAccessInfoList CheckDeps; 7470b57cec5SDimitry Andric 7480b57cec5SDimitry Andric /// Set of pointers that are read only. 7490b57cec5SDimitry Andric SmallPtrSet<Value*, 16> ReadOnlyPtr; 7500b57cec5SDimitry Andric 751bdd1243dSDimitry Andric /// Batched alias analysis results. 752bdd1243dSDimitry Andric BatchAAResults BAA; 753bdd1243dSDimitry Andric 7540b57cec5SDimitry Andric /// An alias set tracker to partition the access set by underlying object and 7550b57cec5SDimitry Andric //intrinsic property (such as TBAA metadata). 7560b57cec5SDimitry Andric AliasSetTracker AST; 7570b57cec5SDimitry Andric 7580b57cec5SDimitry Andric LoopInfo *LI; 7590b57cec5SDimitry Andric 7600b57cec5SDimitry Andric /// Sets of potentially dependent accesses - members of one set share an 7610b57cec5SDimitry Andric /// underlying pointer. The set "CheckDeps" identfies which sets really need a 7620b57cec5SDimitry Andric /// dependence check. 7630b57cec5SDimitry Andric MemoryDepChecker::DepCandidates &DepCands; 7640b57cec5SDimitry Andric 7650b57cec5SDimitry Andric /// Initial processing of memory accesses determined that we may need 7660b57cec5SDimitry Andric /// to add memchecks. Perform the analysis to determine the necessary checks. 7670b57cec5SDimitry Andric /// 7680b57cec5SDimitry Andric /// Note that, this is different from isDependencyCheckNeeded. When we retry 7690b57cec5SDimitry Andric /// memcheck analysis without dependency checking 7700b57cec5SDimitry Andric /// (i.e. FoundNonConstantDistanceDependence), isDependencyCheckNeeded is 7710b57cec5SDimitry Andric /// cleared while this remains set if we have potentially dependent accesses. 77204eeddc0SDimitry Andric bool IsRTCheckAnalysisNeeded = false; 7730b57cec5SDimitry Andric 7740b57cec5SDimitry Andric /// The SCEV predicate containing all the SCEV-related assumptions. 7750b57cec5SDimitry Andric PredicatedScalarEvolution &PSE; 776c9157d92SDimitry Andric 777c9157d92SDimitry Andric DenseMap<Value *, SmallVector<const Value *, 16>> UnderlyingObjects; 7780b57cec5SDimitry Andric }; 7790b57cec5SDimitry Andric 7800b57cec5SDimitry Andric } // end anonymous namespace 7810b57cec5SDimitry Andric 7820b57cec5SDimitry Andric /// Check whether a pointer can participate in a runtime bounds check. 7830b57cec5SDimitry Andric /// If \p Assume, try harder to prove that we can compute the bounds of \p Ptr 7840b57cec5SDimitry Andric /// by adding run-time checks (overflow checks) if necessary. 78581ad6265SDimitry Andric static bool hasComputableBounds(PredicatedScalarEvolution &PSE, Value *Ptr, 78681ad6265SDimitry Andric const SCEV *PtrScev, Loop *L, bool Assume) { 7870b57cec5SDimitry Andric // The bounds for loop-invariant pointer is trivial. 7880b57cec5SDimitry Andric if (PSE.getSE()->isLoopInvariant(PtrScev, L)) 7890b57cec5SDimitry Andric return true; 7900b57cec5SDimitry Andric 7910b57cec5SDimitry Andric const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev); 7920b57cec5SDimitry Andric 7930b57cec5SDimitry Andric if (!AR && Assume) 7940b57cec5SDimitry Andric AR = PSE.getAsAddRec(Ptr); 7950b57cec5SDimitry Andric 7960b57cec5SDimitry Andric if (!AR) 7970b57cec5SDimitry Andric return false; 7980b57cec5SDimitry Andric 7990b57cec5SDimitry Andric return AR->isAffine(); 8000b57cec5SDimitry Andric } 8010b57cec5SDimitry Andric 8020b57cec5SDimitry Andric /// Check whether a pointer address cannot wrap. 8030b57cec5SDimitry Andric static bool isNoWrap(PredicatedScalarEvolution &PSE, 804fe013be4SDimitry Andric const DenseMap<Value *, const SCEV *> &Strides, Value *Ptr, Type *AccessTy, 80581ad6265SDimitry Andric Loop *L) { 8060b57cec5SDimitry Andric const SCEV *PtrScev = PSE.getSCEV(Ptr); 8070b57cec5SDimitry Andric if (PSE.getSE()->isLoopInvariant(PtrScev, L)) 8080b57cec5SDimitry Andric return true; 8090b57cec5SDimitry Andric 810bdd1243dSDimitry Andric int64_t Stride = getPtrStride(PSE, AccessTy, Ptr, L, Strides).value_or(0); 8110b57cec5SDimitry Andric if (Stride == 1 || PSE.hasNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW)) 8120b57cec5SDimitry Andric return true; 8130b57cec5SDimitry Andric 8140b57cec5SDimitry Andric return false; 8150b57cec5SDimitry Andric } 8160b57cec5SDimitry Andric 8174824e7fdSDimitry Andric static void visitPointers(Value *StartPtr, const Loop &InnermostLoop, 8184824e7fdSDimitry Andric function_ref<void(Value *)> AddPointer) { 8194824e7fdSDimitry Andric SmallPtrSet<Value *, 8> Visited; 8204824e7fdSDimitry Andric SmallVector<Value *> WorkList; 8214824e7fdSDimitry Andric WorkList.push_back(StartPtr); 8224824e7fdSDimitry Andric 8234824e7fdSDimitry Andric while (!WorkList.empty()) { 8244824e7fdSDimitry Andric Value *Ptr = WorkList.pop_back_val(); 8254824e7fdSDimitry Andric if (!Visited.insert(Ptr).second) 8264824e7fdSDimitry Andric continue; 8274824e7fdSDimitry Andric auto *PN = dyn_cast<PHINode>(Ptr); 8284824e7fdSDimitry Andric // SCEV does not look through non-header PHIs inside the loop. Such phis 8294824e7fdSDimitry Andric // can be analyzed by adding separate accesses for each incoming pointer 8304824e7fdSDimitry Andric // value. 8314824e7fdSDimitry Andric if (PN && InnermostLoop.contains(PN->getParent()) && 8324824e7fdSDimitry Andric PN->getParent() != InnermostLoop.getHeader()) { 8334824e7fdSDimitry Andric for (const Use &Inc : PN->incoming_values()) 8344824e7fdSDimitry Andric WorkList.push_back(Inc); 8354824e7fdSDimitry Andric } else 8364824e7fdSDimitry Andric AddPointer(Ptr); 8374824e7fdSDimitry Andric } 8384824e7fdSDimitry Andric } 8394824e7fdSDimitry Andric 840fcaf7f86SDimitry Andric // Walk back through the IR for a pointer, looking for a select like the 841fcaf7f86SDimitry Andric // following: 842fcaf7f86SDimitry Andric // 843fcaf7f86SDimitry Andric // %offset = select i1 %cmp, i64 %a, i64 %b 844fcaf7f86SDimitry Andric // %addr = getelementptr double, double* %base, i64 %offset 845fcaf7f86SDimitry Andric // %ld = load double, double* %addr, align 8 846fcaf7f86SDimitry Andric // 847fcaf7f86SDimitry Andric // We won't be able to form a single SCEVAddRecExpr from this since the 848fcaf7f86SDimitry Andric // address for each loop iteration depends on %cmp. We could potentially 849fcaf7f86SDimitry Andric // produce multiple valid SCEVAddRecExprs, though, and check all of them for 850fcaf7f86SDimitry Andric // memory safety/aliasing if needed. 851fcaf7f86SDimitry Andric // 852fcaf7f86SDimitry Andric // If we encounter some IR we don't yet handle, or something obviously fine 853fcaf7f86SDimitry Andric // like a constant, then we just add the SCEV for that term to the list passed 854fcaf7f86SDimitry Andric // in by the caller. If we have a node that may potentially yield a valid 855fcaf7f86SDimitry Andric // SCEVAddRecExpr then we decompose it into parts and build the SCEV terms 856fcaf7f86SDimitry Andric // ourselves before adding to the list. 857bdd1243dSDimitry Andric static void findForkedSCEVs( 858bdd1243dSDimitry Andric ScalarEvolution *SE, const Loop *L, Value *Ptr, 859bdd1243dSDimitry Andric SmallVectorImpl<PointerIntPair<const SCEV *, 1, bool>> &ScevList, 860fcaf7f86SDimitry Andric unsigned Depth) { 861fcaf7f86SDimitry Andric // If our Value is a SCEVAddRecExpr, loop invariant, not an instruction, or 862fcaf7f86SDimitry Andric // we've exceeded our limit on recursion, just return whatever we have 863fcaf7f86SDimitry Andric // regardless of whether it can be used for a forked pointer or not, along 864fcaf7f86SDimitry Andric // with an indication of whether it might be a poison or undef value. 865fcaf7f86SDimitry Andric const SCEV *Scev = SE->getSCEV(Ptr); 866fcaf7f86SDimitry Andric if (isa<SCEVAddRecExpr>(Scev) || L->isLoopInvariant(Ptr) || 867fcaf7f86SDimitry Andric !isa<Instruction>(Ptr) || Depth == 0) { 868bdd1243dSDimitry Andric ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr)); 869fcaf7f86SDimitry Andric return; 870fcaf7f86SDimitry Andric } 871fcaf7f86SDimitry Andric 872fcaf7f86SDimitry Andric Depth--; 873fcaf7f86SDimitry Andric 874bdd1243dSDimitry Andric auto UndefPoisonCheck = [](PointerIntPair<const SCEV *, 1, bool> S) { 875bdd1243dSDimitry Andric return get<1>(S); 876bdd1243dSDimitry Andric }; 877bdd1243dSDimitry Andric 878bdd1243dSDimitry Andric auto GetBinOpExpr = [&SE](unsigned Opcode, const SCEV *L, const SCEV *R) { 879bdd1243dSDimitry Andric switch (Opcode) { 880bdd1243dSDimitry Andric case Instruction::Add: 881bdd1243dSDimitry Andric return SE->getAddExpr(L, R); 882bdd1243dSDimitry Andric case Instruction::Sub: 883bdd1243dSDimitry Andric return SE->getMinusSCEV(L, R); 884bdd1243dSDimitry Andric default: 885bdd1243dSDimitry Andric llvm_unreachable("Unexpected binary operator when walking ForkedPtrs"); 886bdd1243dSDimitry Andric } 887fcaf7f86SDimitry Andric }; 888fcaf7f86SDimitry Andric 889fcaf7f86SDimitry Andric Instruction *I = cast<Instruction>(Ptr); 890fcaf7f86SDimitry Andric unsigned Opcode = I->getOpcode(); 891fcaf7f86SDimitry Andric switch (Opcode) { 892fcaf7f86SDimitry Andric case Instruction::GetElementPtr: { 893fcaf7f86SDimitry Andric GetElementPtrInst *GEP = cast<GetElementPtrInst>(I); 894fcaf7f86SDimitry Andric Type *SourceTy = GEP->getSourceElementType(); 895fcaf7f86SDimitry Andric // We only handle base + single offset GEPs here for now. 896fcaf7f86SDimitry Andric // Not dealing with preexisting gathers yet, so no vectors. 897fcaf7f86SDimitry Andric if (I->getNumOperands() != 2 || SourceTy->isVectorTy()) { 898bdd1243dSDimitry Andric ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(GEP)); 899fcaf7f86SDimitry Andric break; 900fcaf7f86SDimitry Andric } 901bdd1243dSDimitry Andric SmallVector<PointerIntPair<const SCEV *, 1, bool>, 2> BaseScevs; 902bdd1243dSDimitry Andric SmallVector<PointerIntPair<const SCEV *, 1, bool>, 2> OffsetScevs; 903fcaf7f86SDimitry Andric findForkedSCEVs(SE, L, I->getOperand(0), BaseScevs, Depth); 904fcaf7f86SDimitry Andric findForkedSCEVs(SE, L, I->getOperand(1), OffsetScevs, Depth); 905fcaf7f86SDimitry Andric 906fcaf7f86SDimitry Andric // See if we need to freeze our fork... 907fcaf7f86SDimitry Andric bool NeedsFreeze = any_of(BaseScevs, UndefPoisonCheck) || 908fcaf7f86SDimitry Andric any_of(OffsetScevs, UndefPoisonCheck); 909fcaf7f86SDimitry Andric 910fcaf7f86SDimitry Andric // Check that we only have a single fork, on either the base or the offset. 911fcaf7f86SDimitry Andric // Copy the SCEV across for the one without a fork in order to generate 912fcaf7f86SDimitry Andric // the full SCEV for both sides of the GEP. 913fcaf7f86SDimitry Andric if (OffsetScevs.size() == 2 && BaseScevs.size() == 1) 914fcaf7f86SDimitry Andric BaseScevs.push_back(BaseScevs[0]); 915fcaf7f86SDimitry Andric else if (BaseScevs.size() == 2 && OffsetScevs.size() == 1) 916fcaf7f86SDimitry Andric OffsetScevs.push_back(OffsetScevs[0]); 917fcaf7f86SDimitry Andric else { 918bdd1243dSDimitry Andric ScevList.emplace_back(Scev, NeedsFreeze); 919fcaf7f86SDimitry Andric break; 920fcaf7f86SDimitry Andric } 921fcaf7f86SDimitry Andric 922fcaf7f86SDimitry Andric // Find the pointer type we need to extend to. 923fcaf7f86SDimitry Andric Type *IntPtrTy = SE->getEffectiveSCEVType( 924fcaf7f86SDimitry Andric SE->getSCEV(GEP->getPointerOperand())->getType()); 925fcaf7f86SDimitry Andric 926fcaf7f86SDimitry Andric // Find the size of the type being pointed to. We only have a single 927fcaf7f86SDimitry Andric // index term (guarded above) so we don't need to index into arrays or 928fcaf7f86SDimitry Andric // structures, just get the size of the scalar value. 929fcaf7f86SDimitry Andric const SCEV *Size = SE->getSizeOfExpr(IntPtrTy, SourceTy); 930fcaf7f86SDimitry Andric 931fcaf7f86SDimitry Andric // Scale up the offsets by the size of the type, then add to the bases. 932fcaf7f86SDimitry Andric const SCEV *Scaled1 = SE->getMulExpr( 933bdd1243dSDimitry Andric Size, SE->getTruncateOrSignExtend(get<0>(OffsetScevs[0]), IntPtrTy)); 934fcaf7f86SDimitry Andric const SCEV *Scaled2 = SE->getMulExpr( 935bdd1243dSDimitry Andric Size, SE->getTruncateOrSignExtend(get<0>(OffsetScevs[1]), IntPtrTy)); 936bdd1243dSDimitry Andric ScevList.emplace_back(SE->getAddExpr(get<0>(BaseScevs[0]), Scaled1), 937bdd1243dSDimitry Andric NeedsFreeze); 938bdd1243dSDimitry Andric ScevList.emplace_back(SE->getAddExpr(get<0>(BaseScevs[1]), Scaled2), 939bdd1243dSDimitry Andric NeedsFreeze); 940fcaf7f86SDimitry Andric break; 941fcaf7f86SDimitry Andric } 942fcaf7f86SDimitry Andric case Instruction::Select: { 943bdd1243dSDimitry Andric SmallVector<PointerIntPair<const SCEV *, 1, bool>, 2> ChildScevs; 944fcaf7f86SDimitry Andric // A select means we've found a forked pointer, but we currently only 945fcaf7f86SDimitry Andric // support a single select per pointer so if there's another behind this 946fcaf7f86SDimitry Andric // then we just bail out and return the generic SCEV. 947fcaf7f86SDimitry Andric findForkedSCEVs(SE, L, I->getOperand(1), ChildScevs, Depth); 948fcaf7f86SDimitry Andric findForkedSCEVs(SE, L, I->getOperand(2), ChildScevs, Depth); 949fcaf7f86SDimitry Andric if (ChildScevs.size() == 2) { 950fcaf7f86SDimitry Andric ScevList.push_back(ChildScevs[0]); 951fcaf7f86SDimitry Andric ScevList.push_back(ChildScevs[1]); 952fcaf7f86SDimitry Andric } else 953bdd1243dSDimitry Andric ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr)); 954bdd1243dSDimitry Andric break; 955bdd1243dSDimitry Andric } 956c9157d92SDimitry Andric case Instruction::PHI: { 957c9157d92SDimitry Andric SmallVector<PointerIntPair<const SCEV *, 1, bool>, 2> ChildScevs; 958c9157d92SDimitry Andric // A phi means we've found a forked pointer, but we currently only 959c9157d92SDimitry Andric // support a single phi per pointer so if there's another behind this 960c9157d92SDimitry Andric // then we just bail out and return the generic SCEV. 961c9157d92SDimitry Andric if (I->getNumOperands() == 2) { 962c9157d92SDimitry Andric findForkedSCEVs(SE, L, I->getOperand(0), ChildScevs, Depth); 963c9157d92SDimitry Andric findForkedSCEVs(SE, L, I->getOperand(1), ChildScevs, Depth); 964c9157d92SDimitry Andric } 965c9157d92SDimitry Andric if (ChildScevs.size() == 2) { 966c9157d92SDimitry Andric ScevList.push_back(ChildScevs[0]); 967c9157d92SDimitry Andric ScevList.push_back(ChildScevs[1]); 968c9157d92SDimitry Andric } else 969c9157d92SDimitry Andric ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr)); 970c9157d92SDimitry Andric break; 971c9157d92SDimitry Andric } 972bdd1243dSDimitry Andric case Instruction::Add: 973bdd1243dSDimitry Andric case Instruction::Sub: { 974bdd1243dSDimitry Andric SmallVector<PointerIntPair<const SCEV *, 1, bool>> LScevs; 975bdd1243dSDimitry Andric SmallVector<PointerIntPair<const SCEV *, 1, bool>> RScevs; 976bdd1243dSDimitry Andric findForkedSCEVs(SE, L, I->getOperand(0), LScevs, Depth); 977bdd1243dSDimitry Andric findForkedSCEVs(SE, L, I->getOperand(1), RScevs, Depth); 978bdd1243dSDimitry Andric 979bdd1243dSDimitry Andric // See if we need to freeze our fork... 980bdd1243dSDimitry Andric bool NeedsFreeze = 981bdd1243dSDimitry Andric any_of(LScevs, UndefPoisonCheck) || any_of(RScevs, UndefPoisonCheck); 982bdd1243dSDimitry Andric 983bdd1243dSDimitry Andric // Check that we only have a single fork, on either the left or right side. 984bdd1243dSDimitry Andric // Copy the SCEV across for the one without a fork in order to generate 985bdd1243dSDimitry Andric // the full SCEV for both sides of the BinOp. 986bdd1243dSDimitry Andric if (LScevs.size() == 2 && RScevs.size() == 1) 987bdd1243dSDimitry Andric RScevs.push_back(RScevs[0]); 988bdd1243dSDimitry Andric else if (RScevs.size() == 2 && LScevs.size() == 1) 989bdd1243dSDimitry Andric LScevs.push_back(LScevs[0]); 990bdd1243dSDimitry Andric else { 991bdd1243dSDimitry Andric ScevList.emplace_back(Scev, NeedsFreeze); 992bdd1243dSDimitry Andric break; 993bdd1243dSDimitry Andric } 994bdd1243dSDimitry Andric 995bdd1243dSDimitry Andric ScevList.emplace_back( 996bdd1243dSDimitry Andric GetBinOpExpr(Opcode, get<0>(LScevs[0]), get<0>(RScevs[0])), 997bdd1243dSDimitry Andric NeedsFreeze); 998bdd1243dSDimitry Andric ScevList.emplace_back( 999bdd1243dSDimitry Andric GetBinOpExpr(Opcode, get<0>(LScevs[1]), get<0>(RScevs[1])), 1000bdd1243dSDimitry Andric NeedsFreeze); 1001fcaf7f86SDimitry Andric break; 1002fcaf7f86SDimitry Andric } 1003fcaf7f86SDimitry Andric default: 1004fcaf7f86SDimitry Andric // Just return the current SCEV if we haven't handled the instruction yet. 1005fcaf7f86SDimitry Andric LLVM_DEBUG(dbgs() << "ForkedPtr unhandled instruction: " << *I << "\n"); 1006bdd1243dSDimitry Andric ScevList.emplace_back(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr)); 1007fcaf7f86SDimitry Andric break; 1008fcaf7f86SDimitry Andric } 1009fcaf7f86SDimitry Andric } 1010fcaf7f86SDimitry Andric 1011bdd1243dSDimitry Andric static SmallVector<PointerIntPair<const SCEV *, 1, bool>> 1012fcaf7f86SDimitry Andric findForkedPointer(PredicatedScalarEvolution &PSE, 1013fe013be4SDimitry Andric const DenseMap<Value *, const SCEV *> &StridesMap, Value *Ptr, 1014fcaf7f86SDimitry Andric const Loop *L) { 1015fcaf7f86SDimitry Andric ScalarEvolution *SE = PSE.getSE(); 1016fcaf7f86SDimitry Andric assert(SE->isSCEVable(Ptr->getType()) && "Value is not SCEVable!"); 1017bdd1243dSDimitry Andric SmallVector<PointerIntPair<const SCEV *, 1, bool>> Scevs; 1018fcaf7f86SDimitry Andric findForkedSCEVs(SE, L, Ptr, Scevs, MaxForkedSCEVDepth); 1019fcaf7f86SDimitry Andric 1020bdd1243dSDimitry Andric // For now, we will only accept a forked pointer with two possible SCEVs 1021bdd1243dSDimitry Andric // that are either SCEVAddRecExprs or loop invariant. 1022bdd1243dSDimitry Andric if (Scevs.size() == 2 && 1023bdd1243dSDimitry Andric (isa<SCEVAddRecExpr>(get<0>(Scevs[0])) || 1024bdd1243dSDimitry Andric SE->isLoopInvariant(get<0>(Scevs[0]), L)) && 1025bdd1243dSDimitry Andric (isa<SCEVAddRecExpr>(get<0>(Scevs[1])) || 1026bdd1243dSDimitry Andric SE->isLoopInvariant(get<0>(Scevs[1]), L))) { 1027bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Found forked pointer: " << *Ptr << "\n"); 1028bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << "\t(1) " << *get<0>(Scevs[0]) << "\n"); 1029bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << "\t(2) " << *get<0>(Scevs[1]) << "\n"); 1030fcaf7f86SDimitry Andric return Scevs; 1031bdd1243dSDimitry Andric } 1032fcaf7f86SDimitry Andric 1033bdd1243dSDimitry Andric return {{replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr), false}}; 1034fcaf7f86SDimitry Andric } 1035fcaf7f86SDimitry Andric 10360b57cec5SDimitry Andric bool AccessAnalysis::createCheckForAccess(RuntimePointerChecking &RtCheck, 103781ad6265SDimitry Andric MemAccessInfo Access, Type *AccessTy, 1038fe013be4SDimitry Andric const DenseMap<Value *, const SCEV *> &StridesMap, 10390b57cec5SDimitry Andric DenseMap<Value *, unsigned> &DepSetId, 10400b57cec5SDimitry Andric Loop *TheLoop, unsigned &RunningDepId, 10410b57cec5SDimitry Andric unsigned ASId, bool ShouldCheckWrap, 10420b57cec5SDimitry Andric bool Assume) { 10430b57cec5SDimitry Andric Value *Ptr = Access.getPointer(); 10440b57cec5SDimitry Andric 1045bdd1243dSDimitry Andric SmallVector<PointerIntPair<const SCEV *, 1, bool>> TranslatedPtrs = 1046fcaf7f86SDimitry Andric findForkedPointer(PSE, StridesMap, Ptr, TheLoop); 104781ad6265SDimitry Andric 104881ad6265SDimitry Andric for (auto &P : TranslatedPtrs) { 1049bdd1243dSDimitry Andric const SCEV *PtrExpr = get<0>(P); 105081ad6265SDimitry Andric if (!hasComputableBounds(PSE, Ptr, PtrExpr, TheLoop, Assume)) 10510b57cec5SDimitry Andric return false; 10520b57cec5SDimitry Andric 10530b57cec5SDimitry Andric // When we run after a failing dependency check we have to make sure 10540b57cec5SDimitry Andric // we don't have wrapping pointers. 105581ad6265SDimitry Andric if (ShouldCheckWrap) { 105681ad6265SDimitry Andric // Skip wrap checking when translating pointers. 105781ad6265SDimitry Andric if (TranslatedPtrs.size() > 1) 105881ad6265SDimitry Andric return false; 105981ad6265SDimitry Andric 106081ad6265SDimitry Andric if (!isNoWrap(PSE, StridesMap, Ptr, AccessTy, TheLoop)) { 10610b57cec5SDimitry Andric auto *Expr = PSE.getSCEV(Ptr); 10620b57cec5SDimitry Andric if (!Assume || !isa<SCEVAddRecExpr>(Expr)) 10630b57cec5SDimitry Andric return false; 10640b57cec5SDimitry Andric PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW); 10650b57cec5SDimitry Andric } 106681ad6265SDimitry Andric } 106781ad6265SDimitry Andric // If there's only one option for Ptr, look it up after bounds and wrap 106881ad6265SDimitry Andric // checking, because assumptions might have been added to PSE. 106981ad6265SDimitry Andric if (TranslatedPtrs.size() == 1) 1070bdd1243dSDimitry Andric TranslatedPtrs[0] = {replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr), 1071bdd1243dSDimitry Andric false}; 107281ad6265SDimitry Andric } 107381ad6265SDimitry Andric 1074bdd1243dSDimitry Andric for (auto [PtrExpr, NeedsFreeze] : TranslatedPtrs) { 10750b57cec5SDimitry Andric // The id of the dependence set. 10760b57cec5SDimitry Andric unsigned DepId; 10770b57cec5SDimitry Andric 10780b57cec5SDimitry Andric if (isDependencyCheckNeeded()) { 10790b57cec5SDimitry Andric Value *Leader = DepCands.getLeaderValue(Access).getPointer(); 10800b57cec5SDimitry Andric unsigned &LeaderId = DepSetId[Leader]; 10810b57cec5SDimitry Andric if (!LeaderId) 10820b57cec5SDimitry Andric LeaderId = RunningDepId++; 10830b57cec5SDimitry Andric DepId = LeaderId; 10840b57cec5SDimitry Andric } else 10850b57cec5SDimitry Andric // Each access has its own dependence set. 10860b57cec5SDimitry Andric DepId = RunningDepId++; 10870b57cec5SDimitry Andric 10880b57cec5SDimitry Andric bool IsWrite = Access.getInt(); 108981ad6265SDimitry Andric RtCheck.insert(TheLoop, Ptr, PtrExpr, AccessTy, IsWrite, DepId, ASId, PSE, 1090bdd1243dSDimitry Andric NeedsFreeze); 10910b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n'); 109281ad6265SDimitry Andric } 10930b57cec5SDimitry Andric 10940b57cec5SDimitry Andric return true; 10950b57cec5SDimitry Andric } 10960b57cec5SDimitry Andric 10970b57cec5SDimitry Andric bool AccessAnalysis::canCheckPtrAtRT(RuntimePointerChecking &RtCheck, 10980b57cec5SDimitry Andric ScalarEvolution *SE, Loop *TheLoop, 1099fe013be4SDimitry Andric const DenseMap<Value *, const SCEV *> &StridesMap, 110081ad6265SDimitry Andric Value *&UncomputablePtr, bool ShouldCheckWrap) { 11010b57cec5SDimitry Andric // Find pointers with computable bounds. We are going to use this information 11020b57cec5SDimitry Andric // to place a runtime bound check. 11030b57cec5SDimitry Andric bool CanDoRT = true; 11040b57cec5SDimitry Andric 11055ffd83dbSDimitry Andric bool MayNeedRTCheck = false; 11060b57cec5SDimitry Andric if (!IsRTCheckAnalysisNeeded) return true; 11070b57cec5SDimitry Andric 11080b57cec5SDimitry Andric bool IsDepCheckNeeded = isDependencyCheckNeeded(); 11090b57cec5SDimitry Andric 11100b57cec5SDimitry Andric // We assign a consecutive id to access from different alias sets. 11110b57cec5SDimitry Andric // Accesses between different groups doesn't need to be checked. 11125ffd83dbSDimitry Andric unsigned ASId = 0; 11130b57cec5SDimitry Andric for (auto &AS : AST) { 11140b57cec5SDimitry Andric int NumReadPtrChecks = 0; 11150b57cec5SDimitry Andric int NumWritePtrChecks = 0; 11160b57cec5SDimitry Andric bool CanDoAliasSetRT = true; 11175ffd83dbSDimitry Andric ++ASId; 1118*a58f00eaSDimitry Andric auto ASPointers = AS.getPointers(); 11190b57cec5SDimitry Andric 11200b57cec5SDimitry Andric // We assign consecutive id to access from different dependence sets. 11210b57cec5SDimitry Andric // Accesses within the same set don't need a runtime check. 11220b57cec5SDimitry Andric unsigned RunningDepId = 1; 11230b57cec5SDimitry Andric DenseMap<Value *, unsigned> DepSetId; 11240b57cec5SDimitry Andric 1125fcaf7f86SDimitry Andric SmallVector<std::pair<MemAccessInfo, Type *>, 4> Retries; 11260b57cec5SDimitry Andric 11271106035dSDimitry Andric // First, count how many write and read accesses are in the alias set. Also 11281106035dSDimitry Andric // collect MemAccessInfos for later. 11291106035dSDimitry Andric SmallVector<MemAccessInfo, 4> AccessInfos; 1130*a58f00eaSDimitry Andric for (const Value *Ptr_ : ASPointers) { 1131*a58f00eaSDimitry Andric Value *Ptr = const_cast<Value *>(Ptr_); 11320b57cec5SDimitry Andric bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true)); 11330b57cec5SDimitry Andric if (IsWrite) 11340b57cec5SDimitry Andric ++NumWritePtrChecks; 11350b57cec5SDimitry Andric else 11360b57cec5SDimitry Andric ++NumReadPtrChecks; 11371106035dSDimitry Andric AccessInfos.emplace_back(Ptr, IsWrite); 11380b57cec5SDimitry Andric } 11390b57cec5SDimitry Andric 11401106035dSDimitry Andric // We do not need runtime checks for this alias set, if there are no writes 11411106035dSDimitry Andric // or a single write and no reads. 11421106035dSDimitry Andric if (NumWritePtrChecks == 0 || 11431106035dSDimitry Andric (NumWritePtrChecks == 1 && NumReadPtrChecks == 0)) { 1144*a58f00eaSDimitry Andric assert((ASPointers.size() <= 1 || 1145*a58f00eaSDimitry Andric all_of(ASPointers, 1146*a58f00eaSDimitry Andric [this](const Value *Ptr) { 1147*a58f00eaSDimitry Andric MemAccessInfo AccessWrite(const_cast<Value *>(Ptr), 1148*a58f00eaSDimitry Andric true); 11491106035dSDimitry Andric return DepCands.findValue(AccessWrite) == DepCands.end(); 11505ffd83dbSDimitry Andric })) && 11515ffd83dbSDimitry Andric "Can only skip updating CanDoRT below, if all entries in AS " 11525ffd83dbSDimitry Andric "are reads or there is at most 1 entry"); 11535ffd83dbSDimitry Andric continue; 11545ffd83dbSDimitry Andric } 11551106035dSDimitry Andric 11561106035dSDimitry Andric for (auto &Access : AccessInfos) { 1157fcaf7f86SDimitry Andric for (const auto &AccessTy : Accesses[Access]) { 115881ad6265SDimitry Andric if (!createCheckForAccess(RtCheck, Access, AccessTy, StridesMap, 115981ad6265SDimitry Andric DepSetId, TheLoop, RunningDepId, ASId, 116081ad6265SDimitry Andric ShouldCheckWrap, false)) { 11611106035dSDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Can't find bounds for ptr:" 11621106035dSDimitry Andric << *Access.getPointer() << '\n'); 1163fcaf7f86SDimitry Andric Retries.push_back({Access, AccessTy}); 11641106035dSDimitry Andric CanDoAliasSetRT = false; 11655ffd83dbSDimitry Andric } 11661106035dSDimitry Andric } 116781ad6265SDimitry Andric } 11681106035dSDimitry Andric 11691106035dSDimitry Andric // Note that this function computes CanDoRT and MayNeedRTCheck 11701106035dSDimitry Andric // independently. For example CanDoRT=false, MayNeedRTCheck=false means that 11711106035dSDimitry Andric // we have a pointer for which we couldn't find the bounds but we don't 11721106035dSDimitry Andric // actually need to emit any checks so it does not matter. 11731106035dSDimitry Andric // 11741106035dSDimitry Andric // We need runtime checks for this alias set, if there are at least 2 11751106035dSDimitry Andric // dependence sets (in which case RunningDepId > 2) or if we need to re-try 11761106035dSDimitry Andric // any bound checks (because in that case the number of dependence sets is 11771106035dSDimitry Andric // incomplete). 11781106035dSDimitry Andric bool NeedsAliasSetRTCheck = RunningDepId > 2 || !Retries.empty(); 11790b57cec5SDimitry Andric 11800b57cec5SDimitry Andric // We need to perform run-time alias checks, but some pointers had bounds 11810b57cec5SDimitry Andric // that couldn't be checked. 11820b57cec5SDimitry Andric if (NeedsAliasSetRTCheck && !CanDoAliasSetRT) { 11830b57cec5SDimitry Andric // Reset the CanDoSetRt flag and retry all accesses that have failed. 11840b57cec5SDimitry Andric // We know that we need these checks, so we can now be more aggressive 11850b57cec5SDimitry Andric // and add further checks if required (overflow checks). 11860b57cec5SDimitry Andric CanDoAliasSetRT = true; 1187fcaf7f86SDimitry Andric for (auto Retry : Retries) { 1188fcaf7f86SDimitry Andric MemAccessInfo Access = Retry.first; 1189fcaf7f86SDimitry Andric Type *AccessTy = Retry.second; 119081ad6265SDimitry Andric if (!createCheckForAccess(RtCheck, Access, AccessTy, StridesMap, 119181ad6265SDimitry Andric DepSetId, TheLoop, RunningDepId, ASId, 11920b57cec5SDimitry Andric ShouldCheckWrap, /*Assume=*/true)) { 11930b57cec5SDimitry Andric CanDoAliasSetRT = false; 119481ad6265SDimitry Andric UncomputablePtr = Access.getPointer(); 11950b57cec5SDimitry Andric break; 11960b57cec5SDimitry Andric } 11970b57cec5SDimitry Andric } 119881ad6265SDimitry Andric } 11990b57cec5SDimitry Andric 12000b57cec5SDimitry Andric CanDoRT &= CanDoAliasSetRT; 12015ffd83dbSDimitry Andric MayNeedRTCheck |= NeedsAliasSetRTCheck; 12020b57cec5SDimitry Andric ++ASId; 12030b57cec5SDimitry Andric } 12040b57cec5SDimitry Andric 12050b57cec5SDimitry Andric // If the pointers that we would use for the bounds comparison have different 12060b57cec5SDimitry Andric // address spaces, assume the values aren't directly comparable, so we can't 12070b57cec5SDimitry Andric // use them for the runtime check. We also have to assume they could 12080b57cec5SDimitry Andric // overlap. In the future there should be metadata for whether address spaces 12090b57cec5SDimitry Andric // are disjoint. 12100b57cec5SDimitry Andric unsigned NumPointers = RtCheck.Pointers.size(); 12110b57cec5SDimitry Andric for (unsigned i = 0; i < NumPointers; ++i) { 12120b57cec5SDimitry Andric for (unsigned j = i + 1; j < NumPointers; ++j) { 12130b57cec5SDimitry Andric // Only need to check pointers between two different dependency sets. 12140b57cec5SDimitry Andric if (RtCheck.Pointers[i].DependencySetId == 12150b57cec5SDimitry Andric RtCheck.Pointers[j].DependencySetId) 12160b57cec5SDimitry Andric continue; 12170b57cec5SDimitry Andric // Only need to check pointers in the same alias set. 12180b57cec5SDimitry Andric if (RtCheck.Pointers[i].AliasSetId != RtCheck.Pointers[j].AliasSetId) 12190b57cec5SDimitry Andric continue; 12200b57cec5SDimitry Andric 12210b57cec5SDimitry Andric Value *PtrI = RtCheck.Pointers[i].PointerValue; 12220b57cec5SDimitry Andric Value *PtrJ = RtCheck.Pointers[j].PointerValue; 12230b57cec5SDimitry Andric 12240b57cec5SDimitry Andric unsigned ASi = PtrI->getType()->getPointerAddressSpace(); 12250b57cec5SDimitry Andric unsigned ASj = PtrJ->getType()->getPointerAddressSpace(); 12260b57cec5SDimitry Andric if (ASi != ASj) { 12270b57cec5SDimitry Andric LLVM_DEBUG( 12280b57cec5SDimitry Andric dbgs() << "LAA: Runtime check would require comparison between" 12290b57cec5SDimitry Andric " different address spaces\n"); 12300b57cec5SDimitry Andric return false; 12310b57cec5SDimitry Andric } 12320b57cec5SDimitry Andric } 12330b57cec5SDimitry Andric } 12340b57cec5SDimitry Andric 12355ffd83dbSDimitry Andric if (MayNeedRTCheck && CanDoRT) 12360b57cec5SDimitry Andric RtCheck.generateChecks(DepCands, IsDepCheckNeeded); 12370b57cec5SDimitry Andric 12380b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: We need to do " << RtCheck.getNumberOfChecks() 12390b57cec5SDimitry Andric << " pointer comparisons.\n"); 12400b57cec5SDimitry Andric 12415ffd83dbSDimitry Andric // If we can do run-time checks, but there are no checks, no runtime checks 12425ffd83dbSDimitry Andric // are needed. This can happen when all pointers point to the same underlying 12435ffd83dbSDimitry Andric // object for example. 12445ffd83dbSDimitry Andric RtCheck.Need = CanDoRT ? RtCheck.getNumberOfChecks() != 0 : MayNeedRTCheck; 12450b57cec5SDimitry Andric 12465ffd83dbSDimitry Andric bool CanDoRTIfNeeded = !RtCheck.Need || CanDoRT; 12470b57cec5SDimitry Andric if (!CanDoRTIfNeeded) 12480b57cec5SDimitry Andric RtCheck.reset(); 12490b57cec5SDimitry Andric return CanDoRTIfNeeded; 12500b57cec5SDimitry Andric } 12510b57cec5SDimitry Andric 12520b57cec5SDimitry Andric void AccessAnalysis::processMemAccesses() { 12530b57cec5SDimitry Andric // We process the set twice: first we process read-write pointers, last we 12540b57cec5SDimitry Andric // process read-only pointers. This allows us to skip dependence tests for 12550b57cec5SDimitry Andric // read-only pointers. 12560b57cec5SDimitry Andric 12570b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Processing memory accesses...\n"); 12580b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " AST: "; AST.dump()); 12590b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Accesses(" << Accesses.size() << "):\n"); 12600b57cec5SDimitry Andric LLVM_DEBUG({ 12610b57cec5SDimitry Andric for (auto A : Accesses) 126281ad6265SDimitry Andric dbgs() << "\t" << *A.first.getPointer() << " (" 126381ad6265SDimitry Andric << (A.first.getInt() 126481ad6265SDimitry Andric ? "write" 126581ad6265SDimitry Andric : (ReadOnlyPtr.count(A.first.getPointer()) ? "read-only" 126681ad6265SDimitry Andric : "read")) 126781ad6265SDimitry Andric << ")\n"; 12680b57cec5SDimitry Andric }); 12690b57cec5SDimitry Andric 12700b57cec5SDimitry Andric // The AliasSetTracker has nicely partitioned our pointers by metadata 12710b57cec5SDimitry Andric // compatibility and potential for underlying-object overlap. As a result, we 12720b57cec5SDimitry Andric // only need to check for potential pointer dependencies within each alias 12730b57cec5SDimitry Andric // set. 1274e8d8bef9SDimitry Andric for (const auto &AS : AST) { 12750b57cec5SDimitry Andric // Note that both the alias-set tracker and the alias sets themselves used 1276*a58f00eaSDimitry Andric // ordered collections internally and so the iteration order here is 1277*a58f00eaSDimitry Andric // deterministic. 1278*a58f00eaSDimitry Andric auto ASPointers = AS.getPointers(); 12790b57cec5SDimitry Andric 12800b57cec5SDimitry Andric bool SetHasWrite = false; 12810b57cec5SDimitry Andric 12820b57cec5SDimitry Andric // Map of pointers to last access encountered. 12830b57cec5SDimitry Andric typedef DenseMap<const Value*, MemAccessInfo> UnderlyingObjToAccessMap; 12840b57cec5SDimitry Andric UnderlyingObjToAccessMap ObjToLastAccess; 12850b57cec5SDimitry Andric 12860b57cec5SDimitry Andric // Set of access to check after all writes have been processed. 128781ad6265SDimitry Andric PtrAccessMap DeferredAccesses; 12880b57cec5SDimitry Andric 12890b57cec5SDimitry Andric // Iterate over each alias set twice, once to process read/write pointers, 12900b57cec5SDimitry Andric // and then to process read-only pointers. 12910b57cec5SDimitry Andric for (int SetIteration = 0; SetIteration < 2; ++SetIteration) { 12920b57cec5SDimitry Andric bool UseDeferred = SetIteration > 0; 129381ad6265SDimitry Andric PtrAccessMap &S = UseDeferred ? DeferredAccesses : Accesses; 12940b57cec5SDimitry Andric 1295*a58f00eaSDimitry Andric for (const Value *Ptr_ : ASPointers) { 1296*a58f00eaSDimitry Andric Value *Ptr = const_cast<Value *>(Ptr_); 12970b57cec5SDimitry Andric 12980b57cec5SDimitry Andric // For a single memory access in AliasSetTracker, Accesses may contain 12990b57cec5SDimitry Andric // both read and write, and they both need to be handled for CheckDeps. 1300e8d8bef9SDimitry Andric for (const auto &AC : S) { 130181ad6265SDimitry Andric if (AC.first.getPointer() != Ptr) 13020b57cec5SDimitry Andric continue; 13030b57cec5SDimitry Andric 130481ad6265SDimitry Andric bool IsWrite = AC.first.getInt(); 13050b57cec5SDimitry Andric 13060b57cec5SDimitry Andric // If we're using the deferred access set, then it contains only 13070b57cec5SDimitry Andric // reads. 13080b57cec5SDimitry Andric bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite; 13090b57cec5SDimitry Andric if (UseDeferred && !IsReadOnlyPtr) 13100b57cec5SDimitry Andric continue; 13110b57cec5SDimitry Andric // Otherwise, the pointer must be in the PtrAccessSet, either as a 13120b57cec5SDimitry Andric // read or a write. 13130b57cec5SDimitry Andric assert(((IsReadOnlyPtr && UseDeferred) || IsWrite || 13140b57cec5SDimitry Andric S.count(MemAccessInfo(Ptr, false))) && 13150b57cec5SDimitry Andric "Alias-set pointer not in the access set?"); 13160b57cec5SDimitry Andric 13170b57cec5SDimitry Andric MemAccessInfo Access(Ptr, IsWrite); 13180b57cec5SDimitry Andric DepCands.insert(Access); 13190b57cec5SDimitry Andric 13200b57cec5SDimitry Andric // Memorize read-only pointers for later processing and skip them in 13210b57cec5SDimitry Andric // the first round (they need to be checked after we have seen all 13220b57cec5SDimitry Andric // write pointers). Note: we also mark pointer that are not 13230b57cec5SDimitry Andric // consecutive as "read-only" pointers (so that we check 13240b57cec5SDimitry Andric // "a[b[i]] +="). Hence, we need the second check for "!IsWrite". 13250b57cec5SDimitry Andric if (!UseDeferred && IsReadOnlyPtr) { 132681ad6265SDimitry Andric // We only use the pointer keys, the types vector values don't 132781ad6265SDimitry Andric // matter. 132881ad6265SDimitry Andric DeferredAccesses.insert({Access, {}}); 13290b57cec5SDimitry Andric continue; 13300b57cec5SDimitry Andric } 13310b57cec5SDimitry Andric 13320b57cec5SDimitry Andric // If this is a write - check other reads and writes for conflicts. If 13330b57cec5SDimitry Andric // this is a read only check other writes for conflicts (but only if 13340b57cec5SDimitry Andric // there is no other write to the ptr - this is an optimization to 13350b57cec5SDimitry Andric // catch "a[i] = a[i] + " without having to do a dependence check). 13360b57cec5SDimitry Andric if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) { 13370b57cec5SDimitry Andric CheckDeps.push_back(Access); 13380b57cec5SDimitry Andric IsRTCheckAnalysisNeeded = true; 13390b57cec5SDimitry Andric } 13400b57cec5SDimitry Andric 13410b57cec5SDimitry Andric if (IsWrite) 13420b57cec5SDimitry Andric SetHasWrite = true; 13430b57cec5SDimitry Andric 13440b57cec5SDimitry Andric // Create sets of pointers connected by a shared alias set and 13450b57cec5SDimitry Andric // underlying object. 13460b57cec5SDimitry Andric typedef SmallVector<const Value *, 16> ValueVector; 13470b57cec5SDimitry Andric ValueVector TempObjects; 13480b57cec5SDimitry Andric 1349c9157d92SDimitry Andric UnderlyingObjects[Ptr] = {}; 1350c9157d92SDimitry Andric SmallVector<const Value *, 16> &UOs = UnderlyingObjects[Ptr]; 1351c9157d92SDimitry Andric ::getUnderlyingObjects(Ptr, UOs, LI); 13520b57cec5SDimitry Andric LLVM_DEBUG(dbgs() 13530b57cec5SDimitry Andric << "Underlying objects for pointer " << *Ptr << "\n"); 1354c9157d92SDimitry Andric for (const Value *UnderlyingObj : UOs) { 13550b57cec5SDimitry Andric // nullptr never alias, don't join sets for pointer that have "null" 13560b57cec5SDimitry Andric // in their UnderlyingObjects list. 13570b57cec5SDimitry Andric if (isa<ConstantPointerNull>(UnderlyingObj) && 13580b57cec5SDimitry Andric !NullPointerIsDefined( 13590b57cec5SDimitry Andric TheLoop->getHeader()->getParent(), 13600b57cec5SDimitry Andric UnderlyingObj->getType()->getPointerAddressSpace())) 13610b57cec5SDimitry Andric continue; 13620b57cec5SDimitry Andric 13630b57cec5SDimitry Andric UnderlyingObjToAccessMap::iterator Prev = 13640b57cec5SDimitry Andric ObjToLastAccess.find(UnderlyingObj); 13650b57cec5SDimitry Andric if (Prev != ObjToLastAccess.end()) 13660b57cec5SDimitry Andric DepCands.unionSets(Access, Prev->second); 13670b57cec5SDimitry Andric 13680b57cec5SDimitry Andric ObjToLastAccess[UnderlyingObj] = Access; 13690b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " " << *UnderlyingObj << "\n"); 13700b57cec5SDimitry Andric } 13710b57cec5SDimitry Andric } 13720b57cec5SDimitry Andric } 13730b57cec5SDimitry Andric } 13740b57cec5SDimitry Andric } 13750b57cec5SDimitry Andric } 13760b57cec5SDimitry Andric 13770b57cec5SDimitry Andric /// Return true if an AddRec pointer \p Ptr is unsigned non-wrapping, 13780b57cec5SDimitry Andric /// i.e. monotonically increasing/decreasing. 13790b57cec5SDimitry Andric static bool isNoWrapAddRec(Value *Ptr, const SCEVAddRecExpr *AR, 13800b57cec5SDimitry Andric PredicatedScalarEvolution &PSE, const Loop *L) { 1381fe013be4SDimitry Andric 13820b57cec5SDimitry Andric // FIXME: This should probably only return true for NUW. 13830b57cec5SDimitry Andric if (AR->getNoWrapFlags(SCEV::NoWrapMask)) 13840b57cec5SDimitry Andric return true; 13850b57cec5SDimitry Andric 1386fe013be4SDimitry Andric if (PSE.hasNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW)) 1387fe013be4SDimitry Andric return true; 1388fe013be4SDimitry Andric 13890b57cec5SDimitry Andric // Scalar evolution does not propagate the non-wrapping flags to values that 13900b57cec5SDimitry Andric // are derived from a non-wrapping induction variable because non-wrapping 13910b57cec5SDimitry Andric // could be flow-sensitive. 13920b57cec5SDimitry Andric // 13930b57cec5SDimitry Andric // Look through the potentially overflowing instruction to try to prove 13940b57cec5SDimitry Andric // non-wrapping for the *specific* value of Ptr. 13950b57cec5SDimitry Andric 13960b57cec5SDimitry Andric // The arithmetic implied by an inbounds GEP can't overflow. 13970b57cec5SDimitry Andric auto *GEP = dyn_cast<GetElementPtrInst>(Ptr); 13980b57cec5SDimitry Andric if (!GEP || !GEP->isInBounds()) 13990b57cec5SDimitry Andric return false; 14000b57cec5SDimitry Andric 14010b57cec5SDimitry Andric // Make sure there is only one non-const index and analyze that. 14020b57cec5SDimitry Andric Value *NonConstIndex = nullptr; 1403e8d8bef9SDimitry Andric for (Value *Index : GEP->indices()) 14040b57cec5SDimitry Andric if (!isa<ConstantInt>(Index)) { 14050b57cec5SDimitry Andric if (NonConstIndex) 14060b57cec5SDimitry Andric return false; 14070b57cec5SDimitry Andric NonConstIndex = Index; 14080b57cec5SDimitry Andric } 14090b57cec5SDimitry Andric if (!NonConstIndex) 14100b57cec5SDimitry Andric // The recurrence is on the pointer, ignore for now. 14110b57cec5SDimitry Andric return false; 14120b57cec5SDimitry Andric 14130b57cec5SDimitry Andric // The index in GEP is signed. It is non-wrapping if it's derived from a NSW 14140b57cec5SDimitry Andric // AddRec using a NSW operation. 14150b57cec5SDimitry Andric if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(NonConstIndex)) 14160b57cec5SDimitry Andric if (OBO->hasNoSignedWrap() && 14170b57cec5SDimitry Andric // Assume constant for other the operand so that the AddRec can be 14180b57cec5SDimitry Andric // easily found. 14190b57cec5SDimitry Andric isa<ConstantInt>(OBO->getOperand(1))) { 14200b57cec5SDimitry Andric auto *OpScev = PSE.getSCEV(OBO->getOperand(0)); 14210b57cec5SDimitry Andric 14220b57cec5SDimitry Andric if (auto *OpAR = dyn_cast<SCEVAddRecExpr>(OpScev)) 14230b57cec5SDimitry Andric return OpAR->getLoop() == L && OpAR->getNoWrapFlags(SCEV::FlagNSW); 14240b57cec5SDimitry Andric } 14250b57cec5SDimitry Andric 14260b57cec5SDimitry Andric return false; 14270b57cec5SDimitry Andric } 14280b57cec5SDimitry Andric 14290b57cec5SDimitry Andric /// Check whether the access through \p Ptr has a constant stride. 1430bdd1243dSDimitry Andric std::optional<int64_t> llvm::getPtrStride(PredicatedScalarEvolution &PSE, 1431bdd1243dSDimitry Andric Type *AccessTy, Value *Ptr, 1432bdd1243dSDimitry Andric const Loop *Lp, 1433fe013be4SDimitry Andric const DenseMap<Value *, const SCEV *> &StridesMap, 1434bdd1243dSDimitry Andric bool Assume, bool ShouldCheckWrap) { 14350b57cec5SDimitry Andric Type *Ty = Ptr->getType(); 14360b57cec5SDimitry Andric assert(Ty->isPointerTy() && "Unexpected non-ptr"); 14370b57cec5SDimitry Andric 14384824e7fdSDimitry Andric if (isa<ScalableVectorType>(AccessTy)) { 14394824e7fdSDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Bad stride - Scalable object: " << *AccessTy 14404824e7fdSDimitry Andric << "\n"); 1441bdd1243dSDimitry Andric return std::nullopt; 14420b57cec5SDimitry Andric } 14430b57cec5SDimitry Andric 14440b57cec5SDimitry Andric const SCEV *PtrScev = replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr); 14450b57cec5SDimitry Andric 14460b57cec5SDimitry Andric const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev); 14470b57cec5SDimitry Andric if (Assume && !AR) 14480b57cec5SDimitry Andric AR = PSE.getAsAddRec(Ptr); 14490b57cec5SDimitry Andric 14500b57cec5SDimitry Andric if (!AR) { 14510b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer " << *Ptr 14520b57cec5SDimitry Andric << " SCEV: " << *PtrScev << "\n"); 1453bdd1243dSDimitry Andric return std::nullopt; 14540b57cec5SDimitry Andric } 14550b57cec5SDimitry Andric 14560b57cec5SDimitry Andric // The access function must stride over the innermost loop. 14570b57cec5SDimitry Andric if (Lp != AR->getLoop()) { 14580b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " 14590b57cec5SDimitry Andric << *Ptr << " SCEV: " << *AR << "\n"); 1460bdd1243dSDimitry Andric return std::nullopt; 14610b57cec5SDimitry Andric } 14620b57cec5SDimitry Andric 14630b57cec5SDimitry Andric // Check the step is constant. 14640b57cec5SDimitry Andric const SCEV *Step = AR->getStepRecurrence(*PSE.getSE()); 14650b57cec5SDimitry Andric 14660b57cec5SDimitry Andric // Calculate the pointer stride and check if it is constant. 14670b57cec5SDimitry Andric const SCEVConstant *C = dyn_cast<SCEVConstant>(Step); 14680b57cec5SDimitry Andric if (!C) { 14690b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr 14700b57cec5SDimitry Andric << " SCEV: " << *AR << "\n"); 1471bdd1243dSDimitry Andric return std::nullopt; 14720b57cec5SDimitry Andric } 14730b57cec5SDimitry Andric 14740b57cec5SDimitry Andric auto &DL = Lp->getHeader()->getModule()->getDataLayout(); 14754824e7fdSDimitry Andric TypeSize AllocSize = DL.getTypeAllocSize(AccessTy); 1476bdd1243dSDimitry Andric int64_t Size = AllocSize.getFixedValue(); 14770b57cec5SDimitry Andric const APInt &APStepVal = C->getAPInt(); 14780b57cec5SDimitry Andric 14790b57cec5SDimitry Andric // Huge step value - give up. 14800b57cec5SDimitry Andric if (APStepVal.getBitWidth() > 64) 1481bdd1243dSDimitry Andric return std::nullopt; 14820b57cec5SDimitry Andric 14830b57cec5SDimitry Andric int64_t StepVal = APStepVal.getSExtValue(); 14840b57cec5SDimitry Andric 14850b57cec5SDimitry Andric // Strided access. 14860b57cec5SDimitry Andric int64_t Stride = StepVal / Size; 14870b57cec5SDimitry Andric int64_t Rem = StepVal % Size; 14880b57cec5SDimitry Andric if (Rem) 1489bdd1243dSDimitry Andric return std::nullopt; 14900b57cec5SDimitry Andric 1491fe013be4SDimitry Andric if (!ShouldCheckWrap) 1492fe013be4SDimitry Andric return Stride; 1493fe013be4SDimitry Andric 1494fe013be4SDimitry Andric // The address calculation must not wrap. Otherwise, a dependence could be 1495fe013be4SDimitry Andric // inverted. 1496fe013be4SDimitry Andric if (isNoWrapAddRec(Ptr, AR, PSE, Lp)) 1497fe013be4SDimitry Andric return Stride; 1498fe013be4SDimitry Andric 1499fe013be4SDimitry Andric // An inbounds getelementptr that is a AddRec with a unit stride 1500fe013be4SDimitry Andric // cannot wrap per definition. If it did, the result would be poison 1501fe013be4SDimitry Andric // and any memory access dependent on it would be immediate UB 1502fe013be4SDimitry Andric // when executed. 1503fe013be4SDimitry Andric if (auto *GEP = dyn_cast<GetElementPtrInst>(Ptr); 1504fe013be4SDimitry Andric GEP && GEP->isInBounds() && (Stride == 1 || Stride == -1)) 1505fe013be4SDimitry Andric return Stride; 1506fe013be4SDimitry Andric 1507fe013be4SDimitry Andric // If the null pointer is undefined, then a access sequence which would 1508fe013be4SDimitry Andric // otherwise access it can be assumed not to unsigned wrap. Note that this 1509fe013be4SDimitry Andric // assumes the object in memory is aligned to the natural alignment. 1510fe013be4SDimitry Andric unsigned AddrSpace = Ty->getPointerAddressSpace(); 1511fe013be4SDimitry Andric if (!NullPointerIsDefined(Lp->getHeader()->getParent(), AddrSpace) && 1512fe013be4SDimitry Andric (Stride == 1 || Stride == -1)) 1513fe013be4SDimitry Andric return Stride; 1514fe013be4SDimitry Andric 15150b57cec5SDimitry Andric if (Assume) { 1516fe013be4SDimitry Andric PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW); 1517fe013be4SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Pointer may wrap:\n" 15180b57cec5SDimitry Andric << "LAA: Pointer: " << *Ptr << "\n" 15190b57cec5SDimitry Andric << "LAA: SCEV: " << *AR << "\n" 15200b57cec5SDimitry Andric << "LAA: Added an overflow assumption\n"); 15210b57cec5SDimitry Andric return Stride; 15220b57cec5SDimitry Andric } 1523fe013be4SDimitry Andric LLVM_DEBUG( 1524fe013be4SDimitry Andric dbgs() << "LAA: Bad stride - Pointer may wrap in the address space " 1525fe013be4SDimitry Andric << *Ptr << " SCEV: " << *AR << "\n"); 1526fe013be4SDimitry Andric return std::nullopt; 1527fe013be4SDimitry Andric } 15280b57cec5SDimitry Andric 1529bdd1243dSDimitry Andric std::optional<int> llvm::getPointersDiff(Type *ElemTyA, Value *PtrA, 1530bdd1243dSDimitry Andric Type *ElemTyB, Value *PtrB, 1531bdd1243dSDimitry Andric const DataLayout &DL, 1532fe6060f1SDimitry Andric ScalarEvolution &SE, bool StrictCheck, 1533fe6060f1SDimitry Andric bool CheckType) { 1534fe6060f1SDimitry Andric assert(PtrA && PtrB && "Expected non-nullptr pointers."); 1535fe6060f1SDimitry Andric 1536fe6060f1SDimitry Andric // Make sure that A and B are different pointers. 1537fe6060f1SDimitry Andric if (PtrA == PtrB) 1538fe6060f1SDimitry Andric return 0; 1539fe6060f1SDimitry Andric 1540fe6060f1SDimitry Andric // Make sure that the element types are the same if required. 1541fe6060f1SDimitry Andric if (CheckType && ElemTyA != ElemTyB) 1542bdd1243dSDimitry Andric return std::nullopt; 1543fe6060f1SDimitry Andric 1544fe6060f1SDimitry Andric unsigned ASA = PtrA->getType()->getPointerAddressSpace(); 1545fe6060f1SDimitry Andric unsigned ASB = PtrB->getType()->getPointerAddressSpace(); 1546fe6060f1SDimitry Andric 1547fe6060f1SDimitry Andric // Check that the address spaces match. 1548fe6060f1SDimitry Andric if (ASA != ASB) 1549bdd1243dSDimitry Andric return std::nullopt; 1550fe6060f1SDimitry Andric unsigned IdxWidth = DL.getIndexSizeInBits(ASA); 1551fe6060f1SDimitry Andric 1552fe6060f1SDimitry Andric APInt OffsetA(IdxWidth, 0), OffsetB(IdxWidth, 0); 1553fe6060f1SDimitry Andric Value *PtrA1 = PtrA->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetA); 1554fe6060f1SDimitry Andric Value *PtrB1 = PtrB->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetB); 1555fe6060f1SDimitry Andric 1556fe6060f1SDimitry Andric int Val; 1557fe6060f1SDimitry Andric if (PtrA1 == PtrB1) { 1558fe6060f1SDimitry Andric // Retrieve the address space again as pointer stripping now tracks through 1559fe6060f1SDimitry Andric // `addrspacecast`. 1560fe6060f1SDimitry Andric ASA = cast<PointerType>(PtrA1->getType())->getAddressSpace(); 1561fe6060f1SDimitry Andric ASB = cast<PointerType>(PtrB1->getType())->getAddressSpace(); 1562fe6060f1SDimitry Andric // Check that the address spaces match and that the pointers are valid. 1563fe6060f1SDimitry Andric if (ASA != ASB) 1564bdd1243dSDimitry Andric return std::nullopt; 1565fe6060f1SDimitry Andric 1566fe6060f1SDimitry Andric IdxWidth = DL.getIndexSizeInBits(ASA); 1567fe6060f1SDimitry Andric OffsetA = OffsetA.sextOrTrunc(IdxWidth); 1568fe6060f1SDimitry Andric OffsetB = OffsetB.sextOrTrunc(IdxWidth); 1569fe6060f1SDimitry Andric 1570fe6060f1SDimitry Andric OffsetB -= OffsetA; 1571fe6060f1SDimitry Andric Val = OffsetB.getSExtValue(); 1572fe6060f1SDimitry Andric } else { 1573fe6060f1SDimitry Andric // Otherwise compute the distance with SCEV between the base pointers. 1574fe6060f1SDimitry Andric const SCEV *PtrSCEVA = SE.getSCEV(PtrA); 1575fe6060f1SDimitry Andric const SCEV *PtrSCEVB = SE.getSCEV(PtrB); 1576fe6060f1SDimitry Andric const auto *Diff = 1577fe6060f1SDimitry Andric dyn_cast<SCEVConstant>(SE.getMinusSCEV(PtrSCEVB, PtrSCEVA)); 1578fe6060f1SDimitry Andric if (!Diff) 1579bdd1243dSDimitry Andric return std::nullopt; 1580fe6060f1SDimitry Andric Val = Diff->getAPInt().getSExtValue(); 1581fe6060f1SDimitry Andric } 1582fe6060f1SDimitry Andric int Size = DL.getTypeStoreSize(ElemTyA); 1583fe6060f1SDimitry Andric int Dist = Val / Size; 1584fe6060f1SDimitry Andric 1585fe6060f1SDimitry Andric // Ensure that the calculated distance matches the type-based one after all 1586fe6060f1SDimitry Andric // the bitcasts removal in the provided pointers. 1587fe6060f1SDimitry Andric if (!StrictCheck || Dist * Size == Val) 1588fe6060f1SDimitry Andric return Dist; 1589bdd1243dSDimitry Andric return std::nullopt; 1590fe6060f1SDimitry Andric } 1591fe6060f1SDimitry Andric 1592fe6060f1SDimitry Andric bool llvm::sortPtrAccesses(ArrayRef<Value *> VL, Type *ElemTy, 1593fe6060f1SDimitry Andric const DataLayout &DL, ScalarEvolution &SE, 15940b57cec5SDimitry Andric SmallVectorImpl<unsigned> &SortedIndices) { 15950b57cec5SDimitry Andric assert(llvm::all_of( 15960b57cec5SDimitry Andric VL, [](const Value *V) { return V->getType()->isPointerTy(); }) && 15970b57cec5SDimitry Andric "Expected list of pointer operands."); 15980b57cec5SDimitry Andric // Walk over the pointers, and map each of them to an offset relative to 15990b57cec5SDimitry Andric // first pointer in the array. 16000b57cec5SDimitry Andric Value *Ptr0 = VL[0]; 16010b57cec5SDimitry Andric 1602fe6060f1SDimitry Andric using DistOrdPair = std::pair<int64_t, int>; 1603972a253aSDimitry Andric auto Compare = llvm::less_first(); 1604fe6060f1SDimitry Andric std::set<DistOrdPair, decltype(Compare)> Offsets(Compare); 1605fe6060f1SDimitry Andric Offsets.emplace(0, 0); 1606fe6060f1SDimitry Andric int Cnt = 1; 1607fe6060f1SDimitry Andric bool IsConsecutive = true; 1608fe6060f1SDimitry Andric for (auto *Ptr : VL.drop_front()) { 1609bdd1243dSDimitry Andric std::optional<int> Diff = getPointersDiff(ElemTy, Ptr0, ElemTy, Ptr, DL, SE, 1610fe6060f1SDimitry Andric /*StrictCheck=*/true); 16110b57cec5SDimitry Andric if (!Diff) 16120b57cec5SDimitry Andric return false; 16130b57cec5SDimitry Andric 16140b57cec5SDimitry Andric // Check if the pointer with the same offset is found. 1615fe6060f1SDimitry Andric int64_t Offset = *Diff; 1616fe6060f1SDimitry Andric auto Res = Offsets.emplace(Offset, Cnt); 1617fe6060f1SDimitry Andric if (!Res.second) 16180b57cec5SDimitry Andric return false; 1619fe6060f1SDimitry Andric // Consecutive order if the inserted element is the last one. 1620fe6060f1SDimitry Andric IsConsecutive = IsConsecutive && std::next(Res.first) == Offsets.end(); 1621fe6060f1SDimitry Andric ++Cnt; 16220b57cec5SDimitry Andric } 16230b57cec5SDimitry Andric SortedIndices.clear(); 1624fe6060f1SDimitry Andric if (!IsConsecutive) { 1625fe6060f1SDimitry Andric // Fill SortedIndices array only if it is non-consecutive. 16260b57cec5SDimitry Andric SortedIndices.resize(VL.size()); 1627fe6060f1SDimitry Andric Cnt = 0; 1628fe6060f1SDimitry Andric for (const std::pair<int64_t, int> &Pair : Offsets) { 1629fe6060f1SDimitry Andric SortedIndices[Cnt] = Pair.second; 1630fe6060f1SDimitry Andric ++Cnt; 16310b57cec5SDimitry Andric } 1632fe6060f1SDimitry Andric } 1633fe6060f1SDimitry Andric return true; 16340b57cec5SDimitry Andric } 16350b57cec5SDimitry Andric 16360b57cec5SDimitry Andric /// Returns true if the memory operations \p A and \p B are consecutive. 16370b57cec5SDimitry Andric bool llvm::isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL, 16380b57cec5SDimitry Andric ScalarEvolution &SE, bool CheckType) { 16390b57cec5SDimitry Andric Value *PtrA = getLoadStorePointerOperand(A); 16400b57cec5SDimitry Andric Value *PtrB = getLoadStorePointerOperand(B); 1641fe6060f1SDimitry Andric if (!PtrA || !PtrB) 16420b57cec5SDimitry Andric return false; 1643fe6060f1SDimitry Andric Type *ElemTyA = getLoadStoreType(A); 1644fe6060f1SDimitry Andric Type *ElemTyB = getLoadStoreType(B); 1645bdd1243dSDimitry Andric std::optional<int> Diff = 1646bdd1243dSDimitry Andric getPointersDiff(ElemTyA, PtrA, ElemTyB, PtrB, DL, SE, 1647fe6060f1SDimitry Andric /*StrictCheck=*/true, CheckType); 1648fe6060f1SDimitry Andric return Diff && *Diff == 1; 16490b57cec5SDimitry Andric } 16500b57cec5SDimitry Andric 1651349cc55cSDimitry Andric void MemoryDepChecker::addAccess(StoreInst *SI) { 1652349cc55cSDimitry Andric visitPointers(SI->getPointerOperand(), *InnermostLoop, 1653349cc55cSDimitry Andric [this, SI](Value *Ptr) { 1654349cc55cSDimitry Andric Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx); 1655349cc55cSDimitry Andric InstMap.push_back(SI); 1656349cc55cSDimitry Andric ++AccessIdx; 1657349cc55cSDimitry Andric }); 1658349cc55cSDimitry Andric } 1659349cc55cSDimitry Andric 1660349cc55cSDimitry Andric void MemoryDepChecker::addAccess(LoadInst *LI) { 1661349cc55cSDimitry Andric visitPointers(LI->getPointerOperand(), *InnermostLoop, 1662349cc55cSDimitry Andric [this, LI](Value *Ptr) { 1663349cc55cSDimitry Andric Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx); 1664349cc55cSDimitry Andric InstMap.push_back(LI); 1665349cc55cSDimitry Andric ++AccessIdx; 1666349cc55cSDimitry Andric }); 1667349cc55cSDimitry Andric } 1668349cc55cSDimitry Andric 16690b57cec5SDimitry Andric MemoryDepChecker::VectorizationSafetyStatus 16700b57cec5SDimitry Andric MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) { 16710b57cec5SDimitry Andric switch (Type) { 16720b57cec5SDimitry Andric case NoDep: 16730b57cec5SDimitry Andric case Forward: 16740b57cec5SDimitry Andric case BackwardVectorizable: 16750b57cec5SDimitry Andric return VectorizationSafetyStatus::Safe; 16760b57cec5SDimitry Andric 16770b57cec5SDimitry Andric case Unknown: 16780b57cec5SDimitry Andric return VectorizationSafetyStatus::PossiblySafeWithRtChecks; 16790b57cec5SDimitry Andric case ForwardButPreventsForwarding: 16800b57cec5SDimitry Andric case Backward: 16810b57cec5SDimitry Andric case BackwardVectorizableButPreventsForwarding: 1682c9157d92SDimitry Andric case IndirectUnsafe: 16830b57cec5SDimitry Andric return VectorizationSafetyStatus::Unsafe; 16840b57cec5SDimitry Andric } 16850b57cec5SDimitry Andric llvm_unreachable("unexpected DepType!"); 16860b57cec5SDimitry Andric } 16870b57cec5SDimitry Andric 16880b57cec5SDimitry Andric bool MemoryDepChecker::Dependence::isBackward() const { 16890b57cec5SDimitry Andric switch (Type) { 16900b57cec5SDimitry Andric case NoDep: 16910b57cec5SDimitry Andric case Forward: 16920b57cec5SDimitry Andric case ForwardButPreventsForwarding: 16930b57cec5SDimitry Andric case Unknown: 1694c9157d92SDimitry Andric case IndirectUnsafe: 16950b57cec5SDimitry Andric return false; 16960b57cec5SDimitry Andric 16970b57cec5SDimitry Andric case BackwardVectorizable: 16980b57cec5SDimitry Andric case Backward: 16990b57cec5SDimitry Andric case BackwardVectorizableButPreventsForwarding: 17000b57cec5SDimitry Andric return true; 17010b57cec5SDimitry Andric } 17020b57cec5SDimitry Andric llvm_unreachable("unexpected DepType!"); 17030b57cec5SDimitry Andric } 17040b57cec5SDimitry Andric 17050b57cec5SDimitry Andric bool MemoryDepChecker::Dependence::isPossiblyBackward() const { 17060b57cec5SDimitry Andric return isBackward() || Type == Unknown; 17070b57cec5SDimitry Andric } 17080b57cec5SDimitry Andric 17090b57cec5SDimitry Andric bool MemoryDepChecker::Dependence::isForward() const { 17100b57cec5SDimitry Andric switch (Type) { 17110b57cec5SDimitry Andric case Forward: 17120b57cec5SDimitry Andric case ForwardButPreventsForwarding: 17130b57cec5SDimitry Andric return true; 17140b57cec5SDimitry Andric 17150b57cec5SDimitry Andric case NoDep: 17160b57cec5SDimitry Andric case Unknown: 17170b57cec5SDimitry Andric case BackwardVectorizable: 17180b57cec5SDimitry Andric case Backward: 17190b57cec5SDimitry Andric case BackwardVectorizableButPreventsForwarding: 1720c9157d92SDimitry Andric case IndirectUnsafe: 17210b57cec5SDimitry Andric return false; 17220b57cec5SDimitry Andric } 17230b57cec5SDimitry Andric llvm_unreachable("unexpected DepType!"); 17240b57cec5SDimitry Andric } 17250b57cec5SDimitry Andric 17260b57cec5SDimitry Andric bool MemoryDepChecker::couldPreventStoreLoadForward(uint64_t Distance, 17270b57cec5SDimitry Andric uint64_t TypeByteSize) { 17280b57cec5SDimitry Andric // If loads occur at a distance that is not a multiple of a feasible vector 17290b57cec5SDimitry Andric // factor store-load forwarding does not take place. 17300b57cec5SDimitry Andric // Positive dependences might cause troubles because vectorizing them might 17310b57cec5SDimitry Andric // prevent store-load forwarding making vectorized code run a lot slower. 17320b57cec5SDimitry Andric // a[i] = a[i-3] ^ a[i-8]; 17330b57cec5SDimitry Andric // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and 17340b57cec5SDimitry Andric // hence on your typical architecture store-load forwarding does not take 17350b57cec5SDimitry Andric // place. Vectorizing in such cases does not make sense. 17360b57cec5SDimitry Andric // Store-load forwarding distance. 17370b57cec5SDimitry Andric 17380b57cec5SDimitry Andric // After this many iterations store-to-load forwarding conflicts should not 17390b57cec5SDimitry Andric // cause any slowdowns. 17400b57cec5SDimitry Andric const uint64_t NumItersForStoreLoadThroughMemory = 8 * TypeByteSize; 17410b57cec5SDimitry Andric // Maximum vector factor. 17420b57cec5SDimitry Andric uint64_t MaxVFWithoutSLForwardIssues = std::min( 1743c9157d92SDimitry Andric VectorizerParams::MaxVectorWidth * TypeByteSize, MinDepDistBytes); 17440b57cec5SDimitry Andric 17450b57cec5SDimitry Andric // Compute the smallest VF at which the store and load would be misaligned. 17460b57cec5SDimitry Andric for (uint64_t VF = 2 * TypeByteSize; VF <= MaxVFWithoutSLForwardIssues; 17470b57cec5SDimitry Andric VF *= 2) { 17480b57cec5SDimitry Andric // If the number of vector iteration between the store and the load are 17490b57cec5SDimitry Andric // small we could incur conflicts. 17500b57cec5SDimitry Andric if (Distance % VF && Distance / VF < NumItersForStoreLoadThroughMemory) { 1751e8d8bef9SDimitry Andric MaxVFWithoutSLForwardIssues = (VF >> 1); 17520b57cec5SDimitry Andric break; 17530b57cec5SDimitry Andric } 17540b57cec5SDimitry Andric } 17550b57cec5SDimitry Andric 17560b57cec5SDimitry Andric if (MaxVFWithoutSLForwardIssues < 2 * TypeByteSize) { 17570b57cec5SDimitry Andric LLVM_DEBUG( 17580b57cec5SDimitry Andric dbgs() << "LAA: Distance " << Distance 17590b57cec5SDimitry Andric << " that could cause a store-load forwarding conflict\n"); 17600b57cec5SDimitry Andric return true; 17610b57cec5SDimitry Andric } 17620b57cec5SDimitry Andric 1763c9157d92SDimitry Andric if (MaxVFWithoutSLForwardIssues < MinDepDistBytes && 17640b57cec5SDimitry Andric MaxVFWithoutSLForwardIssues != 17650b57cec5SDimitry Andric VectorizerParams::MaxVectorWidth * TypeByteSize) 1766c9157d92SDimitry Andric MinDepDistBytes = MaxVFWithoutSLForwardIssues; 17670b57cec5SDimitry Andric return false; 17680b57cec5SDimitry Andric } 17690b57cec5SDimitry Andric 17700b57cec5SDimitry Andric void MemoryDepChecker::mergeInStatus(VectorizationSafetyStatus S) { 17710b57cec5SDimitry Andric if (Status < S) 17720b57cec5SDimitry Andric Status = S; 17730b57cec5SDimitry Andric } 17740b57cec5SDimitry Andric 1775bdd1243dSDimitry Andric /// Given a dependence-distance \p Dist between two 17760b57cec5SDimitry Andric /// memory accesses, that have the same stride whose absolute value is given 17770b57cec5SDimitry Andric /// in \p Stride, and that have the same type size \p TypeByteSize, 17780b57cec5SDimitry Andric /// in a loop whose takenCount is \p BackedgeTakenCount, check if it is 17790b57cec5SDimitry Andric /// possible to prove statically that the dependence distance is larger 17800b57cec5SDimitry Andric /// than the range that the accesses will travel through the execution of 17810b57cec5SDimitry Andric /// the loop. If so, return true; false otherwise. This is useful for 17820b57cec5SDimitry Andric /// example in loops such as the following (PR31098): 17830b57cec5SDimitry Andric /// for (i = 0; i < D; ++i) { 17840b57cec5SDimitry Andric /// = out[i]; 17850b57cec5SDimitry Andric /// out[i+D] = 17860b57cec5SDimitry Andric /// } 17870b57cec5SDimitry Andric static bool isSafeDependenceDistance(const DataLayout &DL, ScalarEvolution &SE, 17880b57cec5SDimitry Andric const SCEV &BackedgeTakenCount, 17890b57cec5SDimitry Andric const SCEV &Dist, uint64_t Stride, 17900b57cec5SDimitry Andric uint64_t TypeByteSize) { 17910b57cec5SDimitry Andric 17920b57cec5SDimitry Andric // If we can prove that 17930b57cec5SDimitry Andric // (**) |Dist| > BackedgeTakenCount * Step 17940b57cec5SDimitry Andric // where Step is the absolute stride of the memory accesses in bytes, 17950b57cec5SDimitry Andric // then there is no dependence. 17960b57cec5SDimitry Andric // 17970b57cec5SDimitry Andric // Rationale: 17980b57cec5SDimitry Andric // We basically want to check if the absolute distance (|Dist/Step|) 17990b57cec5SDimitry Andric // is >= the loop iteration count (or > BackedgeTakenCount). 18000b57cec5SDimitry Andric // This is equivalent to the Strong SIV Test (Practical Dependence Testing, 18010b57cec5SDimitry Andric // Section 4.2.1); Note, that for vectorization it is sufficient to prove 18020b57cec5SDimitry Andric // that the dependence distance is >= VF; This is checked elsewhere. 1803bdd1243dSDimitry Andric // But in some cases we can prune dependence distances early, and 18040b57cec5SDimitry Andric // even before selecting the VF, and without a runtime test, by comparing 18050b57cec5SDimitry Andric // the distance against the loop iteration count. Since the vectorized code 18060b57cec5SDimitry Andric // will be executed only if LoopCount >= VF, proving distance >= LoopCount 18070b57cec5SDimitry Andric // also guarantees that distance >= VF. 18080b57cec5SDimitry Andric // 18090b57cec5SDimitry Andric const uint64_t ByteStride = Stride * TypeByteSize; 18100b57cec5SDimitry Andric const SCEV *Step = SE.getConstant(BackedgeTakenCount.getType(), ByteStride); 18110b57cec5SDimitry Andric const SCEV *Product = SE.getMulExpr(&BackedgeTakenCount, Step); 18120b57cec5SDimitry Andric 18130b57cec5SDimitry Andric const SCEV *CastedDist = &Dist; 18140b57cec5SDimitry Andric const SCEV *CastedProduct = Product; 181581ad6265SDimitry Andric uint64_t DistTypeSizeBits = DL.getTypeSizeInBits(Dist.getType()); 181681ad6265SDimitry Andric uint64_t ProductTypeSizeBits = DL.getTypeSizeInBits(Product->getType()); 18170b57cec5SDimitry Andric 18180b57cec5SDimitry Andric // The dependence distance can be positive/negative, so we sign extend Dist; 18190b57cec5SDimitry Andric // The multiplication of the absolute stride in bytes and the 18200b57cec5SDimitry Andric // backedgeTakenCount is non-negative, so we zero extend Product. 182181ad6265SDimitry Andric if (DistTypeSizeBits > ProductTypeSizeBits) 18220b57cec5SDimitry Andric CastedProduct = SE.getZeroExtendExpr(Product, Dist.getType()); 18230b57cec5SDimitry Andric else 18240b57cec5SDimitry Andric CastedDist = SE.getNoopOrSignExtend(&Dist, Product->getType()); 18250b57cec5SDimitry Andric 18260b57cec5SDimitry Andric // Is Dist - (BackedgeTakenCount * Step) > 0 ? 18270b57cec5SDimitry Andric // (If so, then we have proven (**) because |Dist| >= Dist) 18280b57cec5SDimitry Andric const SCEV *Minus = SE.getMinusSCEV(CastedDist, CastedProduct); 18290b57cec5SDimitry Andric if (SE.isKnownPositive(Minus)) 18300b57cec5SDimitry Andric return true; 18310b57cec5SDimitry Andric 18320b57cec5SDimitry Andric // Second try: Is -Dist - (BackedgeTakenCount * Step) > 0 ? 18330b57cec5SDimitry Andric // (If so, then we have proven (**) because |Dist| >= -1*Dist) 18340b57cec5SDimitry Andric const SCEV *NegDist = SE.getNegativeSCEV(CastedDist); 18350b57cec5SDimitry Andric Minus = SE.getMinusSCEV(NegDist, CastedProduct); 18360b57cec5SDimitry Andric if (SE.isKnownPositive(Minus)) 18370b57cec5SDimitry Andric return true; 18380b57cec5SDimitry Andric 18390b57cec5SDimitry Andric return false; 18400b57cec5SDimitry Andric } 18410b57cec5SDimitry Andric 18420b57cec5SDimitry Andric /// Check the dependence for two accesses with the same stride \p Stride. 18430b57cec5SDimitry Andric /// \p Distance is the positive distance and \p TypeByteSize is type size in 18440b57cec5SDimitry Andric /// bytes. 18450b57cec5SDimitry Andric /// 18460b57cec5SDimitry Andric /// \returns true if they are independent. 18470b57cec5SDimitry Andric static bool areStridedAccessesIndependent(uint64_t Distance, uint64_t Stride, 18480b57cec5SDimitry Andric uint64_t TypeByteSize) { 18490b57cec5SDimitry Andric assert(Stride > 1 && "The stride must be greater than 1"); 18500b57cec5SDimitry Andric assert(TypeByteSize > 0 && "The type size in byte must be non-zero"); 18510b57cec5SDimitry Andric assert(Distance > 0 && "The distance must be non-zero"); 18520b57cec5SDimitry Andric 18530b57cec5SDimitry Andric // Skip if the distance is not multiple of type byte size. 18540b57cec5SDimitry Andric if (Distance % TypeByteSize) 18550b57cec5SDimitry Andric return false; 18560b57cec5SDimitry Andric 18570b57cec5SDimitry Andric uint64_t ScaledDist = Distance / TypeByteSize; 18580b57cec5SDimitry Andric 18590b57cec5SDimitry Andric // No dependence if the scaled distance is not multiple of the stride. 18600b57cec5SDimitry Andric // E.g. 18610b57cec5SDimitry Andric // for (i = 0; i < 1024 ; i += 4) 18620b57cec5SDimitry Andric // A[i+2] = A[i] + 1; 18630b57cec5SDimitry Andric // 18640b57cec5SDimitry Andric // Two accesses in memory (scaled distance is 2, stride is 4): 18650b57cec5SDimitry Andric // | A[0] | | | | A[4] | | | | 18660b57cec5SDimitry Andric // | | | A[2] | | | | A[6] | | 18670b57cec5SDimitry Andric // 18680b57cec5SDimitry Andric // E.g. 18690b57cec5SDimitry Andric // for (i = 0; i < 1024 ; i += 3) 18700b57cec5SDimitry Andric // A[i+4] = A[i] + 1; 18710b57cec5SDimitry Andric // 18720b57cec5SDimitry Andric // Two accesses in memory (scaled distance is 4, stride is 3): 18730b57cec5SDimitry Andric // | A[0] | | | A[3] | | | A[6] | | | 18740b57cec5SDimitry Andric // | | | | | A[4] | | | A[7] | | 18750b57cec5SDimitry Andric return ScaledDist % Stride; 18760b57cec5SDimitry Andric } 18770b57cec5SDimitry Andric 1878c9157d92SDimitry Andric /// Returns true if any of the underlying objects has a loop varying address, 1879c9157d92SDimitry Andric /// i.e. may change in \p L. 1880c9157d92SDimitry Andric static bool 1881c9157d92SDimitry Andric isLoopVariantIndirectAddress(ArrayRef<const Value *> UnderlyingObjects, 1882c9157d92SDimitry Andric ScalarEvolution &SE, const Loop *L) { 1883c9157d92SDimitry Andric return any_of(UnderlyingObjects, [&SE, L](const Value *UO) { 1884c9157d92SDimitry Andric return !SE.isLoopInvariant(SE.getSCEV(const_cast<Value *>(UO)), L); 1885c9157d92SDimitry Andric }); 1886c9157d92SDimitry Andric } 18870b57cec5SDimitry Andric 1888c9157d92SDimitry Andric // Get the dependence distance, stride, type size in whether i is a write for 1889c9157d92SDimitry Andric // the dependence between A and B. Returns a DepType, if we can prove there's 1890c9157d92SDimitry Andric // no dependence or the analysis fails. Outlined to lambda to limit he scope 1891c9157d92SDimitry Andric // of various temporary variables, like A/BPtr, StrideA/BPtr and others. 1892c9157d92SDimitry Andric // Returns either the dependence result, if it could already be determined, or a 1893c9157d92SDimitry Andric // tuple with (Distance, Stride, TypeSize, AIsWrite, BIsWrite). 1894c9157d92SDimitry Andric static std::variant<MemoryDepChecker::Dependence::DepType, 1895c9157d92SDimitry Andric std::tuple<const SCEV *, uint64_t, uint64_t, bool, bool>> 1896c9157d92SDimitry Andric getDependenceDistanceStrideAndSize( 1897c9157d92SDimitry Andric const AccessAnalysis::MemAccessInfo &A, Instruction *AInst, 1898c9157d92SDimitry Andric const AccessAnalysis::MemAccessInfo &B, Instruction *BInst, 1899c9157d92SDimitry Andric const DenseMap<Value *, const SCEV *> &Strides, 1900c9157d92SDimitry Andric const DenseMap<Value *, SmallVector<const Value *, 16>> &UnderlyingObjects, 1901c9157d92SDimitry Andric PredicatedScalarEvolution &PSE, const Loop *InnermostLoop) { 1902c9157d92SDimitry Andric auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout(); 1903c9157d92SDimitry Andric auto &SE = *PSE.getSE(); 1904bdd1243dSDimitry Andric auto [APtr, AIsWrite] = A; 1905bdd1243dSDimitry Andric auto [BPtr, BIsWrite] = B; 19060b57cec5SDimitry Andric 19070b57cec5SDimitry Andric // Two reads are independent. 19080b57cec5SDimitry Andric if (!AIsWrite && !BIsWrite) 1909c9157d92SDimitry Andric return MemoryDepChecker::Dependence::NoDep; 1910c9157d92SDimitry Andric 1911c9157d92SDimitry Andric Type *ATy = getLoadStoreType(AInst); 1912c9157d92SDimitry Andric Type *BTy = getLoadStoreType(BInst); 19130b57cec5SDimitry Andric 19140b57cec5SDimitry Andric // We cannot check pointers in different address spaces. 19150b57cec5SDimitry Andric if (APtr->getType()->getPointerAddressSpace() != 19160b57cec5SDimitry Andric BPtr->getType()->getPointerAddressSpace()) 1917c9157d92SDimitry Andric return MemoryDepChecker::Dependence::Unknown; 19180b57cec5SDimitry Andric 1919349cc55cSDimitry Andric int64_t StrideAPtr = 1920bdd1243dSDimitry Andric getPtrStride(PSE, ATy, APtr, InnermostLoop, Strides, true).value_or(0); 1921349cc55cSDimitry Andric int64_t StrideBPtr = 1922bdd1243dSDimitry Andric getPtrStride(PSE, BTy, BPtr, InnermostLoop, Strides, true).value_or(0); 19230b57cec5SDimitry Andric 19240b57cec5SDimitry Andric const SCEV *Src = PSE.getSCEV(APtr); 19250b57cec5SDimitry Andric const SCEV *Sink = PSE.getSCEV(BPtr); 19260b57cec5SDimitry Andric 19270b57cec5SDimitry Andric // If the induction step is negative we have to invert source and sink of the 1928c9157d92SDimitry Andric // dependence when measuring the distance between them. We should not swap 1929c9157d92SDimitry Andric // AIsWrite with BIsWrite, as their uses expect them in program order. 19300b57cec5SDimitry Andric if (StrideAPtr < 0) { 19310b57cec5SDimitry Andric std::swap(Src, Sink); 1932c9157d92SDimitry Andric std::swap(AInst, BInst); 19330b57cec5SDimitry Andric } 19340b57cec5SDimitry Andric 1935bdd1243dSDimitry Andric const SCEV *Dist = SE.getMinusSCEV(Sink, Src); 19360b57cec5SDimitry Andric 19370b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink 19380b57cec5SDimitry Andric << "(Induction step: " << StrideAPtr << ")\n"); 1939c9157d92SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Distance for " << *AInst << " to " << *BInst 1940c9157d92SDimitry Andric << ": " << *Dist << "\n"); 1941c9157d92SDimitry Andric 1942c9157d92SDimitry Andric // Needs accesses where the addresses of the accessed underlying objects do 1943c9157d92SDimitry Andric // not change within the loop. 1944c9157d92SDimitry Andric if (isLoopVariantIndirectAddress(UnderlyingObjects.find(APtr)->second, SE, 1945c9157d92SDimitry Andric InnermostLoop) || 1946c9157d92SDimitry Andric isLoopVariantIndirectAddress(UnderlyingObjects.find(BPtr)->second, SE, 1947c9157d92SDimitry Andric InnermostLoop)) 1948c9157d92SDimitry Andric return MemoryDepChecker::Dependence::IndirectUnsafe; 19490b57cec5SDimitry Andric 19500b57cec5SDimitry Andric // Need accesses with constant stride. We don't want to vectorize 1951c9157d92SDimitry Andric // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap 1952c9157d92SDimitry Andric // in the address space. 19530b57cec5SDimitry Andric if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr) { 19540b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Pointer access with non-constant stride\n"); 1955c9157d92SDimitry Andric return MemoryDepChecker::Dependence::Unknown; 19560b57cec5SDimitry Andric } 19570b57cec5SDimitry Andric 19580b57cec5SDimitry Andric uint64_t TypeByteSize = DL.getTypeAllocSize(ATy); 19590eae32dcSDimitry Andric bool HasSameSize = 19600eae32dcSDimitry Andric DL.getTypeStoreSizeInBits(ATy) == DL.getTypeStoreSizeInBits(BTy); 1961c9157d92SDimitry Andric if (!HasSameSize) 1962c9157d92SDimitry Andric TypeByteSize = 0; 19630b57cec5SDimitry Andric uint64_t Stride = std::abs(StrideAPtr); 1964c9157d92SDimitry Andric return std::make_tuple(Dist, Stride, TypeByteSize, AIsWrite, BIsWrite); 1965c9157d92SDimitry Andric } 1966bdd1243dSDimitry Andric 1967c9157d92SDimitry Andric MemoryDepChecker::Dependence::DepType MemoryDepChecker::isDependent( 1968c9157d92SDimitry Andric const MemAccessInfo &A, unsigned AIdx, const MemAccessInfo &B, 1969c9157d92SDimitry Andric unsigned BIdx, const DenseMap<Value *, const SCEV *> &Strides, 1970c9157d92SDimitry Andric const DenseMap<Value *, SmallVector<const Value *, 16>> 1971c9157d92SDimitry Andric &UnderlyingObjects) { 1972c9157d92SDimitry Andric assert(AIdx < BIdx && "Must pass arguments in program order"); 1973c9157d92SDimitry Andric 1974c9157d92SDimitry Andric // Get the dependence distance, stride, type size and what access writes for 1975c9157d92SDimitry Andric // the dependence between A and B. 1976c9157d92SDimitry Andric auto Res = getDependenceDistanceStrideAndSize( 1977c9157d92SDimitry Andric A, InstMap[AIdx], B, InstMap[BIdx], Strides, UnderlyingObjects, PSE, 1978c9157d92SDimitry Andric InnermostLoop); 1979c9157d92SDimitry Andric if (std::holds_alternative<Dependence::DepType>(Res)) 1980c9157d92SDimitry Andric return std::get<Dependence::DepType>(Res); 1981c9157d92SDimitry Andric 1982c9157d92SDimitry Andric const auto &[Dist, Stride, TypeByteSize, AIsWrite, BIsWrite] = 1983c9157d92SDimitry Andric std::get<std::tuple<const SCEV *, uint64_t, uint64_t, bool, bool>>(Res); 1984c9157d92SDimitry Andric bool HasSameSize = TypeByteSize > 0; 1985c9157d92SDimitry Andric 1986c9157d92SDimitry Andric ScalarEvolution &SE = *PSE.getSE(); 1987c9157d92SDimitry Andric auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout(); 19880eae32dcSDimitry Andric if (!isa<SCEVCouldNotCompute>(Dist) && HasSameSize && 1989bdd1243dSDimitry Andric isSafeDependenceDistance(DL, SE, *(PSE.getBackedgeTakenCount()), *Dist, 1990bdd1243dSDimitry Andric Stride, TypeByteSize)) 19910b57cec5SDimitry Andric return Dependence::NoDep; 19920b57cec5SDimitry Andric 1993bdd1243dSDimitry Andric const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist); 1994bdd1243dSDimitry Andric if (!C) { 19950b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n"); 19960b57cec5SDimitry Andric FoundNonConstantDistanceDependence = true; 19970b57cec5SDimitry Andric return Dependence::Unknown; 19980b57cec5SDimitry Andric } 19990b57cec5SDimitry Andric 20000b57cec5SDimitry Andric const APInt &Val = C->getAPInt(); 20010b57cec5SDimitry Andric int64_t Distance = Val.getSExtValue(); 20020b57cec5SDimitry Andric 20030b57cec5SDimitry Andric // Attempt to prove strided accesses independent. 20040eae32dcSDimitry Andric if (std::abs(Distance) > 0 && Stride > 1 && HasSameSize && 20050b57cec5SDimitry Andric areStridedAccessesIndependent(std::abs(Distance), Stride, TypeByteSize)) { 20060b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Strided accesses are independent\n"); 20070b57cec5SDimitry Andric return Dependence::NoDep; 20080b57cec5SDimitry Andric } 20090b57cec5SDimitry Andric 20100b57cec5SDimitry Andric // Negative distances are not plausible dependencies. 20110b57cec5SDimitry Andric if (Val.isNegative()) { 20120b57cec5SDimitry Andric bool IsTrueDataDependence = (AIsWrite && !BIsWrite); 2013c9157d92SDimitry Andric // There is no need to update MaxSafeVectorWidthInBits after call to 2014c9157d92SDimitry Andric // couldPreventStoreLoadForward, even if it changed MinDepDistBytes, 2015c9157d92SDimitry Andric // since a forward dependency will allow vectorization using any width. 20160b57cec5SDimitry Andric if (IsTrueDataDependence && EnableForwardingConflictDetection && 2017c9157d92SDimitry Andric (!HasSameSize || couldPreventStoreLoadForward(Val.abs().getZExtValue(), 2018c9157d92SDimitry Andric TypeByteSize))) { 20190b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Forward but may prevent st->ld forwarding\n"); 20200b57cec5SDimitry Andric return Dependence::ForwardButPreventsForwarding; 20210b57cec5SDimitry Andric } 20220b57cec5SDimitry Andric 20230b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Dependence is negative\n"); 20240b57cec5SDimitry Andric return Dependence::Forward; 20250b57cec5SDimitry Andric } 20260b57cec5SDimitry Andric 20270b57cec5SDimitry Andric // Write to the same location with the same size. 20280b57cec5SDimitry Andric if (Val == 0) { 20290eae32dcSDimitry Andric if (HasSameSize) 20300b57cec5SDimitry Andric return Dependence::Forward; 20310b57cec5SDimitry Andric LLVM_DEBUG( 20320eae32dcSDimitry Andric dbgs() << "LAA: Zero dependence difference but different type sizes\n"); 20330b57cec5SDimitry Andric return Dependence::Unknown; 20340b57cec5SDimitry Andric } 20350b57cec5SDimitry Andric 20360b57cec5SDimitry Andric assert(Val.isStrictlyPositive() && "Expect a positive value"); 20370b57cec5SDimitry Andric 20380eae32dcSDimitry Andric if (!HasSameSize) { 20390eae32dcSDimitry Andric LLVM_DEBUG(dbgs() << "LAA: ReadWrite-Write positive dependency with " 20400eae32dcSDimitry Andric "different type sizes\n"); 20410b57cec5SDimitry Andric return Dependence::Unknown; 20420b57cec5SDimitry Andric } 20430b57cec5SDimitry Andric 20440b57cec5SDimitry Andric // Bail out early if passed-in parameters make vectorization not feasible. 20450b57cec5SDimitry Andric unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ? 20460b57cec5SDimitry Andric VectorizerParams::VectorizationFactor : 1); 20470b57cec5SDimitry Andric unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ? 20480b57cec5SDimitry Andric VectorizerParams::VectorizationInterleave : 1); 20490b57cec5SDimitry Andric // The minimum number of iterations for a vectorized/unrolled version. 20500b57cec5SDimitry Andric unsigned MinNumIter = std::max(ForcedFactor * ForcedUnroll, 2U); 20510b57cec5SDimitry Andric 20520b57cec5SDimitry Andric // It's not vectorizable if the distance is smaller than the minimum distance 20530b57cec5SDimitry Andric // needed for a vectroized/unrolled version. Vectorizing one iteration in 20540b57cec5SDimitry Andric // front needs TypeByteSize * Stride. Vectorizing the last iteration needs 20550b57cec5SDimitry Andric // TypeByteSize (No need to plus the last gap distance). 20560b57cec5SDimitry Andric // 20570b57cec5SDimitry Andric // E.g. Assume one char is 1 byte in memory and one int is 4 bytes. 20580b57cec5SDimitry Andric // foo(int *A) { 20590b57cec5SDimitry Andric // int *B = (int *)((char *)A + 14); 20600b57cec5SDimitry Andric // for (i = 0 ; i < 1024 ; i += 2) 20610b57cec5SDimitry Andric // B[i] = A[i] + 1; 20620b57cec5SDimitry Andric // } 20630b57cec5SDimitry Andric // 20640b57cec5SDimitry Andric // Two accesses in memory (stride is 2): 20650b57cec5SDimitry Andric // | A[0] | | A[2] | | A[4] | | A[6] | | 20660b57cec5SDimitry Andric // | B[0] | | B[2] | | B[4] | 20670b57cec5SDimitry Andric // 20680b57cec5SDimitry Andric // Distance needs for vectorizing iterations except the last iteration: 20690b57cec5SDimitry Andric // 4 * 2 * (MinNumIter - 1). Distance needs for the last iteration: 4. 20700b57cec5SDimitry Andric // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4. 20710b57cec5SDimitry Andric // 20720b57cec5SDimitry Andric // If MinNumIter is 2, it is vectorizable as the minimum distance needed is 20730b57cec5SDimitry Andric // 12, which is less than distance. 20740b57cec5SDimitry Andric // 20750b57cec5SDimitry Andric // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4), 20760b57cec5SDimitry Andric // the minimum distance needed is 28, which is greater than distance. It is 20770b57cec5SDimitry Andric // not safe to do vectorization. 20780b57cec5SDimitry Andric uint64_t MinDistanceNeeded = 20790b57cec5SDimitry Andric TypeByteSize * Stride * (MinNumIter - 1) + TypeByteSize; 20800b57cec5SDimitry Andric if (MinDistanceNeeded > static_cast<uint64_t>(Distance)) { 20810b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Failure because of positive distance " 20820b57cec5SDimitry Andric << Distance << '\n'); 20830b57cec5SDimitry Andric return Dependence::Backward; 20840b57cec5SDimitry Andric } 20850b57cec5SDimitry Andric 2086c9157d92SDimitry Andric // Unsafe if the minimum distance needed is greater than smallest dependence 2087c9157d92SDimitry Andric // distance distance. 2088c9157d92SDimitry Andric if (MinDistanceNeeded > MinDepDistBytes) { 20890b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Failure because it needs at least " 2090bdd1243dSDimitry Andric << MinDistanceNeeded << " size in bytes\n"); 20910b57cec5SDimitry Andric return Dependence::Backward; 20920b57cec5SDimitry Andric } 20930b57cec5SDimitry Andric 20940b57cec5SDimitry Andric // Positive distance bigger than max vectorization factor. 20950b57cec5SDimitry Andric // FIXME: Should use max factor instead of max distance in bytes, which could 20960b57cec5SDimitry Andric // not handle different types. 20970b57cec5SDimitry Andric // E.g. Assume one char is 1 byte in memory and one int is 4 bytes. 20980b57cec5SDimitry Andric // void foo (int *A, char *B) { 20990b57cec5SDimitry Andric // for (unsigned i = 0; i < 1024; i++) { 21000b57cec5SDimitry Andric // A[i+2] = A[i] + 1; 21010b57cec5SDimitry Andric // B[i+2] = B[i] + 1; 21020b57cec5SDimitry Andric // } 21030b57cec5SDimitry Andric // } 21040b57cec5SDimitry Andric // 21050b57cec5SDimitry Andric // This case is currently unsafe according to the max safe distance. If we 21060b57cec5SDimitry Andric // analyze the two accesses on array B, the max safe dependence distance 21070b57cec5SDimitry Andric // is 2. Then we analyze the accesses on array A, the minimum distance needed 21080b57cec5SDimitry Andric // is 8, which is less than 2 and forbidden vectorization, But actually 21090b57cec5SDimitry Andric // both A and B could be vectorized by 2 iterations. 2110c9157d92SDimitry Andric MinDepDistBytes = 2111c9157d92SDimitry Andric std::min(static_cast<uint64_t>(Distance), MinDepDistBytes); 21120b57cec5SDimitry Andric 21130b57cec5SDimitry Andric bool IsTrueDataDependence = (!AIsWrite && BIsWrite); 2114c9157d92SDimitry Andric uint64_t MinDepDistBytesOld = MinDepDistBytes; 21150b57cec5SDimitry Andric if (IsTrueDataDependence && EnableForwardingConflictDetection && 2116c9157d92SDimitry Andric couldPreventStoreLoadForward(Distance, TypeByteSize)) { 2117c9157d92SDimitry Andric // Sanity check that we didn't update MinDepDistBytes when calling 2118c9157d92SDimitry Andric // couldPreventStoreLoadForward 2119c9157d92SDimitry Andric assert(MinDepDistBytes == MinDepDistBytesOld && 2120c9157d92SDimitry Andric "An update to MinDepDistBytes requires an update to " 2121c9157d92SDimitry Andric "MaxSafeVectorWidthInBits"); 2122c9157d92SDimitry Andric (void)MinDepDistBytesOld; 21230b57cec5SDimitry Andric return Dependence::BackwardVectorizableButPreventsForwarding; 2124c9157d92SDimitry Andric } 21250b57cec5SDimitry Andric 2126c9157d92SDimitry Andric // An update to MinDepDistBytes requires an update to MaxSafeVectorWidthInBits 2127c9157d92SDimitry Andric // since there is a backwards dependency. 2128c9157d92SDimitry Andric uint64_t MaxVF = MinDepDistBytes / (TypeByteSize * Stride); 21290b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue() 21300b57cec5SDimitry Andric << " with max VF = " << MaxVF << '\n'); 21310b57cec5SDimitry Andric uint64_t MaxVFInBits = MaxVF * TypeByteSize * 8; 2132e8d8bef9SDimitry Andric MaxSafeVectorWidthInBits = std::min(MaxSafeVectorWidthInBits, MaxVFInBits); 21330b57cec5SDimitry Andric return Dependence::BackwardVectorizable; 21340b57cec5SDimitry Andric } 21350b57cec5SDimitry Andric 2136c9157d92SDimitry Andric bool MemoryDepChecker::areDepsSafe( 2137c9157d92SDimitry Andric DepCandidates &AccessSets, MemAccessInfoList &CheckDeps, 2138c9157d92SDimitry Andric const DenseMap<Value *, const SCEV *> &Strides, 2139c9157d92SDimitry Andric const DenseMap<Value *, SmallVector<const Value *, 16>> 2140c9157d92SDimitry Andric &UnderlyingObjects) { 21410b57cec5SDimitry Andric 2142c9157d92SDimitry Andric MinDepDistBytes = -1; 21430b57cec5SDimitry Andric SmallPtrSet<MemAccessInfo, 8> Visited; 21440b57cec5SDimitry Andric for (MemAccessInfo CurAccess : CheckDeps) { 21450b57cec5SDimitry Andric if (Visited.count(CurAccess)) 21460b57cec5SDimitry Andric continue; 21470b57cec5SDimitry Andric 21480b57cec5SDimitry Andric // Get the relevant memory access set. 21490b57cec5SDimitry Andric EquivalenceClasses<MemAccessInfo>::iterator I = 21500b57cec5SDimitry Andric AccessSets.findValue(AccessSets.getLeaderValue(CurAccess)); 21510b57cec5SDimitry Andric 21520b57cec5SDimitry Andric // Check accesses within this set. 21530b57cec5SDimitry Andric EquivalenceClasses<MemAccessInfo>::member_iterator AI = 21540b57cec5SDimitry Andric AccessSets.member_begin(I); 21550b57cec5SDimitry Andric EquivalenceClasses<MemAccessInfo>::member_iterator AE = 21560b57cec5SDimitry Andric AccessSets.member_end(); 21570b57cec5SDimitry Andric 21580b57cec5SDimitry Andric // Check every access pair. 21590b57cec5SDimitry Andric while (AI != AE) { 21600b57cec5SDimitry Andric Visited.insert(*AI); 21618bcb0991SDimitry Andric bool AIIsWrite = AI->getInt(); 21628bcb0991SDimitry Andric // Check loads only against next equivalent class, but stores also against 21638bcb0991SDimitry Andric // other stores in the same equivalence class - to the same address. 21648bcb0991SDimitry Andric EquivalenceClasses<MemAccessInfo>::member_iterator OI = 21658bcb0991SDimitry Andric (AIIsWrite ? AI : std::next(AI)); 21660b57cec5SDimitry Andric while (OI != AE) { 21670b57cec5SDimitry Andric // Check every accessing instruction pair in program order. 21680b57cec5SDimitry Andric for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(), 21690b57cec5SDimitry Andric I1E = Accesses[*AI].end(); I1 != I1E; ++I1) 21708bcb0991SDimitry Andric // Scan all accesses of another equivalence class, but only the next 21718bcb0991SDimitry Andric // accesses of the same equivalent class. 21728bcb0991SDimitry Andric for (std::vector<unsigned>::iterator 21738bcb0991SDimitry Andric I2 = (OI == AI ? std::next(I1) : Accesses[*OI].begin()), 21748bcb0991SDimitry Andric I2E = (OI == AI ? I1E : Accesses[*OI].end()); 21758bcb0991SDimitry Andric I2 != I2E; ++I2) { 21760b57cec5SDimitry Andric auto A = std::make_pair(&*AI, *I1); 21770b57cec5SDimitry Andric auto B = std::make_pair(&*OI, *I2); 21780b57cec5SDimitry Andric 21790b57cec5SDimitry Andric assert(*I1 != *I2); 21800b57cec5SDimitry Andric if (*I1 > *I2) 21810b57cec5SDimitry Andric std::swap(A, B); 21820b57cec5SDimitry Andric 21830b57cec5SDimitry Andric Dependence::DepType Type = 2184c9157d92SDimitry Andric isDependent(*A.first, A.second, *B.first, B.second, Strides, 2185c9157d92SDimitry Andric UnderlyingObjects); 21860b57cec5SDimitry Andric mergeInStatus(Dependence::isSafeForVectorization(Type)); 21870b57cec5SDimitry Andric 21880b57cec5SDimitry Andric // Gather dependences unless we accumulated MaxDependences 21890b57cec5SDimitry Andric // dependences. In that case return as soon as we find the first 21900b57cec5SDimitry Andric // unsafe dependence. This puts a limit on this quadratic 21910b57cec5SDimitry Andric // algorithm. 21920b57cec5SDimitry Andric if (RecordDependences) { 21930b57cec5SDimitry Andric if (Type != Dependence::NoDep) 21940b57cec5SDimitry Andric Dependences.push_back(Dependence(A.second, B.second, Type)); 21950b57cec5SDimitry Andric 21960b57cec5SDimitry Andric if (Dependences.size() >= MaxDependences) { 21970b57cec5SDimitry Andric RecordDependences = false; 21980b57cec5SDimitry Andric Dependences.clear(); 21990b57cec5SDimitry Andric LLVM_DEBUG(dbgs() 22000b57cec5SDimitry Andric << "Too many dependences, stopped recording\n"); 22010b57cec5SDimitry Andric } 22020b57cec5SDimitry Andric } 22030b57cec5SDimitry Andric if (!RecordDependences && !isSafeForVectorization()) 22040b57cec5SDimitry Andric return false; 22050b57cec5SDimitry Andric } 22060b57cec5SDimitry Andric ++OI; 22070b57cec5SDimitry Andric } 22080b57cec5SDimitry Andric AI++; 22090b57cec5SDimitry Andric } 22100b57cec5SDimitry Andric } 22110b57cec5SDimitry Andric 22120b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Total Dependences: " << Dependences.size() << "\n"); 22130b57cec5SDimitry Andric return isSafeForVectorization(); 22140b57cec5SDimitry Andric } 22150b57cec5SDimitry Andric 22160b57cec5SDimitry Andric SmallVector<Instruction *, 4> 22170b57cec5SDimitry Andric MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const { 22180b57cec5SDimitry Andric MemAccessInfo Access(Ptr, isWrite); 22190b57cec5SDimitry Andric auto &IndexVector = Accesses.find(Access)->second; 22200b57cec5SDimitry Andric 22210b57cec5SDimitry Andric SmallVector<Instruction *, 4> Insts; 22220b57cec5SDimitry Andric transform(IndexVector, 22230b57cec5SDimitry Andric std::back_inserter(Insts), 22240b57cec5SDimitry Andric [&](unsigned Idx) { return this->InstMap[Idx]; }); 22250b57cec5SDimitry Andric return Insts; 22260b57cec5SDimitry Andric } 22270b57cec5SDimitry Andric 22280b57cec5SDimitry Andric const char *MemoryDepChecker::Dependence::DepName[] = { 2229c9157d92SDimitry Andric "NoDep", 2230c9157d92SDimitry Andric "Unknown", 2231c9157d92SDimitry Andric "IndidrectUnsafe", 2232c9157d92SDimitry Andric "Forward", 2233c9157d92SDimitry Andric "ForwardButPreventsForwarding", 2234c9157d92SDimitry Andric "Backward", 2235c9157d92SDimitry Andric "BackwardVectorizable", 2236c9157d92SDimitry Andric "BackwardVectorizableButPreventsForwarding"}; 22370b57cec5SDimitry Andric 22380b57cec5SDimitry Andric void MemoryDepChecker::Dependence::print( 22390b57cec5SDimitry Andric raw_ostream &OS, unsigned Depth, 22400b57cec5SDimitry Andric const SmallVectorImpl<Instruction *> &Instrs) const { 22410b57cec5SDimitry Andric OS.indent(Depth) << DepName[Type] << ":\n"; 22420b57cec5SDimitry Andric OS.indent(Depth + 2) << *Instrs[Source] << " -> \n"; 22430b57cec5SDimitry Andric OS.indent(Depth + 2) << *Instrs[Destination] << "\n"; 22440b57cec5SDimitry Andric } 22450b57cec5SDimitry Andric 22460b57cec5SDimitry Andric bool LoopAccessInfo::canAnalyzeLoop() { 22470b57cec5SDimitry Andric // We need to have a loop header. 22480b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Found a loop in " 22490b57cec5SDimitry Andric << TheLoop->getHeader()->getParent()->getName() << ": " 22500b57cec5SDimitry Andric << TheLoop->getHeader()->getName() << '\n'); 22510b57cec5SDimitry Andric 22520b57cec5SDimitry Andric // We can only analyze innermost loops. 2253e8d8bef9SDimitry Andric if (!TheLoop->isInnermost()) { 22540b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: loop is not the innermost loop\n"); 22550b57cec5SDimitry Andric recordAnalysis("NotInnerMostLoop") << "loop is not the innermost loop"; 22560b57cec5SDimitry Andric return false; 22570b57cec5SDimitry Andric } 22580b57cec5SDimitry Andric 22590b57cec5SDimitry Andric // We must have a single backedge. 22600b57cec5SDimitry Andric if (TheLoop->getNumBackEdges() != 1) { 22610b57cec5SDimitry Andric LLVM_DEBUG( 22620b57cec5SDimitry Andric dbgs() << "LAA: loop control flow is not understood by analyzer\n"); 22630b57cec5SDimitry Andric recordAnalysis("CFGNotUnderstood") 22640b57cec5SDimitry Andric << "loop control flow is not understood by analyzer"; 22650b57cec5SDimitry Andric return false; 22660b57cec5SDimitry Andric } 22670b57cec5SDimitry Andric 22680b57cec5SDimitry Andric // ScalarEvolution needs to be able to find the exit count. 22690b57cec5SDimitry Andric const SCEV *ExitCount = PSE->getBackedgeTakenCount(); 2270e8d8bef9SDimitry Andric if (isa<SCEVCouldNotCompute>(ExitCount)) { 22710b57cec5SDimitry Andric recordAnalysis("CantComputeNumberOfIterations") 22720b57cec5SDimitry Andric << "could not determine number of loop iterations"; 22730b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n"); 22740b57cec5SDimitry Andric return false; 22750b57cec5SDimitry Andric } 22760b57cec5SDimitry Andric 22770b57cec5SDimitry Andric return true; 22780b57cec5SDimitry Andric } 22790b57cec5SDimitry Andric 22805ffd83dbSDimitry Andric void LoopAccessInfo::analyzeLoop(AAResults *AA, LoopInfo *LI, 22810b57cec5SDimitry Andric const TargetLibraryInfo *TLI, 22820b57cec5SDimitry Andric DominatorTree *DT) { 22830b57cec5SDimitry Andric // Holds the Load and Store instructions. 22840b57cec5SDimitry Andric SmallVector<LoadInst *, 16> Loads; 22850b57cec5SDimitry Andric SmallVector<StoreInst *, 16> Stores; 22860b57cec5SDimitry Andric 22870b57cec5SDimitry Andric // Holds all the different accesses in the loop. 22880b57cec5SDimitry Andric unsigned NumReads = 0; 22890b57cec5SDimitry Andric unsigned NumReadWrites = 0; 22900b57cec5SDimitry Andric 22910b57cec5SDimitry Andric bool HasComplexMemInst = false; 22920b57cec5SDimitry Andric 22930b57cec5SDimitry Andric // A runtime check is only legal to insert if there are no convergent calls. 22940b57cec5SDimitry Andric HasConvergentOp = false; 22950b57cec5SDimitry Andric 22960b57cec5SDimitry Andric PtrRtChecking->Pointers.clear(); 22970b57cec5SDimitry Andric PtrRtChecking->Need = false; 22980b57cec5SDimitry Andric 22990b57cec5SDimitry Andric const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel(); 23000b57cec5SDimitry Andric 23015ffd83dbSDimitry Andric const bool EnableMemAccessVersioningOfLoop = 23025ffd83dbSDimitry Andric EnableMemAccessVersioning && 23035ffd83dbSDimitry Andric !TheLoop->getHeader()->getParent()->hasOptSize(); 23045ffd83dbSDimitry Andric 2305bdd1243dSDimitry Andric // Traverse blocks in fixed RPOT order, regardless of their storage in the 2306bdd1243dSDimitry Andric // loop info, as it may be arbitrary. 2307bdd1243dSDimitry Andric LoopBlocksRPO RPOT(TheLoop); 2308bdd1243dSDimitry Andric RPOT.perform(LI); 2309bdd1243dSDimitry Andric for (BasicBlock *BB : RPOT) { 23100b57cec5SDimitry Andric // Scan the BB and collect legal loads and stores. Also detect any 23110b57cec5SDimitry Andric // convergent instructions. 23120b57cec5SDimitry Andric for (Instruction &I : *BB) { 23130b57cec5SDimitry Andric if (auto *Call = dyn_cast<CallBase>(&I)) { 23140b57cec5SDimitry Andric if (Call->isConvergent()) 23150b57cec5SDimitry Andric HasConvergentOp = true; 23160b57cec5SDimitry Andric } 23170b57cec5SDimitry Andric 23180b57cec5SDimitry Andric // With both a non-vectorizable memory instruction and a convergent 23190b57cec5SDimitry Andric // operation, found in this loop, no reason to continue the search. 23200b57cec5SDimitry Andric if (HasComplexMemInst && HasConvergentOp) { 23210b57cec5SDimitry Andric CanVecMem = false; 23220b57cec5SDimitry Andric return; 23230b57cec5SDimitry Andric } 23240b57cec5SDimitry Andric 23250b57cec5SDimitry Andric // Avoid hitting recordAnalysis multiple times. 23260b57cec5SDimitry Andric if (HasComplexMemInst) 23270b57cec5SDimitry Andric continue; 23280b57cec5SDimitry Andric 23290b57cec5SDimitry Andric // Many math library functions read the rounding mode. We will only 23300b57cec5SDimitry Andric // vectorize a loop if it contains known function calls that don't set 23310b57cec5SDimitry Andric // the flag. Therefore, it is safe to ignore this read from memory. 23320b57cec5SDimitry Andric auto *Call = dyn_cast<CallInst>(&I); 23330b57cec5SDimitry Andric if (Call && getVectorIntrinsicIDForCall(Call, TLI)) 23340b57cec5SDimitry Andric continue; 23350b57cec5SDimitry Andric 2336c9157d92SDimitry Andric // If this is a load, save it. If this instruction can read from memory 2337c9157d92SDimitry Andric // but is not a load, then we quit. Notice that we don't handle function 2338c9157d92SDimitry Andric // calls that read or write. 2339c9157d92SDimitry Andric if (I.mayReadFromMemory()) { 23400b57cec5SDimitry Andric // If the function has an explicit vectorized counterpart, we can safely 23410b57cec5SDimitry Andric // assume that it can be vectorized. 23420b57cec5SDimitry Andric if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() && 23435ffd83dbSDimitry Andric !VFDatabase::getMappings(*Call).empty()) 23440b57cec5SDimitry Andric continue; 23450b57cec5SDimitry Andric 23460b57cec5SDimitry Andric auto *Ld = dyn_cast<LoadInst>(&I); 23470b57cec5SDimitry Andric if (!Ld) { 23480b57cec5SDimitry Andric recordAnalysis("CantVectorizeInstruction", Ld) 23490b57cec5SDimitry Andric << "instruction cannot be vectorized"; 23500b57cec5SDimitry Andric HasComplexMemInst = true; 23510b57cec5SDimitry Andric continue; 23520b57cec5SDimitry Andric } 23530b57cec5SDimitry Andric if (!Ld->isSimple() && !IsAnnotatedParallel) { 23540b57cec5SDimitry Andric recordAnalysis("NonSimpleLoad", Ld) 23550b57cec5SDimitry Andric << "read with atomic ordering or volatile read"; 23560b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Found a non-simple load.\n"); 23570b57cec5SDimitry Andric HasComplexMemInst = true; 23580b57cec5SDimitry Andric continue; 23590b57cec5SDimitry Andric } 23600b57cec5SDimitry Andric NumLoads++; 23610b57cec5SDimitry Andric Loads.push_back(Ld); 23620b57cec5SDimitry Andric DepChecker->addAccess(Ld); 23635ffd83dbSDimitry Andric if (EnableMemAccessVersioningOfLoop) 23640b57cec5SDimitry Andric collectStridedAccess(Ld); 23650b57cec5SDimitry Andric continue; 23660b57cec5SDimitry Andric } 23670b57cec5SDimitry Andric 23680b57cec5SDimitry Andric // Save 'store' instructions. Abort if other instructions write to memory. 23690b57cec5SDimitry Andric if (I.mayWriteToMemory()) { 23700b57cec5SDimitry Andric auto *St = dyn_cast<StoreInst>(&I); 23710b57cec5SDimitry Andric if (!St) { 23720b57cec5SDimitry Andric recordAnalysis("CantVectorizeInstruction", St) 23730b57cec5SDimitry Andric << "instruction cannot be vectorized"; 23740b57cec5SDimitry Andric HasComplexMemInst = true; 23750b57cec5SDimitry Andric continue; 23760b57cec5SDimitry Andric } 23770b57cec5SDimitry Andric if (!St->isSimple() && !IsAnnotatedParallel) { 23780b57cec5SDimitry Andric recordAnalysis("NonSimpleStore", St) 23790b57cec5SDimitry Andric << "write with atomic ordering or volatile write"; 23800b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Found a non-simple store.\n"); 23810b57cec5SDimitry Andric HasComplexMemInst = true; 23820b57cec5SDimitry Andric continue; 23830b57cec5SDimitry Andric } 23840b57cec5SDimitry Andric NumStores++; 23850b57cec5SDimitry Andric Stores.push_back(St); 23860b57cec5SDimitry Andric DepChecker->addAccess(St); 23875ffd83dbSDimitry Andric if (EnableMemAccessVersioningOfLoop) 23880b57cec5SDimitry Andric collectStridedAccess(St); 23890b57cec5SDimitry Andric } 23900b57cec5SDimitry Andric } // Next instr. 23910b57cec5SDimitry Andric } // Next block. 23920b57cec5SDimitry Andric 23930b57cec5SDimitry Andric if (HasComplexMemInst) { 23940b57cec5SDimitry Andric CanVecMem = false; 23950b57cec5SDimitry Andric return; 23960b57cec5SDimitry Andric } 23970b57cec5SDimitry Andric 23980b57cec5SDimitry Andric // Now we have two lists that hold the loads and the stores. 23990b57cec5SDimitry Andric // Next, we find the pointers that they use. 24000b57cec5SDimitry Andric 24010b57cec5SDimitry Andric // Check if we see any stores. If there are no stores, then we don't 24020b57cec5SDimitry Andric // care if the pointers are *restrict*. 24030b57cec5SDimitry Andric if (!Stores.size()) { 24040b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Found a read-only loop!\n"); 24050b57cec5SDimitry Andric CanVecMem = true; 24060b57cec5SDimitry Andric return; 24070b57cec5SDimitry Andric } 24080b57cec5SDimitry Andric 24090b57cec5SDimitry Andric MemoryDepChecker::DepCandidates DependentAccesses; 2410e8d8bef9SDimitry Andric AccessAnalysis Accesses(TheLoop, AA, LI, DependentAccesses, *PSE); 24110b57cec5SDimitry Andric 2412e8d8bef9SDimitry Andric // Holds the analyzed pointers. We don't want to call getUnderlyingObjects 24130b57cec5SDimitry Andric // multiple times on the same object. If the ptr is accessed twice, once 24140b57cec5SDimitry Andric // for read and once for write, it will only appear once (on the write 24150b57cec5SDimitry Andric // list). This is okay, since we are going to check for conflicts between 24160b57cec5SDimitry Andric // writes and between reads and writes, but not between reads and reads. 241781ad6265SDimitry Andric SmallSet<std::pair<Value *, Type *>, 16> Seen; 24180b57cec5SDimitry Andric 24190b57cec5SDimitry Andric // Record uniform store addresses to identify if we have multiple stores 24200b57cec5SDimitry Andric // to the same address. 242181ad6265SDimitry Andric SmallPtrSet<Value *, 16> UniformStores; 24220b57cec5SDimitry Andric 24230b57cec5SDimitry Andric for (StoreInst *ST : Stores) { 24240b57cec5SDimitry Andric Value *Ptr = ST->getPointerOperand(); 24250b57cec5SDimitry Andric 2426fe013be4SDimitry Andric if (isInvariant(Ptr)) { 242781ad6265SDimitry Andric // Record store instructions to loop invariant addresses 242881ad6265SDimitry Andric StoresToInvariantAddresses.push_back(ST); 24290b57cec5SDimitry Andric HasDependenceInvolvingLoopInvariantAddress |= 24300b57cec5SDimitry Andric !UniformStores.insert(Ptr).second; 243181ad6265SDimitry Andric } 24320b57cec5SDimitry Andric 24330b57cec5SDimitry Andric // If we did *not* see this pointer before, insert it to the read-write 24340b57cec5SDimitry Andric // list. At this phase it is only a 'write' list. 243581ad6265SDimitry Andric Type *AccessTy = getLoadStoreType(ST); 243681ad6265SDimitry Andric if (Seen.insert({Ptr, AccessTy}).second) { 24370b57cec5SDimitry Andric ++NumReadWrites; 24380b57cec5SDimitry Andric 24390b57cec5SDimitry Andric MemoryLocation Loc = MemoryLocation::get(ST); 24400b57cec5SDimitry Andric // The TBAA metadata could have a control dependency on the predication 24410b57cec5SDimitry Andric // condition, so we cannot rely on it when determining whether or not we 24420b57cec5SDimitry Andric // need runtime pointer checks. 24430b57cec5SDimitry Andric if (blockNeedsPredication(ST->getParent(), TheLoop, DT)) 24440b57cec5SDimitry Andric Loc.AATags.TBAA = nullptr; 24450b57cec5SDimitry Andric 2446349cc55cSDimitry Andric visitPointers(const_cast<Value *>(Loc.Ptr), *TheLoop, 244781ad6265SDimitry Andric [&Accesses, AccessTy, Loc](Value *Ptr) { 2448349cc55cSDimitry Andric MemoryLocation NewLoc = Loc.getWithNewPtr(Ptr); 244981ad6265SDimitry Andric Accesses.addStore(NewLoc, AccessTy); 2450349cc55cSDimitry Andric }); 24510b57cec5SDimitry Andric } 24520b57cec5SDimitry Andric } 24530b57cec5SDimitry Andric 24540b57cec5SDimitry Andric if (IsAnnotatedParallel) { 24550b57cec5SDimitry Andric LLVM_DEBUG( 24560b57cec5SDimitry Andric dbgs() << "LAA: A loop annotated parallel, ignore memory dependency " 24570b57cec5SDimitry Andric << "checks.\n"); 24580b57cec5SDimitry Andric CanVecMem = true; 24590b57cec5SDimitry Andric return; 24600b57cec5SDimitry Andric } 24610b57cec5SDimitry Andric 24620b57cec5SDimitry Andric for (LoadInst *LD : Loads) { 24630b57cec5SDimitry Andric Value *Ptr = LD->getPointerOperand(); 24640b57cec5SDimitry Andric // If we did *not* see this pointer before, insert it to the 24650b57cec5SDimitry Andric // read list. If we *did* see it before, then it is already in 24660b57cec5SDimitry Andric // the read-write list. This allows us to vectorize expressions 24670b57cec5SDimitry Andric // such as A[i] += x; Because the address of A[i] is a read-write 24680b57cec5SDimitry Andric // pointer. This only works if the index of A[i] is consecutive. 24690b57cec5SDimitry Andric // If the address of i is unknown (for example A[B[i]]) then we may 24700b57cec5SDimitry Andric // read a few words, modify, and write a few words, and some of the 24710b57cec5SDimitry Andric // words may be written to the same address. 24720b57cec5SDimitry Andric bool IsReadOnlyPtr = false; 247381ad6265SDimitry Andric Type *AccessTy = getLoadStoreType(LD); 247481ad6265SDimitry Andric if (Seen.insert({Ptr, AccessTy}).second || 2475bdd1243dSDimitry Andric !getPtrStride(*PSE, LD->getType(), Ptr, TheLoop, SymbolicStrides).value_or(0)) { 24760b57cec5SDimitry Andric ++NumReads; 24770b57cec5SDimitry Andric IsReadOnlyPtr = true; 24780b57cec5SDimitry Andric } 24790b57cec5SDimitry Andric 24800b57cec5SDimitry Andric // See if there is an unsafe dependency between a load to a uniform address and 24810b57cec5SDimitry Andric // store to the same uniform address. 24820b57cec5SDimitry Andric if (UniformStores.count(Ptr)) { 24830b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Found an unsafe dependency between a uniform " 24840b57cec5SDimitry Andric "load and uniform store to the same address!\n"); 24850b57cec5SDimitry Andric HasDependenceInvolvingLoopInvariantAddress = true; 24860b57cec5SDimitry Andric } 24870b57cec5SDimitry Andric 24880b57cec5SDimitry Andric MemoryLocation Loc = MemoryLocation::get(LD); 24890b57cec5SDimitry Andric // The TBAA metadata could have a control dependency on the predication 24900b57cec5SDimitry Andric // condition, so we cannot rely on it when determining whether or not we 24910b57cec5SDimitry Andric // need runtime pointer checks. 24920b57cec5SDimitry Andric if (blockNeedsPredication(LD->getParent(), TheLoop, DT)) 24930b57cec5SDimitry Andric Loc.AATags.TBAA = nullptr; 24940b57cec5SDimitry Andric 2495349cc55cSDimitry Andric visitPointers(const_cast<Value *>(Loc.Ptr), *TheLoop, 249681ad6265SDimitry Andric [&Accesses, AccessTy, Loc, IsReadOnlyPtr](Value *Ptr) { 2497349cc55cSDimitry Andric MemoryLocation NewLoc = Loc.getWithNewPtr(Ptr); 249881ad6265SDimitry Andric Accesses.addLoad(NewLoc, AccessTy, IsReadOnlyPtr); 2499349cc55cSDimitry Andric }); 25000b57cec5SDimitry Andric } 25010b57cec5SDimitry Andric 25020b57cec5SDimitry Andric // If we write (or read-write) to a single destination and there are no 25030b57cec5SDimitry Andric // other reads in this loop then is it safe to vectorize. 25040b57cec5SDimitry Andric if (NumReadWrites == 1 && NumReads == 0) { 25050b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Found a write-only loop!\n"); 25060b57cec5SDimitry Andric CanVecMem = true; 25070b57cec5SDimitry Andric return; 25080b57cec5SDimitry Andric } 25090b57cec5SDimitry Andric 25100b57cec5SDimitry Andric // Build dependence sets and check whether we need a runtime pointer bounds 25110b57cec5SDimitry Andric // check. 25120b57cec5SDimitry Andric Accesses.buildDependenceSets(); 25130b57cec5SDimitry Andric 25140b57cec5SDimitry Andric // Find pointers with computable bounds. We are going to use this information 25150b57cec5SDimitry Andric // to place a runtime bound check. 251681ad6265SDimitry Andric Value *UncomputablePtr = nullptr; 251781ad6265SDimitry Andric bool CanDoRTIfNeeded = 251881ad6265SDimitry Andric Accesses.canCheckPtrAtRT(*PtrRtChecking, PSE->getSE(), TheLoop, 251981ad6265SDimitry Andric SymbolicStrides, UncomputablePtr, false); 25200b57cec5SDimitry Andric if (!CanDoRTIfNeeded) { 252181ad6265SDimitry Andric auto *I = dyn_cast_or_null<Instruction>(UncomputablePtr); 252281ad6265SDimitry Andric recordAnalysis("CantIdentifyArrayBounds", I) 252381ad6265SDimitry Andric << "cannot identify array bounds"; 25240b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: We can't vectorize because we can't find " 25250b57cec5SDimitry Andric << "the array bounds.\n"); 25260b57cec5SDimitry Andric CanVecMem = false; 25270b57cec5SDimitry Andric return; 25280b57cec5SDimitry Andric } 25290b57cec5SDimitry Andric 25300b57cec5SDimitry Andric LLVM_DEBUG( 25310b57cec5SDimitry Andric dbgs() << "LAA: May be able to perform a memory runtime check if needed.\n"); 25320b57cec5SDimitry Andric 25330b57cec5SDimitry Andric CanVecMem = true; 25340b57cec5SDimitry Andric if (Accesses.isDependencyCheckNeeded()) { 25350b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Checking memory dependencies\n"); 25360b57cec5SDimitry Andric CanVecMem = DepChecker->areDepsSafe( 2537c9157d92SDimitry Andric DependentAccesses, Accesses.getDependenciesToCheck(), SymbolicStrides, 2538c9157d92SDimitry Andric Accesses.getUnderlyingObjects()); 25390b57cec5SDimitry Andric 25400b57cec5SDimitry Andric if (!CanVecMem && DepChecker->shouldRetryWithRuntimeCheck()) { 25410b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Retrying with memory checks\n"); 25420b57cec5SDimitry Andric 25430b57cec5SDimitry Andric // Clear the dependency checks. We assume they are not needed. 25440b57cec5SDimitry Andric Accesses.resetDepChecks(*DepChecker); 25450b57cec5SDimitry Andric 25460b57cec5SDimitry Andric PtrRtChecking->reset(); 25470b57cec5SDimitry Andric PtrRtChecking->Need = true; 25480b57cec5SDimitry Andric 25490b57cec5SDimitry Andric auto *SE = PSE->getSE(); 255081ad6265SDimitry Andric UncomputablePtr = nullptr; 255181ad6265SDimitry Andric CanDoRTIfNeeded = Accesses.canCheckPtrAtRT( 255281ad6265SDimitry Andric *PtrRtChecking, SE, TheLoop, SymbolicStrides, UncomputablePtr, true); 25530b57cec5SDimitry Andric 25540b57cec5SDimitry Andric // Check that we found the bounds for the pointer. 25550b57cec5SDimitry Andric if (!CanDoRTIfNeeded) { 255681ad6265SDimitry Andric auto *I = dyn_cast_or_null<Instruction>(UncomputablePtr); 255781ad6265SDimitry Andric recordAnalysis("CantCheckMemDepsAtRunTime", I) 25580b57cec5SDimitry Andric << "cannot check memory dependencies at runtime"; 25590b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n"); 25600b57cec5SDimitry Andric CanVecMem = false; 25610b57cec5SDimitry Andric return; 25620b57cec5SDimitry Andric } 25630b57cec5SDimitry Andric 25640b57cec5SDimitry Andric CanVecMem = true; 25650b57cec5SDimitry Andric } 25660b57cec5SDimitry Andric } 25670b57cec5SDimitry Andric 25680b57cec5SDimitry Andric if (HasConvergentOp) { 25690b57cec5SDimitry Andric recordAnalysis("CantInsertRuntimeCheckWithConvergent") 25700b57cec5SDimitry Andric << "cannot add control dependency to convergent operation"; 25710b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: We can't vectorize because a runtime check " 25720b57cec5SDimitry Andric "would be needed with a convergent operation\n"); 25730b57cec5SDimitry Andric CanVecMem = false; 25740b57cec5SDimitry Andric return; 25750b57cec5SDimitry Andric } 25760b57cec5SDimitry Andric 25770b57cec5SDimitry Andric if (CanVecMem) 25780b57cec5SDimitry Andric LLVM_DEBUG( 25790b57cec5SDimitry Andric dbgs() << "LAA: No unsafe dependent memory operations in loop. We" 25800b57cec5SDimitry Andric << (PtrRtChecking->Need ? "" : " don't") 25810b57cec5SDimitry Andric << " need runtime memory checks.\n"); 258281ad6265SDimitry Andric else 258381ad6265SDimitry Andric emitUnsafeDependenceRemark(); 258481ad6265SDimitry Andric } 258581ad6265SDimitry Andric 258681ad6265SDimitry Andric void LoopAccessInfo::emitUnsafeDependenceRemark() { 258781ad6265SDimitry Andric auto Deps = getDepChecker().getDependences(); 258881ad6265SDimitry Andric if (!Deps) 258981ad6265SDimitry Andric return; 2590bdd1243dSDimitry Andric auto Found = llvm::find_if(*Deps, [](const MemoryDepChecker::Dependence &D) { 259181ad6265SDimitry Andric return MemoryDepChecker::Dependence::isSafeForVectorization(D.Type) != 259281ad6265SDimitry Andric MemoryDepChecker::VectorizationSafetyStatus::Safe; 259381ad6265SDimitry Andric }); 259481ad6265SDimitry Andric if (Found == Deps->end()) 259581ad6265SDimitry Andric return; 259681ad6265SDimitry Andric MemoryDepChecker::Dependence Dep = *Found; 259781ad6265SDimitry Andric 259881ad6265SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n"); 259981ad6265SDimitry Andric 260081ad6265SDimitry Andric // Emit remark for first unsafe dependence 2601c9157d92SDimitry Andric bool HasForcedDistribution = false; 2602c9157d92SDimitry Andric std::optional<const MDOperand *> Value = 2603c9157d92SDimitry Andric findStringMetadataForLoop(TheLoop, "llvm.loop.distribute.enable"); 2604c9157d92SDimitry Andric if (Value) { 2605c9157d92SDimitry Andric const MDOperand *Op = *Value; 2606c9157d92SDimitry Andric assert(Op && mdconst::hasa<ConstantInt>(*Op) && "invalid metadata"); 2607c9157d92SDimitry Andric HasForcedDistribution = mdconst::extract<ConstantInt>(*Op)->getZExtValue(); 2608c9157d92SDimitry Andric } 2609c9157d92SDimitry Andric 2610c9157d92SDimitry Andric const std::string Info = 2611c9157d92SDimitry Andric HasForcedDistribution 2612c9157d92SDimitry Andric ? "unsafe dependent memory operations in loop." 2613c9157d92SDimitry Andric : "unsafe dependent memory operations in loop. Use " 2614c9157d92SDimitry Andric "#pragma clang loop distribute(enable) to allow loop distribution " 26150b57cec5SDimitry Andric "to attempt to isolate the offending operations into a separate " 26160b57cec5SDimitry Andric "loop"; 2617c9157d92SDimitry Andric OptimizationRemarkAnalysis &R = 2618c9157d92SDimitry Andric recordAnalysis("UnsafeDep", Dep.getDestination(*this)) << Info; 261981ad6265SDimitry Andric 262081ad6265SDimitry Andric switch (Dep.Type) { 262181ad6265SDimitry Andric case MemoryDepChecker::Dependence::NoDep: 262281ad6265SDimitry Andric case MemoryDepChecker::Dependence::Forward: 262381ad6265SDimitry Andric case MemoryDepChecker::Dependence::BackwardVectorizable: 262481ad6265SDimitry Andric llvm_unreachable("Unexpected dependence"); 262581ad6265SDimitry Andric case MemoryDepChecker::Dependence::Backward: 262681ad6265SDimitry Andric R << "\nBackward loop carried data dependence."; 262781ad6265SDimitry Andric break; 262881ad6265SDimitry Andric case MemoryDepChecker::Dependence::ForwardButPreventsForwarding: 262981ad6265SDimitry Andric R << "\nForward loop carried data dependence that prevents " 263081ad6265SDimitry Andric "store-to-load forwarding."; 263181ad6265SDimitry Andric break; 263281ad6265SDimitry Andric case MemoryDepChecker::Dependence::BackwardVectorizableButPreventsForwarding: 263381ad6265SDimitry Andric R << "\nBackward loop carried data dependence that prevents " 263481ad6265SDimitry Andric "store-to-load forwarding."; 263581ad6265SDimitry Andric break; 2636c9157d92SDimitry Andric case MemoryDepChecker::Dependence::IndirectUnsafe: 2637c9157d92SDimitry Andric R << "\nUnsafe indirect dependence."; 2638c9157d92SDimitry Andric break; 263981ad6265SDimitry Andric case MemoryDepChecker::Dependence::Unknown: 264081ad6265SDimitry Andric R << "\nUnknown data dependence."; 264181ad6265SDimitry Andric break; 264281ad6265SDimitry Andric } 264381ad6265SDimitry Andric 264481ad6265SDimitry Andric if (Instruction *I = Dep.getSource(*this)) { 264581ad6265SDimitry Andric DebugLoc SourceLoc = I->getDebugLoc(); 264681ad6265SDimitry Andric if (auto *DD = dyn_cast_or_null<Instruction>(getPointerOperand(I))) 264781ad6265SDimitry Andric SourceLoc = DD->getDebugLoc(); 264881ad6265SDimitry Andric if (SourceLoc) 264981ad6265SDimitry Andric R << " Memory location is the same as accessed at " 265081ad6265SDimitry Andric << ore::NV("Location", SourceLoc); 26510b57cec5SDimitry Andric } 26520b57cec5SDimitry Andric } 26530b57cec5SDimitry Andric 26540b57cec5SDimitry Andric bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop, 26550b57cec5SDimitry Andric DominatorTree *DT) { 26560b57cec5SDimitry Andric assert(TheLoop->contains(BB) && "Unknown block used"); 26570b57cec5SDimitry Andric 26580b57cec5SDimitry Andric // Blocks that do not dominate the latch need predication. 26590b57cec5SDimitry Andric BasicBlock* Latch = TheLoop->getLoopLatch(); 26600b57cec5SDimitry Andric return !DT->dominates(BB, Latch); 26610b57cec5SDimitry Andric } 26620b57cec5SDimitry Andric 26630b57cec5SDimitry Andric OptimizationRemarkAnalysis &LoopAccessInfo::recordAnalysis(StringRef RemarkName, 26640b57cec5SDimitry Andric Instruction *I) { 26650b57cec5SDimitry Andric assert(!Report && "Multiple reports generated"); 26660b57cec5SDimitry Andric 26670b57cec5SDimitry Andric Value *CodeRegion = TheLoop->getHeader(); 26680b57cec5SDimitry Andric DebugLoc DL = TheLoop->getStartLoc(); 26690b57cec5SDimitry Andric 26700b57cec5SDimitry Andric if (I) { 26710b57cec5SDimitry Andric CodeRegion = I->getParent(); 26720b57cec5SDimitry Andric // If there is no debug location attached to the instruction, revert back to 26730b57cec5SDimitry Andric // using the loop's. 26740b57cec5SDimitry Andric if (I->getDebugLoc()) 26750b57cec5SDimitry Andric DL = I->getDebugLoc(); 26760b57cec5SDimitry Andric } 26770b57cec5SDimitry Andric 26788bcb0991SDimitry Andric Report = std::make_unique<OptimizationRemarkAnalysis>(DEBUG_TYPE, RemarkName, DL, 26790b57cec5SDimitry Andric CodeRegion); 26800b57cec5SDimitry Andric return *Report; 26810b57cec5SDimitry Andric } 26820b57cec5SDimitry Andric 2683fe013be4SDimitry Andric bool LoopAccessInfo::isInvariant(Value *V) const { 26840b57cec5SDimitry Andric auto *SE = PSE->getSE(); 26850b57cec5SDimitry Andric // TODO: Is this really what we want? Even without FP SCEV, we may want some 2686fe013be4SDimitry Andric // trivially loop-invariant FP values to be considered invariant. 26870b57cec5SDimitry Andric if (!SE->isSCEVable(V->getType())) 26880b57cec5SDimitry Andric return false; 2689fe013be4SDimitry Andric const SCEV *S = SE->getSCEV(V); 2690fe013be4SDimitry Andric return SE->isLoopInvariant(S, TheLoop); 2691fe013be4SDimitry Andric } 2692fe013be4SDimitry Andric 2693fe013be4SDimitry Andric /// Find the operand of the GEP that should be checked for consecutive 2694fe013be4SDimitry Andric /// stores. This ignores trailing indices that have no effect on the final 2695fe013be4SDimitry Andric /// pointer. 2696fe013be4SDimitry Andric static unsigned getGEPInductionOperand(const GetElementPtrInst *Gep) { 2697fe013be4SDimitry Andric const DataLayout &DL = Gep->getModule()->getDataLayout(); 2698fe013be4SDimitry Andric unsigned LastOperand = Gep->getNumOperands() - 1; 2699fe013be4SDimitry Andric TypeSize GEPAllocSize = DL.getTypeAllocSize(Gep->getResultElementType()); 2700fe013be4SDimitry Andric 2701fe013be4SDimitry Andric // Walk backwards and try to peel off zeros. 2702fe013be4SDimitry Andric while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) { 2703fe013be4SDimitry Andric // Find the type we're currently indexing into. 2704fe013be4SDimitry Andric gep_type_iterator GEPTI = gep_type_begin(Gep); 2705fe013be4SDimitry Andric std::advance(GEPTI, LastOperand - 2); 2706fe013be4SDimitry Andric 2707fe013be4SDimitry Andric // If it's a type with the same allocation size as the result of the GEP we 2708fe013be4SDimitry Andric // can peel off the zero index. 2709cdc20ff6SDimitry Andric TypeSize ElemSize = GEPTI.isStruct() 2710cdc20ff6SDimitry Andric ? DL.getTypeAllocSize(GEPTI.getIndexedType()) 2711cdc20ff6SDimitry Andric : GEPTI.getSequentialElementStride(DL); 2712cdc20ff6SDimitry Andric if (ElemSize != GEPAllocSize) 2713fe013be4SDimitry Andric break; 2714fe013be4SDimitry Andric --LastOperand; 2715fe013be4SDimitry Andric } 2716fe013be4SDimitry Andric 2717fe013be4SDimitry Andric return LastOperand; 2718fe013be4SDimitry Andric } 2719fe013be4SDimitry Andric 2720fe013be4SDimitry Andric /// If the argument is a GEP, then returns the operand identified by 2721fe013be4SDimitry Andric /// getGEPInductionOperand. However, if there is some other non-loop-invariant 2722fe013be4SDimitry Andric /// operand, it returns that instead. 2723fe013be4SDimitry Andric static Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE, Loop *Lp) { 2724fe013be4SDimitry Andric GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 2725fe013be4SDimitry Andric if (!GEP) 2726fe013be4SDimitry Andric return Ptr; 2727fe013be4SDimitry Andric 2728fe013be4SDimitry Andric unsigned InductionOperand = getGEPInductionOperand(GEP); 2729fe013be4SDimitry Andric 2730fe013be4SDimitry Andric // Check that all of the gep indices are uniform except for our induction 2731fe013be4SDimitry Andric // operand. 2732fe013be4SDimitry Andric for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) 2733fe013be4SDimitry Andric if (i != InductionOperand && 2734fe013be4SDimitry Andric !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp)) 2735fe013be4SDimitry Andric return Ptr; 2736fe013be4SDimitry Andric return GEP->getOperand(InductionOperand); 2737fe013be4SDimitry Andric } 2738fe013be4SDimitry Andric 2739fe013be4SDimitry Andric /// If a value has only one user that is a CastInst, return it. 2740fe013be4SDimitry Andric static Value *getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) { 2741fe013be4SDimitry Andric Value *UniqueCast = nullptr; 2742fe013be4SDimitry Andric for (User *U : Ptr->users()) { 2743fe013be4SDimitry Andric CastInst *CI = dyn_cast<CastInst>(U); 2744fe013be4SDimitry Andric if (CI && CI->getType() == Ty) { 2745fe013be4SDimitry Andric if (!UniqueCast) 2746fe013be4SDimitry Andric UniqueCast = CI; 2747fe013be4SDimitry Andric else 2748fe013be4SDimitry Andric return nullptr; 2749fe013be4SDimitry Andric } 2750fe013be4SDimitry Andric } 2751fe013be4SDimitry Andric return UniqueCast; 2752fe013be4SDimitry Andric } 2753fe013be4SDimitry Andric 2754fe013be4SDimitry Andric /// Get the stride of a pointer access in a loop. Looks for symbolic 2755fe013be4SDimitry Andric /// strides "a[i*stride]". Returns the symbolic stride, or null otherwise. 2756fe013be4SDimitry Andric static const SCEV *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE, Loop *Lp) { 2757fe013be4SDimitry Andric auto *PtrTy = dyn_cast<PointerType>(Ptr->getType()); 2758fe013be4SDimitry Andric if (!PtrTy || PtrTy->isAggregateType()) 2759fe013be4SDimitry Andric return nullptr; 2760fe013be4SDimitry Andric 2761fe013be4SDimitry Andric // Try to remove a gep instruction to make the pointer (actually index at this 2762fe013be4SDimitry Andric // point) easier analyzable. If OrigPtr is equal to Ptr we are analyzing the 2763fe013be4SDimitry Andric // pointer, otherwise, we are analyzing the index. 2764fe013be4SDimitry Andric Value *OrigPtr = Ptr; 2765fe013be4SDimitry Andric 2766fe013be4SDimitry Andric // The size of the pointer access. 2767fe013be4SDimitry Andric int64_t PtrAccessSize = 1; 2768fe013be4SDimitry Andric 2769fe013be4SDimitry Andric Ptr = stripGetElementPtr(Ptr, SE, Lp); 2770fe013be4SDimitry Andric const SCEV *V = SE->getSCEV(Ptr); 2771fe013be4SDimitry Andric 2772fe013be4SDimitry Andric if (Ptr != OrigPtr) 2773fe013be4SDimitry Andric // Strip off casts. 2774fe013be4SDimitry Andric while (const SCEVIntegralCastExpr *C = dyn_cast<SCEVIntegralCastExpr>(V)) 2775fe013be4SDimitry Andric V = C->getOperand(); 2776fe013be4SDimitry Andric 2777fe013be4SDimitry Andric const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V); 2778fe013be4SDimitry Andric if (!S) 2779fe013be4SDimitry Andric return nullptr; 2780fe013be4SDimitry Andric 2781fe013be4SDimitry Andric // If the pointer is invariant then there is no stride and it makes no 2782fe013be4SDimitry Andric // sense to add it here. 2783fe013be4SDimitry Andric if (Lp != S->getLoop()) 2784fe013be4SDimitry Andric return nullptr; 2785fe013be4SDimitry Andric 2786fe013be4SDimitry Andric V = S->getStepRecurrence(*SE); 2787fe013be4SDimitry Andric if (!V) 2788fe013be4SDimitry Andric return nullptr; 2789fe013be4SDimitry Andric 2790fe013be4SDimitry Andric // Strip off the size of access multiplication if we are still analyzing the 2791fe013be4SDimitry Andric // pointer. 2792fe013be4SDimitry Andric if (OrigPtr == Ptr) { 2793fe013be4SDimitry Andric if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) { 2794fe013be4SDimitry Andric if (M->getOperand(0)->getSCEVType() != scConstant) 2795fe013be4SDimitry Andric return nullptr; 2796fe013be4SDimitry Andric 2797fe013be4SDimitry Andric const APInt &APStepVal = cast<SCEVConstant>(M->getOperand(0))->getAPInt(); 2798fe013be4SDimitry Andric 2799fe013be4SDimitry Andric // Huge step value - give up. 2800fe013be4SDimitry Andric if (APStepVal.getBitWidth() > 64) 2801fe013be4SDimitry Andric return nullptr; 2802fe013be4SDimitry Andric 2803fe013be4SDimitry Andric int64_t StepVal = APStepVal.getSExtValue(); 2804fe013be4SDimitry Andric if (PtrAccessSize != StepVal) 2805fe013be4SDimitry Andric return nullptr; 2806fe013be4SDimitry Andric V = M->getOperand(1); 2807fe013be4SDimitry Andric } 2808fe013be4SDimitry Andric } 2809fe013be4SDimitry Andric 2810fe013be4SDimitry Andric // Note that the restriction after this loop invariant check are only 2811fe013be4SDimitry Andric // profitability restrictions. 2812fe013be4SDimitry Andric if (!SE->isLoopInvariant(V, Lp)) 2813fe013be4SDimitry Andric return nullptr; 2814fe013be4SDimitry Andric 2815fe013be4SDimitry Andric // Look for the loop invariant symbolic value. 2816fe013be4SDimitry Andric const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V); 2817fe013be4SDimitry Andric if (!U) { 2818fe013be4SDimitry Andric const auto *C = dyn_cast<SCEVIntegralCastExpr>(V); 2819fe013be4SDimitry Andric if (!C) 2820fe013be4SDimitry Andric return nullptr; 2821fe013be4SDimitry Andric U = dyn_cast<SCEVUnknown>(C->getOperand()); 2822fe013be4SDimitry Andric if (!U) 2823fe013be4SDimitry Andric return nullptr; 2824fe013be4SDimitry Andric 2825fe013be4SDimitry Andric // Match legacy behavior - this is not needed for correctness 2826fe013be4SDimitry Andric if (!getUniqueCastUse(U->getValue(), Lp, V->getType())) 2827fe013be4SDimitry Andric return nullptr; 2828fe013be4SDimitry Andric } 2829fe013be4SDimitry Andric 2830fe013be4SDimitry Andric return V; 28310b57cec5SDimitry Andric } 28320b57cec5SDimitry Andric 28330b57cec5SDimitry Andric void LoopAccessInfo::collectStridedAccess(Value *MemAccess) { 2834e8d8bef9SDimitry Andric Value *Ptr = getLoadStorePointerOperand(MemAccess); 2835e8d8bef9SDimitry Andric if (!Ptr) 28360b57cec5SDimitry Andric return; 28370b57cec5SDimitry Andric 2838fe013be4SDimitry Andric // Note: getStrideFromPointer is a *profitability* heuristic. We 2839fe013be4SDimitry Andric // could broaden the scope of values returned here - to anything 2840fe013be4SDimitry Andric // which happens to be loop invariant and contributes to the 2841fe013be4SDimitry Andric // computation of an interesting IV - but we chose not to as we 2842fe013be4SDimitry Andric // don't have a cost model here, and broadening the scope exposes 2843fe013be4SDimitry Andric // far too many unprofitable cases. 2844fe013be4SDimitry Andric const SCEV *StrideExpr = getStrideFromPointer(Ptr, PSE->getSE(), TheLoop); 2845fe013be4SDimitry Andric if (!StrideExpr) 28460b57cec5SDimitry Andric return; 28470b57cec5SDimitry Andric 28480b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Found a strided access that is a candidate for " 28490b57cec5SDimitry Andric "versioning:"); 2850fe013be4SDimitry Andric LLVM_DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *StrideExpr << "\n"); 2851fe013be4SDimitry Andric 2852fe013be4SDimitry Andric if (!SpeculateUnitStride) { 2853fe013be4SDimitry Andric LLVM_DEBUG(dbgs() << " Chose not to due to -laa-speculate-unit-stride\n"); 2854fe013be4SDimitry Andric return; 2855fe013be4SDimitry Andric } 28560b57cec5SDimitry Andric 28570b57cec5SDimitry Andric // Avoid adding the "Stride == 1" predicate when we know that 28580b57cec5SDimitry Andric // Stride >= Trip-Count. Such a predicate will effectively optimize a single 28590b57cec5SDimitry Andric // or zero iteration loop, as Trip-Count <= Stride == 1. 28600b57cec5SDimitry Andric // 28610b57cec5SDimitry Andric // TODO: We are currently not making a very informed decision on when it is 28620b57cec5SDimitry Andric // beneficial to apply stride versioning. It might make more sense that the 28630b57cec5SDimitry Andric // users of this analysis (such as the vectorizer) will trigger it, based on 28640b57cec5SDimitry Andric // their specific cost considerations; For example, in cases where stride 28650b57cec5SDimitry Andric // versioning does not help resolving memory accesses/dependences, the 28660b57cec5SDimitry Andric // vectorizer should evaluate the cost of the runtime test, and the benefit 28670b57cec5SDimitry Andric // of various possible stride specializations, considering the alternatives 28680b57cec5SDimitry Andric // of using gather/scatters (if available). 28690b57cec5SDimitry Andric 28700b57cec5SDimitry Andric const SCEV *BETakenCount = PSE->getBackedgeTakenCount(); 28710b57cec5SDimitry Andric 28720b57cec5SDimitry Andric // Match the types so we can compare the stride and the BETakenCount. 28730b57cec5SDimitry Andric // The Stride can be positive/negative, so we sign extend Stride; 28740b57cec5SDimitry Andric // The backedgeTakenCount is non-negative, so we zero extend BETakenCount. 28750b57cec5SDimitry Andric const DataLayout &DL = TheLoop->getHeader()->getModule()->getDataLayout(); 287681ad6265SDimitry Andric uint64_t StrideTypeSizeBits = DL.getTypeSizeInBits(StrideExpr->getType()); 287781ad6265SDimitry Andric uint64_t BETypeSizeBits = DL.getTypeSizeInBits(BETakenCount->getType()); 28780b57cec5SDimitry Andric const SCEV *CastedStride = StrideExpr; 28790b57cec5SDimitry Andric const SCEV *CastedBECount = BETakenCount; 28800b57cec5SDimitry Andric ScalarEvolution *SE = PSE->getSE(); 288181ad6265SDimitry Andric if (BETypeSizeBits >= StrideTypeSizeBits) 28820b57cec5SDimitry Andric CastedStride = SE->getNoopOrSignExtend(StrideExpr, BETakenCount->getType()); 28830b57cec5SDimitry Andric else 28840b57cec5SDimitry Andric CastedBECount = SE->getZeroExtendExpr(BETakenCount, StrideExpr->getType()); 28850b57cec5SDimitry Andric const SCEV *StrideMinusBETaken = SE->getMinusSCEV(CastedStride, CastedBECount); 28860b57cec5SDimitry Andric // Since TripCount == BackEdgeTakenCount + 1, checking: 28870b57cec5SDimitry Andric // "Stride >= TripCount" is equivalent to checking: 28880b57cec5SDimitry Andric // Stride - BETakenCount > 0 28890b57cec5SDimitry Andric if (SE->isKnownPositive(StrideMinusBETaken)) { 28900b57cec5SDimitry Andric LLVM_DEBUG( 28910b57cec5SDimitry Andric dbgs() << "LAA: Stride>=TripCount; No point in versioning as the " 28920b57cec5SDimitry Andric "Stride==1 predicate will imply that the loop executes " 28930b57cec5SDimitry Andric "at most once.\n"); 28940b57cec5SDimitry Andric return; 28950b57cec5SDimitry Andric } 289681ad6265SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Found a strided access that we can version.\n"); 28970b57cec5SDimitry Andric 2898fe013be4SDimitry Andric // Strip back off the integer cast, and check that our result is a 2899fe013be4SDimitry Andric // SCEVUnknown as we expect. 2900fe013be4SDimitry Andric const SCEV *StrideBase = StrideExpr; 2901fe013be4SDimitry Andric if (const auto *C = dyn_cast<SCEVIntegralCastExpr>(StrideBase)) 2902fe013be4SDimitry Andric StrideBase = C->getOperand(); 2903fe013be4SDimitry Andric SymbolicStrides[Ptr] = cast<SCEVUnknown>(StrideBase); 29040b57cec5SDimitry Andric } 29050b57cec5SDimitry Andric 29060b57cec5SDimitry Andric LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE, 29075ffd83dbSDimitry Andric const TargetLibraryInfo *TLI, AAResults *AA, 29080b57cec5SDimitry Andric DominatorTree *DT, LoopInfo *LI) 29098bcb0991SDimitry Andric : PSE(std::make_unique<PredicatedScalarEvolution>(*SE, *L)), 291081ad6265SDimitry Andric PtrRtChecking(nullptr), 291104eeddc0SDimitry Andric DepChecker(std::make_unique<MemoryDepChecker>(*PSE, L)), TheLoop(L) { 291281ad6265SDimitry Andric PtrRtChecking = std::make_unique<RuntimePointerChecking>(*DepChecker, SE); 291381ad6265SDimitry Andric if (canAnalyzeLoop()) { 29140b57cec5SDimitry Andric analyzeLoop(AA, LI, TLI, DT); 29150b57cec5SDimitry Andric } 291681ad6265SDimitry Andric } 29170b57cec5SDimitry Andric 29180b57cec5SDimitry Andric void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const { 29190b57cec5SDimitry Andric if (CanVecMem) { 29200b57cec5SDimitry Andric OS.indent(Depth) << "Memory dependences are safe"; 2921c9157d92SDimitry Andric const MemoryDepChecker &DC = getDepChecker(); 2922c9157d92SDimitry Andric if (!DC.isSafeForAnyVectorWidth()) 2923c9157d92SDimitry Andric OS << " with a maximum safe vector width of " 2924c9157d92SDimitry Andric << DC.getMaxSafeVectorWidthInBits() << " bits"; 29250b57cec5SDimitry Andric if (PtrRtChecking->Need) 29260b57cec5SDimitry Andric OS << " with run-time checks"; 29270b57cec5SDimitry Andric OS << "\n"; 29280b57cec5SDimitry Andric } 29290b57cec5SDimitry Andric 29300b57cec5SDimitry Andric if (HasConvergentOp) 29310b57cec5SDimitry Andric OS.indent(Depth) << "Has convergent operation in loop\n"; 29320b57cec5SDimitry Andric 29330b57cec5SDimitry Andric if (Report) 29340b57cec5SDimitry Andric OS.indent(Depth) << "Report: " << Report->getMsg() << "\n"; 29350b57cec5SDimitry Andric 29360b57cec5SDimitry Andric if (auto *Dependences = DepChecker->getDependences()) { 29370b57cec5SDimitry Andric OS.indent(Depth) << "Dependences:\n"; 2938fcaf7f86SDimitry Andric for (const auto &Dep : *Dependences) { 29390b57cec5SDimitry Andric Dep.print(OS, Depth + 2, DepChecker->getMemoryInstructions()); 29400b57cec5SDimitry Andric OS << "\n"; 29410b57cec5SDimitry Andric } 29420b57cec5SDimitry Andric } else 29430b57cec5SDimitry Andric OS.indent(Depth) << "Too many dependences, not recorded\n"; 29440b57cec5SDimitry Andric 29450b57cec5SDimitry Andric // List the pair of accesses need run-time checks to prove independence. 29460b57cec5SDimitry Andric PtrRtChecking->print(OS, Depth); 29470b57cec5SDimitry Andric OS << "\n"; 29480b57cec5SDimitry Andric 29490b57cec5SDimitry Andric OS.indent(Depth) << "Non vectorizable stores to invariant address were " 29500b57cec5SDimitry Andric << (HasDependenceInvolvingLoopInvariantAddress ? "" : "not ") 29510b57cec5SDimitry Andric << "found in loop.\n"; 29520b57cec5SDimitry Andric 29530b57cec5SDimitry Andric OS.indent(Depth) << "SCEV assumptions:\n"; 295481ad6265SDimitry Andric PSE->getPredicate().print(OS, Depth); 29550b57cec5SDimitry Andric 29560b57cec5SDimitry Andric OS << "\n"; 29570b57cec5SDimitry Andric 29580b57cec5SDimitry Andric OS.indent(Depth) << "Expressions re-written:\n"; 29590b57cec5SDimitry Andric PSE->print(OS, Depth); 29600b57cec5SDimitry Andric } 29610b57cec5SDimitry Andric 2962bdd1243dSDimitry Andric const LoopAccessInfo &LoopAccessInfoManager::getInfo(Loop &L) { 2963bdd1243dSDimitry Andric auto I = LoopAccessInfoMap.insert({&L, nullptr}); 2964bdd1243dSDimitry Andric 2965bdd1243dSDimitry Andric if (I.second) 2966bdd1243dSDimitry Andric I.first->second = 2967bdd1243dSDimitry Andric std::make_unique<LoopAccessInfo>(&L, &SE, TLI, &AA, &DT, &LI); 2968bdd1243dSDimitry Andric 2969bdd1243dSDimitry Andric return *I.first->second; 2970bdd1243dSDimitry Andric } 2971bdd1243dSDimitry Andric 2972fe013be4SDimitry Andric bool LoopAccessInfoManager::invalidate( 2973fe013be4SDimitry Andric Function &F, const PreservedAnalyses &PA, 2974fe013be4SDimitry Andric FunctionAnalysisManager::Invalidator &Inv) { 2975fe013be4SDimitry Andric // Check whether our analysis is preserved. 2976fe013be4SDimitry Andric auto PAC = PA.getChecker<LoopAccessAnalysis>(); 2977fe013be4SDimitry Andric if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<Function>>()) 2978fe013be4SDimitry Andric // If not, give up now. 2979fe013be4SDimitry Andric return true; 2980480093f4SDimitry Andric 2981fe013be4SDimitry Andric // Check whether the analyses we depend on became invalid for any reason. 2982fe013be4SDimitry Andric // Skip checking TargetLibraryAnalysis as it is immutable and can't become 2983fe013be4SDimitry Andric // invalid. 2984fe013be4SDimitry Andric return Inv.invalidate<AAManager>(F, PA) || 2985fe013be4SDimitry Andric Inv.invalidate<ScalarEvolutionAnalysis>(F, PA) || 2986fe013be4SDimitry Andric Inv.invalidate<LoopAnalysis>(F, PA) || 2987fe013be4SDimitry Andric Inv.invalidate<DominatorTreeAnalysis>(F, PA); 29880b57cec5SDimitry Andric } 29890b57cec5SDimitry Andric 2990bdd1243dSDimitry Andric LoopAccessInfoManager LoopAccessAnalysis::run(Function &F, 2991fe013be4SDimitry Andric FunctionAnalysisManager &FAM) { 2992fe013be4SDimitry Andric auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F); 2993fe013be4SDimitry Andric auto &AA = FAM.getResult<AAManager>(F); 2994fe013be4SDimitry Andric auto &DT = FAM.getResult<DominatorTreeAnalysis>(F); 2995fe013be4SDimitry Andric auto &LI = FAM.getResult<LoopAnalysis>(F); 2996fe013be4SDimitry Andric auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F); 2997fe013be4SDimitry Andric return LoopAccessInfoManager(SE, AA, DT, LI, &TLI); 2998bdd1243dSDimitry Andric } 2999bdd1243dSDimitry Andric 30000b57cec5SDimitry Andric AnalysisKey LoopAccessAnalysis::Key; 3001