Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1 | //===- LoopAccessAnalysis.cpp - Loop Access Analysis Implementation --------==// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // The implementation for the loop memory dependence that was originally |
| 11 | // developed for the loop vectorizer. |
| 12 | // |
| 13 | //===----------------------------------------------------------------------===// |
| 14 | |
| 15 | #include "llvm/Analysis/LoopAccessAnalysis.h" |
| 16 | #include "llvm/Analysis/LoopInfo.h" |
Adam Nemet | 7206d7a | 2015-02-06 18:31:04 +0000 | [diff] [blame] | 17 | #include "llvm/Analysis/ScalarEvolutionExpander.h" |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 18 | #include "llvm/Analysis/ValueTracking.h" |
| 19 | #include "llvm/IR/DiagnosticInfo.h" |
| 20 | #include "llvm/IR/Dominators.h" |
Adam Nemet | 7206d7a | 2015-02-06 18:31:04 +0000 | [diff] [blame] | 21 | #include "llvm/IR/IRBuilder.h" |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 22 | #include "llvm/Support/Debug.h" |
| 23 | #include "llvm/Transforms/Utils/VectorUtils.h" |
| 24 | using namespace llvm; |
| 25 | |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 26 | #define DEBUG_TYPE "loop-accesses" |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 27 | |
Adam Nemet | f219c64 | 2015-02-19 19:14:52 +0000 | [diff] [blame] | 28 | static cl::opt<unsigned, true> |
| 29 | VectorizationFactor("force-vector-width", cl::Hidden, |
| 30 | cl::desc("Sets the SIMD width. Zero is autoselect."), |
| 31 | cl::location(VectorizerParams::VectorizationFactor)); |
| 32 | unsigned VectorizerParams::VectorizationFactor = 0; |
| 33 | |
| 34 | static cl::opt<unsigned, true> |
| 35 | VectorizationInterleave("force-vector-interleave", cl::Hidden, |
| 36 | cl::desc("Sets the vectorization interleave count. " |
| 37 | "Zero is autoselect."), |
| 38 | cl::location( |
| 39 | VectorizerParams::VectorizationInterleave)); |
| 40 | unsigned VectorizerParams::VectorizationInterleave = 0; |
| 41 | |
| 42 | /// When performing memory disambiguation checks at runtime do not make more |
| 43 | /// than this number of comparisons. |
| 44 | const unsigned VectorizerParams::RuntimeMemoryCheckThreshold = 8; |
| 45 | |
| 46 | /// Maximum SIMD width. |
| 47 | const unsigned VectorizerParams::MaxVectorWidth = 64; |
| 48 | |
| 49 | bool VectorizerParams::isInterleaveForced() { |
| 50 | return ::VectorizationInterleave.getNumOccurrences() > 0; |
| 51 | } |
| 52 | |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 53 | void VectorizationReport::emitAnalysis(VectorizationReport &Message, |
| 54 | const Function *TheFunction, |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 55 | const Loop *TheLoop, |
| 56 | const char *PassName) { |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 57 | DebugLoc DL = TheLoop->getStartLoc(); |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 58 | if (Instruction *I = Message.getInstr()) |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 59 | DL = I->getDebugLoc(); |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 60 | emitOptimizationRemarkAnalysis(TheFunction->getContext(), PassName, |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 61 | *TheFunction, DL, Message.str()); |
| 62 | } |
| 63 | |
| 64 | Value *llvm::stripIntegerCast(Value *V) { |
| 65 | if (CastInst *CI = dyn_cast<CastInst>(V)) |
| 66 | if (CI->getOperand(0)->getType()->isIntegerTy()) |
| 67 | return CI->getOperand(0); |
| 68 | return V; |
| 69 | } |
| 70 | |
| 71 | const SCEV *llvm::replaceSymbolicStrideSCEV(ScalarEvolution *SE, |
| 72 | ValueToValueMap &PtrToStride, |
| 73 | Value *Ptr, Value *OrigPtr) { |
| 74 | |
| 75 | const SCEV *OrigSCEV = SE->getSCEV(Ptr); |
| 76 | |
| 77 | // If there is an entry in the map return the SCEV of the pointer with the |
| 78 | // symbolic stride replaced by one. |
| 79 | ValueToValueMap::iterator SI = PtrToStride.find(OrigPtr ? OrigPtr : Ptr); |
| 80 | if (SI != PtrToStride.end()) { |
| 81 | Value *StrideVal = SI->second; |
| 82 | |
| 83 | // Strip casts. |
| 84 | StrideVal = stripIntegerCast(StrideVal); |
| 85 | |
| 86 | // Replace symbolic stride by one. |
| 87 | Value *One = ConstantInt::get(StrideVal->getType(), 1); |
| 88 | ValueToValueMap RewriteMap; |
| 89 | RewriteMap[StrideVal] = One; |
| 90 | |
| 91 | const SCEV *ByOne = |
| 92 | SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true); |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 93 | DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 94 | << "\n"); |
| 95 | return ByOne; |
| 96 | } |
| 97 | |
| 98 | // Otherwise, just return the SCEV of the original pointer. |
| 99 | return SE->getSCEV(Ptr); |
| 100 | } |
| 101 | |
Adam Nemet | 30f16e1 | 2015-02-18 03:42:35 +0000 | [diff] [blame] | 102 | void LoopAccessInfo::RuntimePointerCheck::insert(ScalarEvolution *SE, Loop *Lp, |
| 103 | Value *Ptr, bool WritePtr, |
| 104 | unsigned DepSetId, |
| 105 | unsigned ASId, |
| 106 | ValueToValueMap &Strides) { |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 107 | // Get the stride replaced scev. |
| 108 | const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr); |
| 109 | const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc); |
| 110 | assert(AR && "Invalid addrec expression"); |
| 111 | const SCEV *Ex = SE->getBackedgeTakenCount(Lp); |
| 112 | const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE); |
| 113 | Pointers.push_back(Ptr); |
| 114 | Starts.push_back(AR->getStart()); |
| 115 | Ends.push_back(ScEnd); |
| 116 | IsWritePtr.push_back(WritePtr); |
| 117 | DependencySetId.push_back(DepSetId); |
| 118 | AliasSetId.push_back(ASId); |
| 119 | } |
| 120 | |
Adam Nemet | a8945b7 | 2015-02-18 03:43:58 +0000 | [diff] [blame] | 121 | bool LoopAccessInfo::RuntimePointerCheck::needsChecking(unsigned I, |
| 122 | unsigned J) const { |
| 123 | // No need to check if two readonly pointers intersect. |
| 124 | if (!IsWritePtr[I] && !IsWritePtr[J]) |
| 125 | return false; |
| 126 | |
| 127 | // Only need to check pointers between two different dependency sets. |
| 128 | if (DependencySetId[I] == DependencySetId[J]) |
| 129 | return false; |
| 130 | |
| 131 | // Only need to check pointers in the same alias set. |
| 132 | if (AliasSetId[I] != AliasSetId[J]) |
| 133 | return false; |
| 134 | |
| 135 | return true; |
| 136 | } |
| 137 | |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 138 | namespace { |
| 139 | /// \brief Analyses memory accesses in a loop. |
| 140 | /// |
| 141 | /// Checks whether run time pointer checks are needed and builds sets for data |
| 142 | /// dependence checking. |
| 143 | class AccessAnalysis { |
| 144 | public: |
| 145 | /// \brief Read or write access location. |
| 146 | typedef PointerIntPair<Value *, 1, bool> MemAccessInfo; |
| 147 | typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet; |
| 148 | |
| 149 | /// \brief Set of potential dependent memory accesses. |
| 150 | typedef EquivalenceClasses<MemAccessInfo> DepCandidates; |
| 151 | |
| 152 | AccessAnalysis(const DataLayout *Dl, AliasAnalysis *AA, DepCandidates &DA) : |
| 153 | DL(Dl), AST(*AA), DepCands(DA), IsRTCheckNeeded(false) {} |
| 154 | |
| 155 | /// \brief Register a load and whether it is only read from. |
| 156 | void addLoad(AliasAnalysis::Location &Loc, bool IsReadOnly) { |
| 157 | Value *Ptr = const_cast<Value*>(Loc.Ptr); |
| 158 | AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags); |
| 159 | Accesses.insert(MemAccessInfo(Ptr, false)); |
| 160 | if (IsReadOnly) |
| 161 | ReadOnlyPtr.insert(Ptr); |
| 162 | } |
| 163 | |
| 164 | /// \brief Register a store. |
| 165 | void addStore(AliasAnalysis::Location &Loc) { |
| 166 | Value *Ptr = const_cast<Value*>(Loc.Ptr); |
| 167 | AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags); |
| 168 | Accesses.insert(MemAccessInfo(Ptr, true)); |
| 169 | } |
| 170 | |
| 171 | /// \brief Check whether we can check the pointers at runtime for |
| 172 | /// non-intersection. |
Adam Nemet | 30f16e1 | 2015-02-18 03:42:35 +0000 | [diff] [blame] | 173 | bool canCheckPtrAtRT(LoopAccessInfo::RuntimePointerCheck &RtCheck, |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 174 | unsigned &NumComparisons, |
| 175 | ScalarEvolution *SE, Loop *TheLoop, |
| 176 | ValueToValueMap &Strides, |
| 177 | bool ShouldCheckStride = false); |
| 178 | |
| 179 | /// \brief Goes over all memory accesses, checks whether a RT check is needed |
| 180 | /// and builds sets of dependent accesses. |
| 181 | void buildDependenceSets() { |
| 182 | processMemAccesses(); |
| 183 | } |
| 184 | |
| 185 | bool isRTCheckNeeded() { return IsRTCheckNeeded; } |
| 186 | |
| 187 | bool isDependencyCheckNeeded() { return !CheckDeps.empty(); } |
| 188 | void resetDepChecks() { CheckDeps.clear(); } |
| 189 | |
| 190 | MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; } |
| 191 | |
| 192 | private: |
| 193 | typedef SetVector<MemAccessInfo> PtrAccessSet; |
| 194 | |
| 195 | /// \brief Go over all memory access and check whether runtime pointer checks |
| 196 | /// are needed /// and build sets of dependency check candidates. |
| 197 | void processMemAccesses(); |
| 198 | |
| 199 | /// Set of all accesses. |
| 200 | PtrAccessSet Accesses; |
| 201 | |
| 202 | /// Set of accesses that need a further dependence check. |
| 203 | MemAccessInfoSet CheckDeps; |
| 204 | |
| 205 | /// Set of pointers that are read only. |
| 206 | SmallPtrSet<Value*, 16> ReadOnlyPtr; |
| 207 | |
| 208 | const DataLayout *DL; |
| 209 | |
| 210 | /// An alias set tracker to partition the access set by underlying object and |
| 211 | //intrinsic property (such as TBAA metadata). |
| 212 | AliasSetTracker AST; |
| 213 | |
| 214 | /// Sets of potentially dependent accesses - members of one set share an |
| 215 | /// underlying pointer. The set "CheckDeps" identfies which sets really need a |
| 216 | /// dependence check. |
| 217 | DepCandidates &DepCands; |
| 218 | |
| 219 | bool IsRTCheckNeeded; |
| 220 | }; |
| 221 | |
| 222 | } // end anonymous namespace |
| 223 | |
| 224 | /// \brief Check whether a pointer can participate in a runtime bounds check. |
| 225 | static bool hasComputableBounds(ScalarEvolution *SE, ValueToValueMap &Strides, |
| 226 | Value *Ptr) { |
| 227 | const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr); |
| 228 | const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev); |
| 229 | if (!AR) |
| 230 | return false; |
| 231 | |
| 232 | return AR->isAffine(); |
| 233 | } |
| 234 | |
| 235 | /// \brief Check the stride of the pointer and ensure that it does not wrap in |
| 236 | /// the address space. |
| 237 | static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr, |
| 238 | const Loop *Lp, ValueToValueMap &StridesMap); |
| 239 | |
| 240 | bool AccessAnalysis::canCheckPtrAtRT( |
Adam Nemet | 30f16e1 | 2015-02-18 03:42:35 +0000 | [diff] [blame] | 241 | LoopAccessInfo::RuntimePointerCheck &RtCheck, |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 242 | unsigned &NumComparisons, ScalarEvolution *SE, Loop *TheLoop, |
| 243 | ValueToValueMap &StridesMap, bool ShouldCheckStride) { |
| 244 | // Find pointers with computable bounds. We are going to use this information |
| 245 | // to place a runtime bound check. |
| 246 | bool CanDoRT = true; |
| 247 | |
| 248 | bool IsDepCheckNeeded = isDependencyCheckNeeded(); |
| 249 | NumComparisons = 0; |
| 250 | |
| 251 | // We assign a consecutive id to access from different alias sets. |
| 252 | // Accesses between different groups doesn't need to be checked. |
| 253 | unsigned ASId = 1; |
| 254 | for (auto &AS : AST) { |
| 255 | unsigned NumReadPtrChecks = 0; |
| 256 | unsigned NumWritePtrChecks = 0; |
| 257 | |
| 258 | // We assign consecutive id to access from different dependence sets. |
| 259 | // Accesses within the same set don't need a runtime check. |
| 260 | unsigned RunningDepId = 1; |
| 261 | DenseMap<Value *, unsigned> DepSetId; |
| 262 | |
| 263 | for (auto A : AS) { |
| 264 | Value *Ptr = A.getValue(); |
| 265 | bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true)); |
| 266 | MemAccessInfo Access(Ptr, IsWrite); |
| 267 | |
| 268 | if (IsWrite) |
| 269 | ++NumWritePtrChecks; |
| 270 | else |
| 271 | ++NumReadPtrChecks; |
| 272 | |
| 273 | if (hasComputableBounds(SE, StridesMap, Ptr) && |
| 274 | // When we run after a failing dependency check we have to make sure we |
| 275 | // don't have wrapping pointers. |
| 276 | (!ShouldCheckStride || |
| 277 | isStridedPtr(SE, DL, Ptr, TheLoop, StridesMap) == 1)) { |
| 278 | // The id of the dependence set. |
| 279 | unsigned DepId; |
| 280 | |
| 281 | if (IsDepCheckNeeded) { |
| 282 | Value *Leader = DepCands.getLeaderValue(Access).getPointer(); |
| 283 | unsigned &LeaderId = DepSetId[Leader]; |
| 284 | if (!LeaderId) |
| 285 | LeaderId = RunningDepId++; |
| 286 | DepId = LeaderId; |
| 287 | } else |
| 288 | // Each access has its own dependence set. |
| 289 | DepId = RunningDepId++; |
| 290 | |
| 291 | RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap); |
| 292 | |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 293 | DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n'); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 294 | } else { |
| 295 | CanDoRT = false; |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2) |
| 300 | NumComparisons += 0; // Only one dependence set. |
| 301 | else { |
| 302 | NumComparisons += (NumWritePtrChecks * (NumReadPtrChecks + |
| 303 | NumWritePtrChecks - 1)); |
| 304 | } |
| 305 | |
| 306 | ++ASId; |
| 307 | } |
| 308 | |
| 309 | // If the pointers that we would use for the bounds comparison have different |
| 310 | // address spaces, assume the values aren't directly comparable, so we can't |
| 311 | // use them for the runtime check. We also have to assume they could |
| 312 | // overlap. In the future there should be metadata for whether address spaces |
| 313 | // are disjoint. |
| 314 | unsigned NumPointers = RtCheck.Pointers.size(); |
| 315 | for (unsigned i = 0; i < NumPointers; ++i) { |
| 316 | for (unsigned j = i + 1; j < NumPointers; ++j) { |
| 317 | // Only need to check pointers between two different dependency sets. |
| 318 | if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j]) |
| 319 | continue; |
| 320 | // Only need to check pointers in the same alias set. |
| 321 | if (RtCheck.AliasSetId[i] != RtCheck.AliasSetId[j]) |
| 322 | continue; |
| 323 | |
| 324 | Value *PtrI = RtCheck.Pointers[i]; |
| 325 | Value *PtrJ = RtCheck.Pointers[j]; |
| 326 | |
| 327 | unsigned ASi = PtrI->getType()->getPointerAddressSpace(); |
| 328 | unsigned ASj = PtrJ->getType()->getPointerAddressSpace(); |
| 329 | if (ASi != ASj) { |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 330 | DEBUG(dbgs() << "LAA: Runtime check would require comparison between" |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 331 | " different address spaces\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 332 | return false; |
| 333 | } |
| 334 | } |
| 335 | } |
| 336 | |
| 337 | return CanDoRT; |
| 338 | } |
| 339 | |
| 340 | void AccessAnalysis::processMemAccesses() { |
| 341 | // We process the set twice: first we process read-write pointers, last we |
| 342 | // process read-only pointers. This allows us to skip dependence tests for |
| 343 | // read-only pointers. |
| 344 | |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 345 | DEBUG(dbgs() << "LAA: Processing memory accesses...\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 346 | DEBUG(dbgs() << " AST: "; AST.dump()); |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 347 | DEBUG(dbgs() << "LAA: Accesses:\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 348 | DEBUG({ |
| 349 | for (auto A : Accesses) |
| 350 | dbgs() << "\t" << *A.getPointer() << " (" << |
| 351 | (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ? |
| 352 | "read-only" : "read")) << ")\n"; |
| 353 | }); |
| 354 | |
| 355 | // The AliasSetTracker has nicely partitioned our pointers by metadata |
| 356 | // compatibility and potential for underlying-object overlap. As a result, we |
| 357 | // only need to check for potential pointer dependencies within each alias |
| 358 | // set. |
| 359 | for (auto &AS : AST) { |
| 360 | // Note that both the alias-set tracker and the alias sets themselves used |
| 361 | // linked lists internally and so the iteration order here is deterministic |
| 362 | // (matching the original instruction order within each set). |
| 363 | |
| 364 | bool SetHasWrite = false; |
| 365 | |
| 366 | // Map of pointers to last access encountered. |
| 367 | typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap; |
| 368 | UnderlyingObjToAccessMap ObjToLastAccess; |
| 369 | |
| 370 | // Set of access to check after all writes have been processed. |
| 371 | PtrAccessSet DeferredAccesses; |
| 372 | |
| 373 | // Iterate over each alias set twice, once to process read/write pointers, |
| 374 | // and then to process read-only pointers. |
| 375 | for (int SetIteration = 0; SetIteration < 2; ++SetIteration) { |
| 376 | bool UseDeferred = SetIteration > 0; |
| 377 | PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses; |
| 378 | |
| 379 | for (auto AV : AS) { |
| 380 | Value *Ptr = AV.getValue(); |
| 381 | |
| 382 | // For a single memory access in AliasSetTracker, Accesses may contain |
| 383 | // both read and write, and they both need to be handled for CheckDeps. |
| 384 | for (auto AC : S) { |
| 385 | if (AC.getPointer() != Ptr) |
| 386 | continue; |
| 387 | |
| 388 | bool IsWrite = AC.getInt(); |
| 389 | |
| 390 | // If we're using the deferred access set, then it contains only |
| 391 | // reads. |
| 392 | bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite; |
| 393 | if (UseDeferred && !IsReadOnlyPtr) |
| 394 | continue; |
| 395 | // Otherwise, the pointer must be in the PtrAccessSet, either as a |
| 396 | // read or a write. |
| 397 | assert(((IsReadOnlyPtr && UseDeferred) || IsWrite || |
| 398 | S.count(MemAccessInfo(Ptr, false))) && |
| 399 | "Alias-set pointer not in the access set?"); |
| 400 | |
| 401 | MemAccessInfo Access(Ptr, IsWrite); |
| 402 | DepCands.insert(Access); |
| 403 | |
| 404 | // Memorize read-only pointers for later processing and skip them in |
| 405 | // the first round (they need to be checked after we have seen all |
| 406 | // write pointers). Note: we also mark pointer that are not |
| 407 | // consecutive as "read-only" pointers (so that we check |
| 408 | // "a[b[i]] +="). Hence, we need the second check for "!IsWrite". |
| 409 | if (!UseDeferred && IsReadOnlyPtr) { |
| 410 | DeferredAccesses.insert(Access); |
| 411 | continue; |
| 412 | } |
| 413 | |
| 414 | // If this is a write - check other reads and writes for conflicts. If |
| 415 | // this is a read only check other writes for conflicts (but only if |
| 416 | // there is no other write to the ptr - this is an optimization to |
| 417 | // catch "a[i] = a[i] + " without having to do a dependence check). |
| 418 | if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) { |
| 419 | CheckDeps.insert(Access); |
| 420 | IsRTCheckNeeded = true; |
| 421 | } |
| 422 | |
| 423 | if (IsWrite) |
| 424 | SetHasWrite = true; |
| 425 | |
| 426 | // Create sets of pointers connected by a shared alias set and |
| 427 | // underlying object. |
| 428 | typedef SmallVector<Value *, 16> ValueVector; |
| 429 | ValueVector TempObjects; |
| 430 | GetUnderlyingObjects(Ptr, TempObjects, DL); |
| 431 | for (Value *UnderlyingObj : TempObjects) { |
| 432 | UnderlyingObjToAccessMap::iterator Prev = |
| 433 | ObjToLastAccess.find(UnderlyingObj); |
| 434 | if (Prev != ObjToLastAccess.end()) |
| 435 | DepCands.unionSets(Access, Prev->second); |
| 436 | |
| 437 | ObjToLastAccess[UnderlyingObj] = Access; |
| 438 | } |
| 439 | } |
| 440 | } |
| 441 | } |
| 442 | } |
| 443 | } |
| 444 | |
| 445 | namespace { |
| 446 | /// \brief Checks memory dependences among accesses to the same underlying |
| 447 | /// object to determine whether there vectorization is legal or not (and at |
| 448 | /// which vectorization factor). |
| 449 | /// |
| 450 | /// This class works under the assumption that we already checked that memory |
| 451 | /// locations with different underlying pointers are "must-not alias". |
| 452 | /// We use the ScalarEvolution framework to symbolically evalutate access |
| 453 | /// functions pairs. Since we currently don't restructure the loop we can rely |
| 454 | /// on the program order of memory accesses to determine their safety. |
| 455 | /// At the moment we will only deem accesses as safe for: |
| 456 | /// * A negative constant distance assuming program order. |
| 457 | /// |
| 458 | /// Safe: tmp = a[i + 1]; OR a[i + 1] = x; |
| 459 | /// a[i] = tmp; y = a[i]; |
| 460 | /// |
| 461 | /// The latter case is safe because later checks guarantuee that there can't |
| 462 | /// be a cycle through a phi node (that is, we check that "x" and "y" is not |
| 463 | /// the same variable: a header phi can only be an induction or a reduction, a |
| 464 | /// reduction can't have a memory sink, an induction can't have a memory |
| 465 | /// source). This is important and must not be violated (or we have to |
| 466 | /// resort to checking for cycles through memory). |
| 467 | /// |
| 468 | /// * A positive constant distance assuming program order that is bigger |
| 469 | /// than the biggest memory access. |
| 470 | /// |
| 471 | /// tmp = a[i] OR b[i] = x |
| 472 | /// a[i+2] = tmp y = b[i+2]; |
| 473 | /// |
| 474 | /// Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively. |
| 475 | /// |
| 476 | /// * Zero distances and all accesses have the same size. |
| 477 | /// |
| 478 | class MemoryDepChecker { |
| 479 | public: |
| 480 | typedef PointerIntPair<Value *, 1, bool> MemAccessInfo; |
| 481 | typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet; |
| 482 | |
Adam Nemet | f219c64 | 2015-02-19 19:14:52 +0000 | [diff] [blame] | 483 | MemoryDepChecker(ScalarEvolution *Se, const DataLayout *Dl, const Loop *L) |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 484 | : SE(Se), DL(Dl), InnermostLoop(L), AccessIdx(0), |
Adam Nemet | f219c64 | 2015-02-19 19:14:52 +0000 | [diff] [blame] | 485 | ShouldRetryWithRuntimeCheck(false) {} |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 486 | |
| 487 | /// \brief Register the location (instructions are given increasing numbers) |
| 488 | /// of a write access. |
| 489 | void addAccess(StoreInst *SI) { |
| 490 | Value *Ptr = SI->getPointerOperand(); |
| 491 | Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx); |
| 492 | InstMap.push_back(SI); |
| 493 | ++AccessIdx; |
| 494 | } |
| 495 | |
| 496 | /// \brief Register the location (instructions are given increasing numbers) |
| 497 | /// of a write access. |
| 498 | void addAccess(LoadInst *LI) { |
| 499 | Value *Ptr = LI->getPointerOperand(); |
| 500 | Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx); |
| 501 | InstMap.push_back(LI); |
| 502 | ++AccessIdx; |
| 503 | } |
| 504 | |
| 505 | /// \brief Check whether the dependencies between the accesses are safe. |
| 506 | /// |
| 507 | /// Only checks sets with elements in \p CheckDeps. |
| 508 | bool areDepsSafe(AccessAnalysis::DepCandidates &AccessSets, |
| 509 | MemAccessInfoSet &CheckDeps, ValueToValueMap &Strides); |
| 510 | |
| 511 | /// \brief The maximum number of bytes of a vector register we can vectorize |
| 512 | /// the accesses safely with. |
| 513 | unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; } |
| 514 | |
| 515 | /// \brief In same cases when the dependency check fails we can still |
| 516 | /// vectorize the loop with a dynamic array access check. |
| 517 | bool shouldRetryWithRuntimeCheck() { return ShouldRetryWithRuntimeCheck; } |
| 518 | |
| 519 | private: |
| 520 | ScalarEvolution *SE; |
| 521 | const DataLayout *DL; |
| 522 | const Loop *InnermostLoop; |
| 523 | |
| 524 | /// \brief Maps access locations (ptr, read/write) to program order. |
| 525 | DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses; |
| 526 | |
| 527 | /// \brief Memory access instructions in program order. |
| 528 | SmallVector<Instruction *, 16> InstMap; |
| 529 | |
| 530 | /// \brief The program order index to be used for the next instruction. |
| 531 | unsigned AccessIdx; |
| 532 | |
| 533 | // We can access this many bytes in parallel safely. |
| 534 | unsigned MaxSafeDepDistBytes; |
| 535 | |
| 536 | /// \brief If we see a non-constant dependence distance we can still try to |
| 537 | /// vectorize this loop with runtime checks. |
| 538 | bool ShouldRetryWithRuntimeCheck; |
| 539 | |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 540 | /// \brief Check whether there is a plausible dependence between the two |
| 541 | /// accesses. |
| 542 | /// |
| 543 | /// Access \p A must happen before \p B in program order. The two indices |
| 544 | /// identify the index into the program order map. |
| 545 | /// |
| 546 | /// This function checks whether there is a plausible dependence (or the |
| 547 | /// absence of such can't be proved) between the two accesses. If there is a |
| 548 | /// plausible dependence but the dependence distance is bigger than one |
| 549 | /// element access it records this distance in \p MaxSafeDepDistBytes (if this |
| 550 | /// distance is smaller than any other distance encountered so far). |
| 551 | /// Otherwise, this function returns true signaling a possible dependence. |
| 552 | bool isDependent(const MemAccessInfo &A, unsigned AIdx, |
| 553 | const MemAccessInfo &B, unsigned BIdx, |
| 554 | ValueToValueMap &Strides); |
| 555 | |
| 556 | /// \brief Check whether the data dependence could prevent store-load |
| 557 | /// forwarding. |
| 558 | bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize); |
| 559 | }; |
| 560 | |
| 561 | } // end anonymous namespace |
| 562 | |
| 563 | static bool isInBoundsGep(Value *Ptr) { |
| 564 | if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) |
| 565 | return GEP->isInBounds(); |
| 566 | return false; |
| 567 | } |
| 568 | |
| 569 | /// \brief Check whether the access through \p Ptr has a constant stride. |
| 570 | static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr, |
| 571 | const Loop *Lp, ValueToValueMap &StridesMap) { |
| 572 | const Type *Ty = Ptr->getType(); |
| 573 | assert(Ty->isPointerTy() && "Unexpected non-ptr"); |
| 574 | |
| 575 | // Make sure that the pointer does not point to aggregate types. |
| 576 | const PointerType *PtrTy = cast<PointerType>(Ty); |
| 577 | if (PtrTy->getElementType()->isAggregateType()) { |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 578 | DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type" |
| 579 | << *Ptr << "\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 580 | return 0; |
| 581 | } |
| 582 | |
| 583 | const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr); |
| 584 | |
| 585 | const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev); |
| 586 | if (!AR) { |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 587 | DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer " |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 588 | << *Ptr << " SCEV: " << *PtrScev << "\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 589 | return 0; |
| 590 | } |
| 591 | |
| 592 | // The accesss function must stride over the innermost loop. |
| 593 | if (Lp != AR->getLoop()) { |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 594 | DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " << |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 595 | *Ptr << " SCEV: " << *PtrScev << "\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 596 | } |
| 597 | |
| 598 | // The address calculation must not wrap. Otherwise, a dependence could be |
| 599 | // inverted. |
| 600 | // An inbounds getelementptr that is a AddRec with a unit stride |
| 601 | // cannot wrap per definition. The unit stride requirement is checked later. |
| 602 | // An getelementptr without an inbounds attribute and unit stride would have |
| 603 | // to access the pointer value "0" which is undefined behavior in address |
| 604 | // space 0, therefore we can also vectorize this case. |
| 605 | bool IsInBoundsGEP = isInBoundsGep(Ptr); |
| 606 | bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask); |
| 607 | bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0; |
| 608 | if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) { |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 609 | DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space " |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 610 | << *Ptr << " SCEV: " << *PtrScev << "\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 611 | return 0; |
| 612 | } |
| 613 | |
| 614 | // Check the step is constant. |
| 615 | const SCEV *Step = AR->getStepRecurrence(*SE); |
| 616 | |
| 617 | // Calculate the pointer stride and check if it is consecutive. |
| 618 | const SCEVConstant *C = dyn_cast<SCEVConstant>(Step); |
| 619 | if (!C) { |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 620 | DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr << |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 621 | " SCEV: " << *PtrScev << "\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 622 | return 0; |
| 623 | } |
| 624 | |
| 625 | int64_t Size = DL->getTypeAllocSize(PtrTy->getElementType()); |
| 626 | const APInt &APStepVal = C->getValue()->getValue(); |
| 627 | |
| 628 | // Huge step value - give up. |
| 629 | if (APStepVal.getBitWidth() > 64) |
| 630 | return 0; |
| 631 | |
| 632 | int64_t StepVal = APStepVal.getSExtValue(); |
| 633 | |
| 634 | // Strided access. |
| 635 | int64_t Stride = StepVal / Size; |
| 636 | int64_t Rem = StepVal % Size; |
| 637 | if (Rem) |
| 638 | return 0; |
| 639 | |
| 640 | // If the SCEV could wrap but we have an inbounds gep with a unit stride we |
| 641 | // know we can't "wrap around the address space". In case of address space |
| 642 | // zero we know that this won't happen without triggering undefined behavior. |
| 643 | if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) && |
| 644 | Stride != 1 && Stride != -1) |
| 645 | return 0; |
| 646 | |
| 647 | return Stride; |
| 648 | } |
| 649 | |
| 650 | bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance, |
| 651 | unsigned TypeByteSize) { |
| 652 | // If loads occur at a distance that is not a multiple of a feasible vector |
| 653 | // factor store-load forwarding does not take place. |
| 654 | // Positive dependences might cause troubles because vectorizing them might |
| 655 | // prevent store-load forwarding making vectorized code run a lot slower. |
| 656 | // a[i] = a[i-3] ^ a[i-8]; |
| 657 | // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and |
| 658 | // hence on your typical architecture store-load forwarding does not take |
| 659 | // place. Vectorizing in such cases does not make sense. |
| 660 | // Store-load forwarding distance. |
| 661 | const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize; |
| 662 | // Maximum vector factor. |
Adam Nemet | f219c64 | 2015-02-19 19:14:52 +0000 | [diff] [blame] | 663 | unsigned MaxVFWithoutSLForwardIssues = |
| 664 | VectorizerParams::MaxVectorWidth * TypeByteSize; |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 665 | if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues) |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 666 | MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes; |
| 667 | |
| 668 | for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues; |
| 669 | vf *= 2) { |
| 670 | if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) { |
| 671 | MaxVFWithoutSLForwardIssues = (vf >>=1); |
| 672 | break; |
| 673 | } |
| 674 | } |
| 675 | |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 676 | if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) { |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 677 | DEBUG(dbgs() << "LAA: Distance " << Distance << |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 678 | " that could cause a store-load forwarding conflict\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 679 | return true; |
| 680 | } |
| 681 | |
| 682 | if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes && |
Adam Nemet | f219c64 | 2015-02-19 19:14:52 +0000 | [diff] [blame] | 683 | MaxVFWithoutSLForwardIssues != |
| 684 | VectorizerParams::MaxVectorWidth * TypeByteSize) |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 685 | MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues; |
| 686 | return false; |
| 687 | } |
| 688 | |
| 689 | bool MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx, |
| 690 | const MemAccessInfo &B, unsigned BIdx, |
| 691 | ValueToValueMap &Strides) { |
| 692 | assert (AIdx < BIdx && "Must pass arguments in program order"); |
| 693 | |
| 694 | Value *APtr = A.getPointer(); |
| 695 | Value *BPtr = B.getPointer(); |
| 696 | bool AIsWrite = A.getInt(); |
| 697 | bool BIsWrite = B.getInt(); |
| 698 | |
| 699 | // Two reads are independent. |
| 700 | if (!AIsWrite && !BIsWrite) |
| 701 | return false; |
| 702 | |
| 703 | // We cannot check pointers in different address spaces. |
| 704 | if (APtr->getType()->getPointerAddressSpace() != |
| 705 | BPtr->getType()->getPointerAddressSpace()) |
| 706 | return true; |
| 707 | |
| 708 | const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr); |
| 709 | const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr); |
| 710 | |
| 711 | int StrideAPtr = isStridedPtr(SE, DL, APtr, InnermostLoop, Strides); |
| 712 | int StrideBPtr = isStridedPtr(SE, DL, BPtr, InnermostLoop, Strides); |
| 713 | |
| 714 | const SCEV *Src = AScev; |
| 715 | const SCEV *Sink = BScev; |
| 716 | |
| 717 | // If the induction step is negative we have to invert source and sink of the |
| 718 | // dependence. |
| 719 | if (StrideAPtr < 0) { |
| 720 | //Src = BScev; |
| 721 | //Sink = AScev; |
| 722 | std::swap(APtr, BPtr); |
| 723 | std::swap(Src, Sink); |
| 724 | std::swap(AIsWrite, BIsWrite); |
| 725 | std::swap(AIdx, BIdx); |
| 726 | std::swap(StrideAPtr, StrideBPtr); |
| 727 | } |
| 728 | |
| 729 | const SCEV *Dist = SE->getMinusSCEV(Sink, Src); |
| 730 | |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 731 | DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 732 | << "(Induction step: " << StrideAPtr << ")\n"); |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 733 | DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to " |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 734 | << *InstMap[BIdx] << ": " << *Dist << "\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 735 | |
| 736 | // Need consecutive accesses. We don't want to vectorize |
| 737 | // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in |
| 738 | // the address space. |
| 739 | if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){ |
| 740 | DEBUG(dbgs() << "Non-consecutive pointer access\n"); |
| 741 | return true; |
| 742 | } |
| 743 | |
| 744 | const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist); |
| 745 | if (!C) { |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 746 | DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 747 | ShouldRetryWithRuntimeCheck = true; |
| 748 | return true; |
| 749 | } |
| 750 | |
| 751 | Type *ATy = APtr->getType()->getPointerElementType(); |
| 752 | Type *BTy = BPtr->getType()->getPointerElementType(); |
| 753 | unsigned TypeByteSize = DL->getTypeAllocSize(ATy); |
| 754 | |
| 755 | // Negative distances are not plausible dependencies. |
| 756 | const APInt &Val = C->getValue()->getValue(); |
| 757 | if (Val.isNegative()) { |
| 758 | bool IsTrueDataDependence = (AIsWrite && !BIsWrite); |
| 759 | if (IsTrueDataDependence && |
| 760 | (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) || |
| 761 | ATy != BTy)) |
| 762 | return true; |
| 763 | |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 764 | DEBUG(dbgs() << "LAA: Dependence is negative: NoDep\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 765 | return false; |
| 766 | } |
| 767 | |
| 768 | // Write to the same location with the same size. |
| 769 | // Could be improved to assert type sizes are the same (i32 == float, etc). |
| 770 | if (Val == 0) { |
| 771 | if (ATy == BTy) |
| 772 | return false; |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 773 | DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 774 | return true; |
| 775 | } |
| 776 | |
| 777 | assert(Val.isStrictlyPositive() && "Expect a positive value"); |
| 778 | |
| 779 | // Positive distance bigger than max vectorization factor. |
| 780 | if (ATy != BTy) { |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 781 | DEBUG(dbgs() << |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 782 | "LAA: ReadWrite-Write positive dependency with different types\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 783 | return false; |
| 784 | } |
| 785 | |
| 786 | unsigned Distance = (unsigned) Val.getZExtValue(); |
| 787 | |
| 788 | // Bail out early if passed-in parameters make vectorization not feasible. |
Adam Nemet | f219c64 | 2015-02-19 19:14:52 +0000 | [diff] [blame] | 789 | unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ? |
| 790 | VectorizerParams::VectorizationFactor : 1); |
| 791 | unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ? |
| 792 | VectorizerParams::VectorizationInterleave : 1); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 793 | |
| 794 | // The distance must be bigger than the size needed for a vectorized version |
| 795 | // of the operation and the size of the vectorized operation must not be |
| 796 | // bigger than the currrent maximum size. |
| 797 | if (Distance < 2*TypeByteSize || |
| 798 | 2*TypeByteSize > MaxSafeDepDistBytes || |
| 799 | Distance < TypeByteSize * ForcedUnroll * ForcedFactor) { |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 800 | DEBUG(dbgs() << "LAA: Failure because of Positive distance " |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 801 | << Val.getSExtValue() << '\n'); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 802 | return true; |
| 803 | } |
| 804 | |
| 805 | MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ? |
| 806 | Distance : MaxSafeDepDistBytes; |
| 807 | |
| 808 | bool IsTrueDataDependence = (!AIsWrite && BIsWrite); |
| 809 | if (IsTrueDataDependence && |
| 810 | couldPreventStoreLoadForward(Distance, TypeByteSize)) |
| 811 | return true; |
| 812 | |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 813 | DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue() << |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 814 | " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n'); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 815 | |
| 816 | return false; |
| 817 | } |
| 818 | |
| 819 | bool MemoryDepChecker::areDepsSafe(AccessAnalysis::DepCandidates &AccessSets, |
| 820 | MemAccessInfoSet &CheckDeps, |
| 821 | ValueToValueMap &Strides) { |
| 822 | |
| 823 | MaxSafeDepDistBytes = -1U; |
| 824 | while (!CheckDeps.empty()) { |
| 825 | MemAccessInfo CurAccess = *CheckDeps.begin(); |
| 826 | |
| 827 | // Get the relevant memory access set. |
| 828 | EquivalenceClasses<MemAccessInfo>::iterator I = |
| 829 | AccessSets.findValue(AccessSets.getLeaderValue(CurAccess)); |
| 830 | |
| 831 | // Check accesses within this set. |
| 832 | EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE; |
| 833 | AI = AccessSets.member_begin(I), AE = AccessSets.member_end(); |
| 834 | |
| 835 | // Check every access pair. |
| 836 | while (AI != AE) { |
| 837 | CheckDeps.erase(*AI); |
| 838 | EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI); |
| 839 | while (OI != AE) { |
| 840 | // Check every accessing instruction pair in program order. |
| 841 | for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(), |
| 842 | I1E = Accesses[*AI].end(); I1 != I1E; ++I1) |
| 843 | for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(), |
| 844 | I2E = Accesses[*OI].end(); I2 != I2E; ++I2) { |
| 845 | if (*I1 < *I2 && isDependent(*AI, *I1, *OI, *I2, Strides)) |
| 846 | return false; |
| 847 | if (*I2 < *I1 && isDependent(*OI, *I2, *AI, *I1, Strides)) |
| 848 | return false; |
| 849 | } |
| 850 | ++OI; |
| 851 | } |
| 852 | AI++; |
| 853 | } |
| 854 | } |
| 855 | return true; |
| 856 | } |
| 857 | |
Adam Nemet | 436018c | 2015-02-19 19:15:00 +0000 | [diff] [blame] | 858 | void LoopAccessInfo::analyzeLoop(ValueToValueMap &Strides) { |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 859 | |
| 860 | typedef SmallVector<Value*, 16> ValueVector; |
| 861 | typedef SmallPtrSet<Value*, 16> ValueSet; |
| 862 | |
| 863 | // Holds the Load and Store *instructions*. |
| 864 | ValueVector Loads; |
| 865 | ValueVector Stores; |
| 866 | |
| 867 | // Holds all the different accesses in the loop. |
| 868 | unsigned NumReads = 0; |
| 869 | unsigned NumReadWrites = 0; |
| 870 | |
| 871 | PtrRtCheck.Pointers.clear(); |
| 872 | PtrRtCheck.Need = false; |
| 873 | |
| 874 | const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel(); |
Adam Nemet | f219c64 | 2015-02-19 19:14:52 +0000 | [diff] [blame] | 875 | MemoryDepChecker DepChecker(SE, DL, TheLoop); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 876 | |
| 877 | // For each block. |
| 878 | for (Loop::block_iterator bb = TheLoop->block_begin(), |
| 879 | be = TheLoop->block_end(); bb != be; ++bb) { |
| 880 | |
| 881 | // Scan the BB and collect legal loads and stores. |
| 882 | for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e; |
| 883 | ++it) { |
| 884 | |
| 885 | // If this is a load, save it. If this instruction can read from memory |
| 886 | // but is not a load, then we quit. Notice that we don't handle function |
| 887 | // calls that read or write. |
| 888 | if (it->mayReadFromMemory()) { |
| 889 | // Many math library functions read the rounding mode. We will only |
| 890 | // vectorize a loop if it contains known function calls that don't set |
| 891 | // the flag. Therefore, it is safe to ignore this read from memory. |
| 892 | CallInst *Call = dyn_cast<CallInst>(it); |
| 893 | if (Call && getIntrinsicIDForCall(Call, TLI)) |
| 894 | continue; |
| 895 | |
| 896 | LoadInst *Ld = dyn_cast<LoadInst>(it); |
| 897 | if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) { |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 898 | emitAnalysis(VectorizationReport(Ld) |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 899 | << "read with atomic ordering or volatile read"); |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 900 | DEBUG(dbgs() << "LAA: Found a non-simple load.\n"); |
Adam Nemet | 436018c | 2015-02-19 19:15:00 +0000 | [diff] [blame] | 901 | CanVecMem = false; |
| 902 | return; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 903 | } |
| 904 | NumLoads++; |
| 905 | Loads.push_back(Ld); |
| 906 | DepChecker.addAccess(Ld); |
| 907 | continue; |
| 908 | } |
| 909 | |
| 910 | // Save 'store' instructions. Abort if other instructions write to memory. |
| 911 | if (it->mayWriteToMemory()) { |
| 912 | StoreInst *St = dyn_cast<StoreInst>(it); |
| 913 | if (!St) { |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 914 | emitAnalysis(VectorizationReport(it) << |
| 915 | "instruction cannot be vectorized"); |
Adam Nemet | 436018c | 2015-02-19 19:15:00 +0000 | [diff] [blame] | 916 | CanVecMem = false; |
| 917 | return; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 918 | } |
| 919 | if (!St->isSimple() && !IsAnnotatedParallel) { |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 920 | emitAnalysis(VectorizationReport(St) |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 921 | << "write with atomic ordering or volatile write"); |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 922 | DEBUG(dbgs() << "LAA: Found a non-simple store.\n"); |
Adam Nemet | 436018c | 2015-02-19 19:15:00 +0000 | [diff] [blame] | 923 | CanVecMem = false; |
| 924 | return; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 925 | } |
| 926 | NumStores++; |
| 927 | Stores.push_back(St); |
| 928 | DepChecker.addAccess(St); |
| 929 | } |
| 930 | } // Next instr. |
| 931 | } // Next block. |
| 932 | |
| 933 | // Now we have two lists that hold the loads and the stores. |
| 934 | // Next, we find the pointers that they use. |
| 935 | |
| 936 | // Check if we see any stores. If there are no stores, then we don't |
| 937 | // care if the pointers are *restrict*. |
| 938 | if (!Stores.size()) { |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 939 | DEBUG(dbgs() << "LAA: Found a read-only loop!\n"); |
Adam Nemet | 436018c | 2015-02-19 19:15:00 +0000 | [diff] [blame] | 940 | CanVecMem = true; |
| 941 | return; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 942 | } |
| 943 | |
| 944 | AccessAnalysis::DepCandidates DependentAccesses; |
| 945 | AccessAnalysis Accesses(DL, AA, DependentAccesses); |
| 946 | |
| 947 | // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects |
| 948 | // multiple times on the same object. If the ptr is accessed twice, once |
| 949 | // for read and once for write, it will only appear once (on the write |
| 950 | // list). This is okay, since we are going to check for conflicts between |
| 951 | // writes and between reads and writes, but not between reads and reads. |
| 952 | ValueSet Seen; |
| 953 | |
| 954 | ValueVector::iterator I, IE; |
| 955 | for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) { |
| 956 | StoreInst *ST = cast<StoreInst>(*I); |
| 957 | Value* Ptr = ST->getPointerOperand(); |
| 958 | |
| 959 | if (isUniform(Ptr)) { |
| 960 | emitAnalysis( |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 961 | VectorizationReport(ST) |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 962 | << "write to a loop invariant address could not be vectorized"); |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 963 | DEBUG(dbgs() << "LAA: We don't allow storing to uniform addresses\n"); |
Adam Nemet | 436018c | 2015-02-19 19:15:00 +0000 | [diff] [blame] | 964 | CanVecMem = false; |
| 965 | return; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 966 | } |
| 967 | |
| 968 | // If we did *not* see this pointer before, insert it to the read-write |
| 969 | // list. At this phase it is only a 'write' list. |
| 970 | if (Seen.insert(Ptr).second) { |
| 971 | ++NumReadWrites; |
| 972 | |
| 973 | AliasAnalysis::Location Loc = AA->getLocation(ST); |
| 974 | // The TBAA metadata could have a control dependency on the predication |
| 975 | // condition, so we cannot rely on it when determining whether or not we |
| 976 | // need runtime pointer checks. |
Adam Nemet | 01abb2c | 2015-02-18 03:43:19 +0000 | [diff] [blame] | 977 | if (blockNeedsPredication(ST->getParent(), TheLoop, DT)) |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 978 | Loc.AATags.TBAA = nullptr; |
| 979 | |
| 980 | Accesses.addStore(Loc); |
| 981 | } |
| 982 | } |
| 983 | |
| 984 | if (IsAnnotatedParallel) { |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 985 | DEBUG(dbgs() |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 986 | << "LAA: A loop annotated parallel, ignore memory dependency " |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 987 | << "checks.\n"); |
Adam Nemet | 436018c | 2015-02-19 19:15:00 +0000 | [diff] [blame] | 988 | CanVecMem = true; |
| 989 | return; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 990 | } |
| 991 | |
| 992 | for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) { |
| 993 | LoadInst *LD = cast<LoadInst>(*I); |
| 994 | Value* Ptr = LD->getPointerOperand(); |
| 995 | // If we did *not* see this pointer before, insert it to the |
| 996 | // read list. If we *did* see it before, then it is already in |
| 997 | // the read-write list. This allows us to vectorize expressions |
| 998 | // such as A[i] += x; Because the address of A[i] is a read-write |
| 999 | // pointer. This only works if the index of A[i] is consecutive. |
| 1000 | // If the address of i is unknown (for example A[B[i]]) then we may |
| 1001 | // read a few words, modify, and write a few words, and some of the |
| 1002 | // words may be written to the same address. |
| 1003 | bool IsReadOnlyPtr = false; |
| 1004 | if (Seen.insert(Ptr).second || |
| 1005 | !isStridedPtr(SE, DL, Ptr, TheLoop, Strides)) { |
| 1006 | ++NumReads; |
| 1007 | IsReadOnlyPtr = true; |
| 1008 | } |
| 1009 | |
| 1010 | AliasAnalysis::Location Loc = AA->getLocation(LD); |
| 1011 | // The TBAA metadata could have a control dependency on the predication |
| 1012 | // condition, so we cannot rely on it when determining whether or not we |
| 1013 | // need runtime pointer checks. |
Adam Nemet | 01abb2c | 2015-02-18 03:43:19 +0000 | [diff] [blame] | 1014 | if (blockNeedsPredication(LD->getParent(), TheLoop, DT)) |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1015 | Loc.AATags.TBAA = nullptr; |
| 1016 | |
| 1017 | Accesses.addLoad(Loc, IsReadOnlyPtr); |
| 1018 | } |
| 1019 | |
| 1020 | // If we write (or read-write) to a single destination and there are no |
| 1021 | // other reads in this loop then is it safe to vectorize. |
| 1022 | if (NumReadWrites == 1 && NumReads == 0) { |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 1023 | DEBUG(dbgs() << "LAA: Found a write-only loop!\n"); |
Adam Nemet | 436018c | 2015-02-19 19:15:00 +0000 | [diff] [blame] | 1024 | CanVecMem = true; |
| 1025 | return; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1026 | } |
| 1027 | |
| 1028 | // Build dependence sets and check whether we need a runtime pointer bounds |
| 1029 | // check. |
| 1030 | Accesses.buildDependenceSets(); |
| 1031 | bool NeedRTCheck = Accesses.isRTCheckNeeded(); |
| 1032 | |
| 1033 | // Find pointers with computable bounds. We are going to use this information |
| 1034 | // to place a runtime bound check. |
| 1035 | unsigned NumComparisons = 0; |
| 1036 | bool CanDoRT = false; |
| 1037 | if (NeedRTCheck) |
| 1038 | CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop, |
| 1039 | Strides); |
| 1040 | |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 1041 | DEBUG(dbgs() << "LAA: We need to do " << NumComparisons << |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 1042 | " pointer comparisons.\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1043 | |
| 1044 | // If we only have one set of dependences to check pointers among we don't |
| 1045 | // need a runtime check. |
| 1046 | if (NumComparisons == 0 && NeedRTCheck) |
| 1047 | NeedRTCheck = false; |
| 1048 | |
| 1049 | // Check that we did not collect too many pointers or found an unsizeable |
| 1050 | // pointer. |
Adam Nemet | f219c64 | 2015-02-19 19:14:52 +0000 | [diff] [blame] | 1051 | if (!CanDoRT || |
| 1052 | NumComparisons > VectorizerParams::RuntimeMemoryCheckThreshold) { |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1053 | PtrRtCheck.reset(); |
| 1054 | CanDoRT = false; |
| 1055 | } |
| 1056 | |
| 1057 | if (CanDoRT) { |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 1058 | DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1059 | } |
| 1060 | |
| 1061 | if (NeedRTCheck && !CanDoRT) { |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 1062 | emitAnalysis(VectorizationReport() << "cannot identify array bounds"); |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 1063 | DEBUG(dbgs() << "LAA: We can't vectorize because we can't find " << |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 1064 | "the array bounds.\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1065 | PtrRtCheck.reset(); |
Adam Nemet | 436018c | 2015-02-19 19:15:00 +0000 | [diff] [blame] | 1066 | CanVecMem = false; |
| 1067 | return; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1068 | } |
| 1069 | |
| 1070 | PtrRtCheck.Need = NeedRTCheck; |
| 1071 | |
Adam Nemet | 436018c | 2015-02-19 19:15:00 +0000 | [diff] [blame] | 1072 | CanVecMem = true; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1073 | if (Accesses.isDependencyCheckNeeded()) { |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 1074 | DEBUG(dbgs() << "LAA: Checking memory dependencies\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1075 | CanVecMem = DepChecker.areDepsSafe( |
| 1076 | DependentAccesses, Accesses.getDependenciesToCheck(), Strides); |
| 1077 | MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes(); |
| 1078 | |
| 1079 | if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) { |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 1080 | DEBUG(dbgs() << "LAA: Retrying with memory checks\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1081 | NeedRTCheck = true; |
| 1082 | |
| 1083 | // Clear the dependency checks. We assume they are not needed. |
| 1084 | Accesses.resetDepChecks(); |
| 1085 | |
| 1086 | PtrRtCheck.reset(); |
| 1087 | PtrRtCheck.Need = true; |
| 1088 | |
| 1089 | CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, |
| 1090 | TheLoop, Strides, true); |
| 1091 | // Check that we did not collect too many pointers or found an unsizeable |
| 1092 | // pointer. |
Adam Nemet | f219c64 | 2015-02-19 19:14:52 +0000 | [diff] [blame] | 1093 | if (!CanDoRT || |
| 1094 | NumComparisons > VectorizerParams::RuntimeMemoryCheckThreshold) { |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1095 | if (!CanDoRT && NumComparisons > 0) |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 1096 | emitAnalysis(VectorizationReport() |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1097 | << "cannot check memory dependencies at runtime"); |
| 1098 | else |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 1099 | emitAnalysis(VectorizationReport() |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1100 | << NumComparisons << " exceeds limit of " |
Adam Nemet | f219c64 | 2015-02-19 19:14:52 +0000 | [diff] [blame] | 1101 | << VectorizerParams::RuntimeMemoryCheckThreshold |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1102 | << " dependent memory operations checked at runtime"); |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 1103 | DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1104 | PtrRtCheck.reset(); |
Adam Nemet | 436018c | 2015-02-19 19:15:00 +0000 | [diff] [blame] | 1105 | CanVecMem = false; |
| 1106 | return; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1107 | } |
| 1108 | |
| 1109 | CanVecMem = true; |
| 1110 | } |
| 1111 | } |
| 1112 | |
| 1113 | if (!CanVecMem) |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 1114 | emitAnalysis(VectorizationReport() << |
| 1115 | "unsafe dependent memory operations in loop"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1116 | |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 1117 | DEBUG(dbgs() << "LAA: We" << (NeedRTCheck ? "" : " don't") << |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 1118 | " need a runtime memory check.\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1119 | } |
| 1120 | |
Adam Nemet | 01abb2c | 2015-02-18 03:43:19 +0000 | [diff] [blame] | 1121 | bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop, |
| 1122 | DominatorTree *DT) { |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1123 | assert(TheLoop->contains(BB) && "Unknown block used"); |
| 1124 | |
| 1125 | // Blocks that do not dominate the latch need predication. |
| 1126 | BasicBlock* Latch = TheLoop->getLoopLatch(); |
| 1127 | return !DT->dominates(BB, Latch); |
| 1128 | } |
| 1129 | |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 1130 | void LoopAccessInfo::emitAnalysis(VectorizationReport &Message) { |
Adam Nemet | c922853 | 2015-02-19 19:14:56 +0000 | [diff] [blame] | 1131 | assert(!Report && "Multiple reports generated"); |
| 1132 | Report = Message; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1133 | } |
| 1134 | |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 1135 | bool LoopAccessInfo::isUniform(Value *V) { |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1136 | return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop)); |
| 1137 | } |
Adam Nemet | 7206d7a | 2015-02-06 18:31:04 +0000 | [diff] [blame] | 1138 | |
| 1139 | // FIXME: this function is currently a duplicate of the one in |
| 1140 | // LoopVectorize.cpp. |
| 1141 | static Instruction *getFirstInst(Instruction *FirstInst, Value *V, |
| 1142 | Instruction *Loc) { |
| 1143 | if (FirstInst) |
| 1144 | return FirstInst; |
| 1145 | if (Instruction *I = dyn_cast<Instruction>(V)) |
| 1146 | return I->getParent() == Loc->getParent() ? I : nullptr; |
| 1147 | return nullptr; |
| 1148 | } |
| 1149 | |
| 1150 | std::pair<Instruction *, Instruction *> |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 1151 | LoopAccessInfo::addRuntimeCheck(Instruction *Loc) { |
Adam Nemet | 7206d7a | 2015-02-06 18:31:04 +0000 | [diff] [blame] | 1152 | Instruction *tnullptr = nullptr; |
| 1153 | if (!PtrRtCheck.Need) |
| 1154 | return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr); |
| 1155 | |
| 1156 | unsigned NumPointers = PtrRtCheck.Pointers.size(); |
| 1157 | SmallVector<TrackingVH<Value> , 2> Starts; |
| 1158 | SmallVector<TrackingVH<Value> , 2> Ends; |
| 1159 | |
| 1160 | LLVMContext &Ctx = Loc->getContext(); |
| 1161 | SCEVExpander Exp(*SE, "induction"); |
| 1162 | Instruction *FirstInst = nullptr; |
| 1163 | |
| 1164 | for (unsigned i = 0; i < NumPointers; ++i) { |
| 1165 | Value *Ptr = PtrRtCheck.Pointers[i]; |
| 1166 | const SCEV *Sc = SE->getSCEV(Ptr); |
| 1167 | |
| 1168 | if (SE->isLoopInvariant(Sc, TheLoop)) { |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 1169 | DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" << |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 1170 | *Ptr <<"\n"); |
Adam Nemet | 7206d7a | 2015-02-06 18:31:04 +0000 | [diff] [blame] | 1171 | Starts.push_back(Ptr); |
| 1172 | Ends.push_back(Ptr); |
| 1173 | } else { |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame^] | 1174 | DEBUG(dbgs() << "LAA: Adding RT check for range:" << *Ptr << '\n'); |
Adam Nemet | 7206d7a | 2015-02-06 18:31:04 +0000 | [diff] [blame] | 1175 | unsigned AS = Ptr->getType()->getPointerAddressSpace(); |
| 1176 | |
| 1177 | // Use this type for pointer arithmetic. |
| 1178 | Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS); |
| 1179 | |
| 1180 | Value *Start = Exp.expandCodeFor(PtrRtCheck.Starts[i], PtrArithTy, Loc); |
| 1181 | Value *End = Exp.expandCodeFor(PtrRtCheck.Ends[i], PtrArithTy, Loc); |
| 1182 | Starts.push_back(Start); |
| 1183 | Ends.push_back(End); |
| 1184 | } |
| 1185 | } |
| 1186 | |
| 1187 | IRBuilder<> ChkBuilder(Loc); |
| 1188 | // Our instructions might fold to a constant. |
| 1189 | Value *MemoryRuntimeCheck = nullptr; |
| 1190 | for (unsigned i = 0; i < NumPointers; ++i) { |
| 1191 | for (unsigned j = i+1; j < NumPointers; ++j) { |
Adam Nemet | a8945b7 | 2015-02-18 03:43:58 +0000 | [diff] [blame] | 1192 | if (!PtrRtCheck.needsChecking(i, j)) |
Adam Nemet | 7206d7a | 2015-02-06 18:31:04 +0000 | [diff] [blame] | 1193 | continue; |
| 1194 | |
| 1195 | unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace(); |
| 1196 | unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace(); |
| 1197 | |
| 1198 | assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) && |
| 1199 | (AS1 == Ends[i]->getType()->getPointerAddressSpace()) && |
| 1200 | "Trying to bounds check pointers with different address spaces"); |
| 1201 | |
| 1202 | Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0); |
| 1203 | Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1); |
| 1204 | |
| 1205 | Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc"); |
| 1206 | Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc"); |
| 1207 | Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc"); |
| 1208 | Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc"); |
| 1209 | |
| 1210 | Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0"); |
| 1211 | FirstInst = getFirstInst(FirstInst, Cmp0, Loc); |
| 1212 | Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1"); |
| 1213 | FirstInst = getFirstInst(FirstInst, Cmp1, Loc); |
| 1214 | Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict"); |
| 1215 | FirstInst = getFirstInst(FirstInst, IsConflict, Loc); |
| 1216 | if (MemoryRuntimeCheck) { |
| 1217 | IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, |
| 1218 | "conflict.rdx"); |
| 1219 | FirstInst = getFirstInst(FirstInst, IsConflict, Loc); |
| 1220 | } |
| 1221 | MemoryRuntimeCheck = IsConflict; |
| 1222 | } |
| 1223 | } |
| 1224 | |
| 1225 | // We have to do this trickery because the IRBuilder might fold the check to a |
| 1226 | // constant expression in which case there is no Instruction anchored in a |
| 1227 | // the block. |
| 1228 | Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck, |
| 1229 | ConstantInt::getTrue(Ctx)); |
| 1230 | ChkBuilder.Insert(Check, "memcheck.conflict"); |
| 1231 | FirstInst = getFirstInst(FirstInst, Check, Loc); |
| 1232 | return std::make_pair(FirstInst, Check); |
| 1233 | } |
Adam Nemet | 3bfd93d | 2015-02-19 19:15:04 +0000 | [diff] [blame] | 1234 | |
| 1235 | LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE, |
| 1236 | const DataLayout *DL, |
| 1237 | const TargetLibraryInfo *TLI, AliasAnalysis *AA, |
| 1238 | DominatorTree *DT, ValueToValueMap &Strides) |
| 1239 | : TheLoop(L), SE(SE), DL(DL), TLI(TLI), AA(AA), DT(DT), NumLoads(0), |
| 1240 | NumStores(0), MaxSafeDepDistBytes(-1U), CanVecMem(false) { |
| 1241 | analyzeLoop(Strides); |
| 1242 | } |
| 1243 | |
| 1244 | LoopAccessInfo &LoopAccessAnalysis::getInfo(Loop *L, ValueToValueMap &Strides) { |
| 1245 | auto &LAI = LoopAccessInfoMap[L]; |
| 1246 | |
| 1247 | #ifndef NDEBUG |
| 1248 | assert((!LAI || LAI->NumSymbolicStrides == Strides.size()) && |
| 1249 | "Symbolic strides changed for loop"); |
| 1250 | #endif |
| 1251 | |
| 1252 | if (!LAI) { |
| 1253 | LAI = llvm::make_unique<LoopAccessInfo>(L, SE, DL, TLI, AA, DT, Strides); |
| 1254 | #ifndef NDEBUG |
| 1255 | LAI->NumSymbolicStrides = Strides.size(); |
| 1256 | #endif |
| 1257 | } |
| 1258 | return *LAI.get(); |
| 1259 | } |
| 1260 | |
| 1261 | bool LoopAccessAnalysis::runOnFunction(Function &F) { |
| 1262 | SE = &getAnalysis<ScalarEvolution>(); |
| 1263 | DL = F.getParent()->getDataLayout(); |
| 1264 | auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); |
| 1265 | TLI = TLIP ? &TLIP->getTLI() : nullptr; |
| 1266 | AA = &getAnalysis<AliasAnalysis>(); |
| 1267 | DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); |
| 1268 | |
| 1269 | return false; |
| 1270 | } |
| 1271 | |
| 1272 | void LoopAccessAnalysis::getAnalysisUsage(AnalysisUsage &AU) const { |
| 1273 | AU.addRequired<ScalarEvolution>(); |
| 1274 | AU.addRequired<AliasAnalysis>(); |
| 1275 | AU.addRequired<DominatorTreeWrapperPass>(); |
| 1276 | |
| 1277 | AU.setPreservesAll(); |
| 1278 | } |
| 1279 | |
| 1280 | char LoopAccessAnalysis::ID = 0; |
| 1281 | static const char laa_name[] = "Loop Access Analysis"; |
| 1282 | #define LAA_NAME "loop-accesses" |
| 1283 | |
| 1284 | INITIALIZE_PASS_BEGIN(LoopAccessAnalysis, LAA_NAME, laa_name, false, true) |
| 1285 | INITIALIZE_AG_DEPENDENCY(AliasAnalysis) |
| 1286 | INITIALIZE_PASS_DEPENDENCY(ScalarEvolution) |
| 1287 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) |
| 1288 | INITIALIZE_PASS_END(LoopAccessAnalysis, LAA_NAME, laa_name, false, true) |
| 1289 | |
| 1290 | namespace llvm { |
| 1291 | Pass *createLAAPass() { |
| 1292 | return new LoopAccessAnalysis(); |
| 1293 | } |
| 1294 | } |