LLVM 24.0.0git
MemoryDependenceAnalysis.cpp
Go to the documentation of this file.
1//===- MemoryDependenceAnalysis.cpp - Mem Deps Implementation -------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements an analysis that determines, for a given memory
10// operation, what preceding memory operations it depends on. It builds on
11// alias analysis information, and tries to provide a lazy, caching interface to
12// a common kind of alias information query.
13//
14//===----------------------------------------------------------------------===//
15
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/Statistic.h"
24#include "llvm/Analysis/Loads.h"
30#include "llvm/IR/BasicBlock.h"
31#include "llvm/IR/Dominators.h"
32#include "llvm/IR/Function.h"
33#include "llvm/IR/InstrTypes.h"
34#include "llvm/IR/Instruction.h"
37#include "llvm/IR/LLVMContext.h"
38#include "llvm/IR/Metadata.h"
39#include "llvm/IR/Module.h"
41#include "llvm/IR/Type.h"
42#include "llvm/IR/Use.h"
43#include "llvm/IR/Value.h"
45#include "llvm/Pass.h"
50#include "llvm/Support/Debug.h"
51#include <algorithm>
52#include <cassert>
53#include <iterator>
54#include <utility>
55
56using namespace llvm;
57
58#define DEBUG_TYPE "memdep"
59
60STATISTIC(NumCacheNonLocal, "Number of fully cached non-local responses");
61STATISTIC(NumCacheDirtyNonLocal, "Number of dirty cached non-local responses");
62STATISTIC(NumUncacheNonLocal, "Number of uncached non-local responses");
63
64STATISTIC(NumCacheNonLocalPtr,
65 "Number of fully cached non-local ptr responses");
66STATISTIC(NumCacheDirtyNonLocalPtr,
67 "Number of cached, but dirty, non-local ptr responses");
68STATISTIC(NumUncacheNonLocalPtr, "Number of uncached non-local ptr responses");
69STATISTIC(NumCacheCompleteNonLocalPtr,
70 "Number of block queries that were completely cached");
71
72// Limit for the number of instructions to scan in a block.
73
75 "memdep-block-scan-limit", cl::Hidden, cl::init(100),
76 cl::desc("The number of instructions to scan in a block in memory "
77 "dependency analysis (default = 100)"));
78
80 BlockNumberLimit("memdep-block-number-limit", cl::Hidden, cl::init(200),
81 cl::desc("The number of blocks to scan during memory "
82 "dependency analysis (default = 200)"));
83
85 "memdep-cache-global-limit", cl::Hidden, cl::init(10000),
86 cl::desc("The max number of entries allowed in a cache (default = 10000)"));
87
88// Limit on the number of memdep results to process.
89static const unsigned int NumResultsLimit = 100;
90
91/// This is a helper function that removes Val from 'Inst's set in ReverseMap.
92///
93/// If the set becomes empty, remove Inst's entry.
94template <typename KeyTy>
95static void
97 Instruction *Inst, KeyTy Val) {
99 ReverseMap.find(Inst);
100 assert(InstIt != ReverseMap.end() && "Reverse map out of sync?");
101 bool Found = InstIt->second.erase(Val);
102 assert(Found && "Invalid reverse map!");
103 (void)Found;
104 if (InstIt->second.empty())
105 ReverseMap.erase(InstIt);
106}
107
108/// If the given instruction references a specific memory location, fill in Loc
109/// with the details, otherwise set Loc.Ptr to null.
110///
111/// Returns a ModRefInfo value describing the general behavior of the
112/// instruction.
114 const TargetLibraryInfo &TLI) {
115 if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
116 if (LI->isUnordered()) {
118 return ModRefInfo::Ref;
119 }
120 if (LI->getOrdering() == AtomicOrdering::Monotonic) {
122 return ModRefInfo::ModRef;
123 }
125 return ModRefInfo::ModRef;
126 }
127
128 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
129 if (SI->isUnordered()) {
131 return ModRefInfo::Mod;
132 }
133 if (SI->getOrdering() == AtomicOrdering::Monotonic) {
135 return ModRefInfo::ModRef;
136 }
138 return ModRefInfo::ModRef;
139 }
140
141 if (const VAArgInst *V = dyn_cast<VAArgInst>(Inst)) {
143 return ModRefInfo::ModRef;
144 }
145
146 if (const CallBase *CB = dyn_cast<CallBase>(Inst)) {
147 if (Value *FreedOp = getFreedOperand(CB, &TLI)) {
148 // calls to free() deallocate the entire structure
149 Loc = MemoryLocation::getAfter(FreedOp);
150 return ModRefInfo::Mod;
151 }
152 }
153
154 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
155 switch (II->getIntrinsicID()) {
156 case Intrinsic::lifetime_start:
157 case Intrinsic::lifetime_end:
159 // These intrinsics don't really modify the memory, but returning Mod
160 // will allow them to be handled conservatively.
161 return ModRefInfo::Mod;
162 case Intrinsic::invariant_start:
164 // These intrinsics don't really modify the memory, but returning Mod
165 // will allow them to be handled conservatively.
166 return ModRefInfo::Mod;
167 case Intrinsic::invariant_end:
169 // These intrinsics don't really modify the memory, but returning Mod
170 // will allow them to be handled conservatively.
171 return ModRefInfo::Mod;
172 case Intrinsic::masked_load:
174 return ModRefInfo::Ref;
175 case Intrinsic::masked_store:
177 return ModRefInfo::Mod;
178 default:
179 break;
180 }
181 }
182
183 // Otherwise, just do the coarse-grained thing that always works.
184 if (Inst->mayWriteToMemory())
185 return ModRefInfo::ModRef;
186 if (Inst->mayReadFromMemory())
187 return ModRefInfo::Ref;
189}
190
191/// Private helper for finding the local dependencies of a call site.
192MemDepResult MemoryDependenceResults::getCallDependencyFrom(
193 CallBase *Call, bool isReadOnlyCall, BasicBlock::iterator ScanIt,
194 BasicBlock *BB) {
195 unsigned Limit = getDefaultBlockScanLimit();
196 bool IsInvariantLoad = Call->hasMetadata(LLVMContext::MD_invariant_load);
197
198 // Walk backwards through the block, looking for dependencies.
199 while (ScanIt != BB->begin()) {
200 Instruction *Inst = &*--ScanIt;
201
202 // Limit the amount of scanning we do so we don't end up with quadratic
203 // running time on extreme testcases.
204 --Limit;
205 if (!Limit)
207
208 // If this inst is a memory op, get the pointer it accessed
209 MemoryLocation Loc;
210 ModRefInfo MR = GetLocation(Inst, Loc, TLI);
211 if (Loc.Ptr) {
212 // A simple instruction.
213 if (isModOrRefSet(AA.getModRefInfo(Call, Loc))) {
214 if (IsInvariantLoad)
215 continue;
216 return MemDepResult::getClobber(Inst);
217 }
218 continue;
219 }
220
221 if (auto *CallB = dyn_cast<CallBase>(Inst)) {
222 bool IsIdenticalReadOnlyCall = isReadOnlyCall && !isModSet(MR) &&
224
225 // An identical earlier invariant load-like call is an available value
226 // even if AA sees both calls as reading the same memory.
227 if (IsInvariantLoad && IsIdenticalReadOnlyCall)
228 return MemDepResult::getDef(Inst);
229
230 // If these two calls do not interfere, look past it.
231 if (isNoModRef(AA.getModRefInfo(Call, CallB))) {
232 // If the two calls are the same, return Inst as a Def, so that
233 // Call can be found redundant and eliminated.
234 if (IsIdenticalReadOnlyCall)
235 return MemDepResult::getDef(Inst);
236
237 // Otherwise if the two calls don't interact (e.g. CallB is readnone)
238 // keep scanning.
239 continue;
240 } else if (IsInvariantLoad) {
241 continue;
242 } else {
243 return MemDepResult::getClobber(Inst);
244 }
245 }
246
247 // If we could not obtain a pointer for the instruction and the instruction
248 // touches memory then assume that this is a dependency.
249 if (isModOrRefSet(MR))
250 return MemDepResult::getClobber(Inst);
251 }
252
253 // No dependence found. If this is the entry block of the function, it is
254 // unknown, otherwise it is non-local.
255 if (BB != &BB->getParent()->getEntryBlock())
258}
259
261 const MemoryLocation &MemLoc, bool isLoad, BasicBlock::iterator ScanIt,
262 BasicBlock *BB, Instruction *QueryInst, unsigned *Limit,
263 BatchAAResults &BatchAA) {
264 MemDepResult InvariantGroupDependency = MemDepResult::getUnknown();
265 if (QueryInst != nullptr) {
266 if (auto *LI = dyn_cast<LoadInst>(QueryInst)) {
267 InvariantGroupDependency = getInvariantGroupPointerDependency(LI, BB);
268
269 if (InvariantGroupDependency.isDef())
270 return InvariantGroupDependency;
271 }
272 }
274 MemLoc, isLoad, ScanIt, BB, QueryInst, Limit, BatchAA);
275 if (SimpleDep.isDef())
276 return SimpleDep;
277 // Non-local invariant group dependency indicates there is non local Def
278 // (it only returns nonLocal if it finds nonLocal def), which is better than
279 // local clobber and everything else.
280 if (InvariantGroupDependency.isNonLocal())
281 return InvariantGroupDependency;
282
283 assert(InvariantGroupDependency.isUnknown() &&
284 "InvariantGroupDependency should be only unknown at this point");
285 return SimpleDep;
286}
287
289 const MemoryLocation &MemLoc, bool isLoad, BasicBlock::iterator ScanIt,
290 BasicBlock *BB, Instruction *QueryInst, unsigned *Limit) {
291 BatchAAResults BatchAA(AA, &EEA);
292 return getPointerDependencyFrom(MemLoc, isLoad, ScanIt, BB, QueryInst, Limit,
293 BatchAA);
294}
295
298 BasicBlock *BB) {
299
300 if (!LI->hasMetadata(LLVMContext::MD_invariant_group))
302
303 // Take the ptr operand after all casts and geps 0. This way we can search
304 // cast graph down only.
305 Value *LoadOperand = LI->getPointerOperand()->stripPointerCasts();
306
307 // It's is not safe to walk the use list of global value, because function
308 // passes aren't allowed to look outside their functions.
309 // FIXME: this could be fixed by filtering instructions from outside
310 // of current function.
311 if (isa<GlobalValue>(LoadOperand))
313
314 Instruction *ClosestDependency = nullptr;
315 // Order of instructions in uses list is unpredictible. In order to always
316 // get the same result, we will look for the closest dominance.
317 auto GetClosestDependency = [this](Instruction *Best, Instruction *Other) {
318 assert(Other && "Must call it with not null instruction");
319 if (Best == nullptr || DT.dominates(Best, Other))
320 return Other;
321 return Best;
322 };
323
324 for (const Use &Us : LoadOperand->uses()) {
325 auto *U = dyn_cast<Instruction>(Us.getUser());
326 if (!U || U == LI || !DT.dominates(U, LI))
327 continue;
328
329 // If we hit load/store with the same invariant.group metadata (and the
330 // same pointer operand) we can assume that value pointed by pointer
331 // operand didn't change.
332 if ((isa<LoadInst>(U) ||
333 (isa<StoreInst>(U) &&
334 cast<StoreInst>(U)->getPointerOperand() == LoadOperand)) &&
335 U->hasMetadata(LLVMContext::MD_invariant_group))
336 ClosestDependency = GetClosestDependency(ClosestDependency, U);
337 }
338
339 if (!ClosestDependency)
341 if (ClosestDependency->getParent() == BB)
342 return MemDepResult::getDef(ClosestDependency);
343 // Def(U) can't be returned here because it is non-local. If local
344 // dependency won't be found then return nonLocal counting that the
345 // user will call getNonLocalPointerDependency, which will return cached
346 // result.
347 NonLocalDefsCache.try_emplace(
348 LI, NonLocalDepResult(ClosestDependency->getParent(),
349 MemDepResult::getDef(ClosestDependency), nullptr));
350 ReverseNonLocalDefsCache[ClosestDependency].insert(LI);
352}
353
355 const MemoryLocation &MemLoc, bool isLoad, BasicBlock::iterator ScanIt,
356 BasicBlock *BB, Instruction *QueryInst, unsigned *Limit,
357 BatchAAResults &BatchAA) {
358 bool isInvariantLoad = false;
359 Align MemLocAlign =
361
362 unsigned DefaultLimit = getDefaultBlockScanLimit();
363 if (!Limit)
364 Limit = &DefaultLimit;
365
366 // We must be careful with atomic accesses, as they may allow another thread
367 // to touch this location, clobbering it. We are conservative: if the
368 // QueryInst is not a simple (non-atomic) memory access, we automatically
369 // return getClobber.
370 // If it is simple, we know based on the results of
371 // "Compiler testing via a theory of sound optimisations in the C11/C++11
372 // memory model" in PLDI 2013, that a non-atomic location can only be
373 // clobbered between a pair of a release and an acquire action, with no
374 // access to the location in between.
375 // Here is an example for giving the general intuition behind this rule.
376 // In the following code:
377 // store x 0;
378 // release action; [1]
379 // acquire action; [4]
380 // %val = load x;
381 // It is unsafe to replace %val by 0 because another thread may be running:
382 // acquire action; [2]
383 // store x 42;
384 // release action; [3]
385 // with synchronization from 1 to 2 and from 3 to 4, resulting in %val
386 // being 42. A key property of this program however is that if either
387 // 1 or 4 were missing, there would be a race between the store of 42
388 // either the store of 0 or the load (making the whole program racy).
389 // The paper mentioned above shows that the same property is respected
390 // by every program that can detect any optimization of that kind: either
391 // it is racy (undefined) or there is a release followed by an acquire
392 // between the pair of accesses under consideration.
393
394 // If the load is invariant, we "know" that it doesn't alias *any* write. We
395 // do want to respect mustalias results since defs are useful for value
396 // forwarding, but any mayalias write can be assumed to be noalias.
397 // Arguably, this logic should be pushed inside AliasAnalysis itself.
398 if (isLoad && QueryInst) {
399 isInvariantLoad = QueryInst->hasMetadata(LLVMContext::MD_invariant_load);
400 if (LoadInst *LI = dyn_cast<LoadInst>(QueryInst))
401 MemLocAlign = LI->getAlign();
402 }
403
404 // True for volatile instruction.
405 // For Load/Store return true if atomic ordering is stronger than AO,
406 // for other instruction just true if it can read or write to memory.
407 auto isComplexForReordering = [](Instruction * I, AtomicOrdering AO)->bool {
408 if (I->isVolatile())
409 return true;
410 if (auto *LI = dyn_cast<LoadInst>(I))
411 return isStrongerThan(LI->getOrdering(), AO);
412 if (auto *SI = dyn_cast<StoreInst>(I))
413 return isStrongerThan(SI->getOrdering(), AO);
414 return I->mayReadOrWriteMemory();
415 };
416
417 // Walk backwards through the basic block, looking for dependencies.
418 while (ScanIt != BB->begin()) {
419 Instruction *Inst = &*--ScanIt;
420
421 // Limit the amount of scanning we do so we don't end up with quadratic
422 // running time on extreme testcases.
423 --*Limit;
424 if (!*Limit)
426
428 // If we reach a lifetime begin or end marker, then the query ends here
429 // because the value is undefined.
430 Intrinsic::ID ID = II->getIntrinsicID();
431 switch (ID) {
432 case Intrinsic::lifetime_start: {
433 MemoryLocation ArgLoc = MemoryLocation::getAfter(II->getArgOperand(0));
434 AliasResult R = BatchAA.alias(ArgLoc, MemLoc);
435 if (R == AliasResult::MustAlias)
436 return MemDepResult::getDef(II);
437 if (R == AliasResult::NoAlias)
438 continue;
439 // A partial overlap must act as a barrier.
441 }
442 case Intrinsic::masked_load:
443 case Intrinsic::masked_store: {
445 /*ModRefInfo MR =*/ GetLocation(II, Loc, TLI);
446 AliasResult R = BatchAA.alias(Loc, MemLoc);
447 if (R == AliasResult::NoAlias)
448 continue;
449 if (R == AliasResult::MustAlias)
450 return MemDepResult::getDef(II);
451 if (ID == Intrinsic::masked_load)
452 continue;
454 }
455 }
456 }
457
458 // Values depend on loads if the pointers are must aliased. This means
459 // that a load depends on another must aliased load from the same value.
460 // One exception is atomic loads: a value can depend on an atomic load that
461 // it does not alias with when this atomic load indicates that another
462 // thread may be accessing the location.
463 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
464 // While volatile access cannot be eliminated, they do not have to clobber
465 // non-aliasing locations, as normal accesses, for example, can be safely
466 // reordered with volatile accesses.
467 if (LI->isVolatile()) {
468 if (!QueryInst)
469 // Original QueryInst *may* be volatile
470 return MemDepResult::getClobber(LI);
471 if (QueryInst->isVolatile())
472 // Ordering required if QueryInst is itself volatile
473 return MemDepResult::getClobber(LI);
474 // Otherwise, volatile doesn't imply any special ordering
475 }
476
477 // Atomic loads have complications involved.
478 // A Monotonic (or higher) load is OK if the query inst is itself not
479 // atomic.
480 // FIXME: This is overly conservative.
481 if (LI->isAtomic() && isStrongerThanUnordered(LI->getOrdering())) {
482 if (!QueryInst ||
483 isComplexForReordering(QueryInst, AtomicOrdering::NotAtomic))
484 return MemDepResult::getClobber(LI);
485 if (LI->getOrdering() != AtomicOrdering::Monotonic)
486 return MemDepResult::getClobber(LI);
487 }
488
490
491 // If we found a pointer, check if it could be the same as our pointer.
492 AliasResult R = BatchAA.alias(LoadLoc, MemLoc);
493
494 if (R == AliasResult::NoAlias)
495 continue;
496
497 if (isLoad) {
498 // Must aliased loads are defs of each other.
499 if (R == AliasResult::MustAlias)
500 return MemDepResult::getDef(Inst);
501
502 // If we have a partial alias, then return this as a clobber for the
503 // client to handle.
504 if (R == AliasResult::PartialAlias && R.hasOffset()) {
505 ClobberOffsets[LI] = R.getOffset();
506 return MemDepResult::getClobber(Inst);
507 }
508
509 // Random may-alias loads don't depend on each other without a
510 // dependence.
511 continue;
512 }
513
514 // Stores don't alias loads from read-only memory.
515 if (!isModSet(BatchAA.getModRefInfoMask(LoadLoc)))
516 continue;
517
518 // Stores depend on may/must aliased loads.
519 return MemDepResult::getDef(Inst);
520 }
521
522 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
523 // Atomic stores have complications involved.
524 // A Monotonic store is OK if the query inst is itself not atomic.
525 // FIXME: This is overly conservative.
526 if (!SI->isUnordered() && SI->isAtomic()) {
527 if (!QueryInst ||
528 isComplexForReordering(QueryInst, AtomicOrdering::Unordered))
530 // Ok, if we are here the guard above guarantee us that
531 // QueryInst is a non-atomic or unordered load/store.
532 // SI is atomic with monotonic or release semantic (seq_cst for store
533 // is actually a release semantic plus total order over other seq_cst
534 // instructions, as soon as QueryInst is not seq_cst we can consider it
535 // as simple release semantic).
536 // Monotonic and Release semantic allows re-ordering before store
537 // so we are safe to go further and check the aliasing. It will prohibit
538 // re-ordering in case locations are may or must alias.
539 }
540
541 // While volatile access cannot be eliminated, they do not have to clobber
542 // non-aliasing locations, as normal accesses can for example be reordered
543 // with volatile accesses.
544 if (SI->isVolatile())
545 if (!QueryInst || QueryInst->isVolatile())
547
548 // If alias analysis can tell that this store is guaranteed to not modify
549 // the query pointer, ignore it. Use getModRefInfo to handle cases where
550 // the query pointer points to constant memory etc.
551 if (!isModOrRefSet(BatchAA.getModRefInfo(SI, MemLoc)))
552 continue;
553
554 // Ok, this store might clobber the query pointer. Check to see if it is
555 // a must alias: in this case, we want to return this as a def.
556 // FIXME: Use ModRefInfo::Must bit from getModRefInfo call above.
558
559 // If we found a pointer, check if it could be the same as our pointer.
560 AliasResult R = BatchAA.alias(StoreLoc, MemLoc);
561
562 if (R == AliasResult::NoAlias)
563 continue;
564 if (R == AliasResult::MustAlias)
565 return MemDepResult::getDef(Inst);
566 if (isInvariantLoad)
567 continue;
568 if (isStorePreservingMemoryLocation(SI, MemLoc, MemLocAlign, BatchAA,
569 *Limit))
570 continue;
571 return MemDepResult::getClobber(Inst);
572 }
573
574 // If this is an allocation, and if we know that the accessed pointer is to
575 // the allocation, return Def. This means that there is no dependence and
576 // the access can be optimized based on that. For example, a load could
577 // turn into undef. Note that we can bypass the allocation itself when
578 // looking for a clobber in many cases; that's an alias property and is
579 // handled by BasicAA.
580 if (isa<AllocaInst>(Inst) || isNoAliasCall(Inst)) {
581 const Value *AccessPtr = getUnderlyingObject(MemLoc.Ptr);
582 if (AccessPtr == Inst || BatchAA.isMustAlias(Inst, AccessPtr))
583 return MemDepResult::getDef(Inst);
584 }
585
586 // If we found a select instruction for MemLoc pointer, return it as Def
587 // dependency.
588 if (isa<SelectInst>(Inst) && MemLoc.Ptr == Inst)
589 return MemDepResult::getDef(Inst);
590
591 if (isInvariantLoad)
592 continue;
593
594 // A release fence requires that all stores complete before it, but does
595 // not prevent the reordering of following loads or stores 'before' the
596 // fence. As a result, we look past it when finding a dependency for
597 // loads. DSE uses this to find preceding stores to delete and thus we
598 // can't bypass the fence if the query instruction is a store.
599 if (FenceInst *FI = dyn_cast<FenceInst>(Inst))
600 if (isLoad && FI->getOrdering() == AtomicOrdering::Release)
601 continue;
602
603 // See if this instruction (e.g. a call or vaarg) mod/ref's the pointer.
604 switch (BatchAA.getModRefInfo(Inst, MemLoc)) {
606 // If the call has no effect on the queried pointer, just ignore it.
607 continue;
608 case ModRefInfo::Mod:
609 return MemDepResult::getClobber(Inst);
610 case ModRefInfo::Ref:
611 // If the call is known to never store to the pointer, and if this is a
612 // load query, we can safely ignore it (scan past it).
613 if (isLoad)
614 continue;
615 [[fallthrough]];
616 default:
617 // Otherwise, there is a potential dependence. Return a clobber.
618 return MemDepResult::getClobber(Inst);
619 }
620 }
621
622 // No dependence found. If this is the entry block of the function, it is
623 // unknown, otherwise it is non-local.
624 if (BB != &BB->getParent()->getEntryBlock())
627}
628
630 ClobberOffsets.clear();
631 Instruction *ScanPos = QueryInst;
632
633 // Check for a cached result
634 MemDepResult &LocalCache = LocalDeps[QueryInst];
635
636 // If the cached entry is non-dirty, just return it. Note that this depends
637 // on MemDepResult's default constructing to 'dirty'.
638 if (!LocalCache.isDirty())
639 return LocalCache;
640
641 // Otherwise, if we have a dirty entry, we know we can start the scan at that
642 // instruction, which may save us some work.
643 if (Instruction *Inst = LocalCache.getInst()) {
644 ScanPos = Inst;
645
646 RemoveFromReverseMap(ReverseLocalDeps, Inst, QueryInst);
647 }
648
649 BasicBlock *QueryParent = QueryInst->getParent();
650
651 // Do the scan.
652 if (BasicBlock::iterator(QueryInst) == QueryParent->begin()) {
653 // No dependence found. If this is the entry block of the function, it is
654 // unknown, otherwise it is non-local.
655 if (QueryParent != &QueryParent->getParent()->getEntryBlock())
656 LocalCache = MemDepResult::getNonLocal();
657 else
658 LocalCache = MemDepResult::getNonFuncLocal();
659 } else {
660 MemoryLocation MemLoc;
661 ModRefInfo MR = GetLocation(QueryInst, MemLoc, TLI);
662 if (MemLoc.Ptr) {
663 // If we can do a pointer scan, make it happen.
664 bool isLoad = !isModSet(MR);
665 if (auto *II = dyn_cast<IntrinsicInst>(QueryInst))
666 isLoad |= II->getIntrinsicID() == Intrinsic::lifetime_start;
667
668 LocalCache =
669 getPointerDependencyFrom(MemLoc, isLoad, ScanPos->getIterator(),
670 QueryParent, QueryInst, nullptr);
671 } else if (auto *QueryCall = dyn_cast<CallBase>(QueryInst)) {
672 bool isReadOnly = AA.onlyReadsMemory(QueryCall);
673 LocalCache = getCallDependencyFrom(QueryCall, isReadOnly,
674 ScanPos->getIterator(), QueryParent);
675 } else
676 // Non-memory instruction.
677 LocalCache = MemDepResult::getUnknown();
678 }
679
680 // Remember the result!
681 if (Instruction *I = LocalCache.getInst())
682 ReverseLocalDeps[I].insert(QueryInst);
683
684 return LocalCache;
685}
686
687#ifndef NDEBUG
688/// This method is used when -debug is specified to verify that cache arrays
689/// are properly kept sorted.
691 int Count = -1) {
692 if (Count == -1)
693 Count = Cache.size();
694 assert(std::is_sorted(Cache.begin(), Cache.begin() + Count) &&
695 "Cache isn't sorted!");
696}
697#endif
698
701 assert(getDependency(QueryCall).isNonLocal() &&
702 "getNonLocalCallDependency should only be used on calls with "
703 "non-local deps!");
704 PerInstNLInfo &CacheP = NonLocalDepsMap[QueryCall];
705 NonLocalDepInfo &Cache = CacheP.first;
706
707 // This is the set of blocks that need to be recomputed. In the cached case,
708 // this can happen due to instructions being deleted etc. In the uncached
709 // case, this starts out as the set of predecessors we care about.
711
712 if (!Cache.empty()) {
713 // Okay, we have a cache entry. If we know it is not dirty, just return it
714 // with no computation.
715 if (!CacheP.second) {
716 ++NumCacheNonLocal;
717 return Cache;
718 }
719
720 // If we already have a partially computed set of results, scan them to
721 // determine what is dirty, seeding our initial DirtyBlocks worklist.
722 for (auto &Entry : Cache)
723 if (Entry.getResult().isDirty())
724 DirtyBlocks.push_back(Entry.getBB());
725
726 // Sort the cache so that we can do fast binary search lookups below.
727 llvm::sort(Cache);
728
729 ++NumCacheDirtyNonLocal;
730 } else {
731 // Seed DirtyBlocks with each of the preds of QueryInst's block.
732 BasicBlock *QueryBB = QueryCall->getParent();
733 append_range(DirtyBlocks, PredCache.get(QueryBB));
734 ++NumUncacheNonLocal;
735 }
736
737 // isReadonlyCall - If this is a read-only call, we can be more aggressive.
738 bool isReadonlyCall = AA.onlyReadsMemory(QueryCall);
739
741
742 unsigned NumSortedEntries = Cache.size();
743 LLVM_DEBUG(AssertSorted(Cache));
744
745 // Iterate while we still have blocks to update.
746 while (!DirtyBlocks.empty()) {
747 BasicBlock *DirtyBB = DirtyBlocks.pop_back_val();
748
749 // Already processed this block?
750 if (!Visited.insert(DirtyBB).second)
751 continue;
752
753 // Do a binary search to see if we already have an entry for this block in
754 // the cache set. If so, find it.
755 LLVM_DEBUG(AssertSorted(Cache, NumSortedEntries));
756 NonLocalDepInfo::iterator Entry =
757 std::upper_bound(Cache.begin(), Cache.begin() + NumSortedEntries,
758 NonLocalDepEntry(DirtyBB));
759 if (Entry != Cache.begin() && std::prev(Entry)->getBB() == DirtyBB)
760 --Entry;
761
762 NonLocalDepEntry *ExistingResult = nullptr;
763 if (Entry != Cache.begin() + NumSortedEntries &&
764 Entry->getBB() == DirtyBB) {
765 // If we already have an entry, and if it isn't already dirty, the block
766 // is done.
767 if (!Entry->getResult().isDirty())
768 continue;
769
770 // Otherwise, remember this slot so we can update the value.
771 ExistingResult = &*Entry;
772 }
773
774 // If the dirty entry has a pointer, start scanning from it so we don't have
775 // to rescan the entire block.
776 BasicBlock::iterator ScanPos = DirtyBB->end();
777 if (ExistingResult) {
778 if (Instruction *Inst = ExistingResult->getResult().getInst()) {
779 ScanPos = Inst->getIterator();
780 // We're removing QueryInst's use of Inst.
781 RemoveFromReverseMap<Instruction *>(ReverseNonLocalDeps, Inst,
782 QueryCall);
783 }
784 }
785
786 // Find out if this block has a local dependency for QueryInst.
787 MemDepResult Dep;
788
789 if (ScanPos != DirtyBB->begin()) {
790 Dep = getCallDependencyFrom(QueryCall, isReadonlyCall, ScanPos, DirtyBB);
791 } else if (DirtyBB != &DirtyBB->getParent()->getEntryBlock()) {
792 // No dependence found. If this is the entry block of the function, it is
793 // a clobber, otherwise it is unknown.
795 } else {
797 }
798
799 // If we had a dirty entry for the block, update it. Otherwise, just add
800 // a new entry.
801 if (ExistingResult)
802 ExistingResult->setResult(Dep);
803 else
804 Cache.push_back(NonLocalDepEntry(DirtyBB, Dep));
805
806 // If the block has a dependency (i.e. it isn't completely transparent to
807 // the value), remember the association!
808 if (!Dep.isNonLocal()) {
809 // Keep the ReverseNonLocalDeps map up to date so we can efficiently
810 // update this when we remove instructions.
811 if (Instruction *Inst = Dep.getInst())
812 ReverseNonLocalDeps[Inst].insert(QueryCall);
813 } else {
814
815 // If the block *is* completely transparent to the load, we need to check
816 // the predecessors of this block. Add them to our worklist.
817 append_range(DirtyBlocks, PredCache.get(DirtyBB));
818 }
819 }
820
821 return Cache;
822}
823
826 const MemoryLocation Loc = MemoryLocation::get(QueryInst);
827 bool isLoad = isa<LoadInst>(QueryInst);
828 BasicBlock *FromBB = QueryInst->getParent();
829 assert(FromBB);
830
831 assert(Loc.Ptr->getType()->isPointerTy() &&
832 "Can't get pointer deps of a non-pointer!");
833 Result.clear();
834 {
835 // Check if there is cached Def with invariant.group.
836 auto NonLocalDefIt = NonLocalDefsCache.find(QueryInst);
837 if (NonLocalDefIt != NonLocalDefsCache.end()) {
838 Result.push_back(NonLocalDefIt->second);
840 ReverseNonLocalDefsCache, NonLocalDefIt->second.getResult().getInst(),
841 QueryInst);
842 NonLocalDefsCache.erase(NonLocalDefIt);
843 return;
844 }
845 }
846 // This routine does not expect to deal with volatile instructions.
847 // Doing so would require piping through the QueryInst all the way through.
848 // TODO: volatiles can't be elided, but they can be reordered with other
849 // non-volatile accesses.
850
851 // We currently give up on any instruction which is ordered, but we do handle
852 // atomic instructions which are unordered.
853 // TODO: Handle ordered instructions
854 auto isOrdered = [](Instruction *Inst) {
855 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
856 return !LI->isUnordered();
857 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
858 return !SI->isUnordered();
859 }
860 return false;
861 };
862 if (QueryInst->isVolatile() || isOrdered(QueryInst)) {
863 Result.push_back(NonLocalDepResult(FromBB, MemDepResult::getUnknown(),
864 const_cast<Value *>(Loc.Ptr)));
865 return;
866 }
867 const DataLayout &DL = FromBB->getDataLayout();
868 PHITransAddr Address(const_cast<Value *>(Loc.Ptr), DL, &AC);
869
870 // NonLocalPointerDepVisited is the set of blocks we've inspected, and the
871 // pointer we consider in each block. Because of critical edges, we currently
872 // bail out if querying a block with multiple different pointers. This can
873 // happen during PHI translation.
874 ++NonLocalPointerDepEpoch;
875 assert(NonLocalPointerDepEpoch > 0 &&
876 "NonLocalPointerDepVisitedEpoch overflow");
877 NonLocalPointerDepVisited.resize(FromBB->getParent()->getMaxBlockNumber());
878 if (getNonLocalPointerDepFromBB(QueryInst, Address, Loc, isLoad, FromBB,
879 Result, true))
880 return;
881 Result.clear();
882 Result.push_back(NonLocalDepResult(FromBB, MemDepResult::getUnknown(),
883 const_cast<Value *>(Loc.Ptr)));
884}
885
886/// Compute the memdep value for BB with Pointer/PointeeSize using either
887/// cached information in Cache or by doing a lookup (which may use dirty cache
888/// info if available).
889///
890/// If we do a lookup, add the result to the cache.
891MemDepResult MemoryDependenceResults::getNonLocalInfoForBlock(
892 Instruction *QueryInst, const MemoryLocation &Loc, bool isLoad,
893 BasicBlock *BB, NonLocalDepInfo *Cache, unsigned NumSortedEntries,
894 BatchAAResults &BatchAA) {
895
896 bool isInvariantLoad = false;
897
898 if (QueryInst)
899 isInvariantLoad = QueryInst->hasMetadata(LLVMContext::MD_invariant_load);
900
901 // Do a binary search to see if we already have an entry for this block in
902 // the cache set. If so, find it.
903 NonLocalDepInfo::iterator Entry = std::upper_bound(
904 Cache->begin(), Cache->begin() + NumSortedEntries, NonLocalDepEntry(BB));
905 if (Entry != Cache->begin() && (Entry - 1)->getBB() == BB)
906 --Entry;
907
908 NonLocalDepEntry *ExistingResult = nullptr;
909 if (Entry != Cache->begin() + NumSortedEntries && Entry->getBB() == BB)
910 ExistingResult = &*Entry;
911
912 // Use cached result for invariant load only if there is no dependency for non
913 // invariant load. In this case invariant load can not have any dependency as
914 // well.
915 if (ExistingResult && isInvariantLoad &&
916 !ExistingResult->getResult().isNonFuncLocal())
917 ExistingResult = nullptr;
918
919 // If we have a cached entry, and it is non-dirty, use it as the value for
920 // this dependency.
921 if (ExistingResult && !ExistingResult->getResult().isDirty()) {
922 ++NumCacheNonLocalPtr;
923 return ExistingResult->getResult();
924 }
925
926 // Otherwise, we have to scan for the value. If we have a dirty cache
927 // entry, start scanning from its position, otherwise we scan from the end
928 // of the block.
929 BasicBlock::iterator ScanPos = BB->end();
930 if (ExistingResult && ExistingResult->getResult().getInst()) {
931 assert(ExistingResult->getResult().getInst()->getParent() == BB &&
932 "Instruction invalidated?");
933 ++NumCacheDirtyNonLocalPtr;
934 ScanPos = ExistingResult->getResult().getInst()->getIterator();
935
936 // Eliminating the dirty entry from 'Cache', so update the reverse info.
937 ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
938 RemoveFromReverseMap(ReverseNonLocalPtrDeps, &*ScanPos, CacheKey);
939 } else {
940 ++NumUncacheNonLocalPtr;
941 }
942
943 // Scan the block for the dependency.
944 MemDepResult Dep = getPointerDependencyFrom(Loc, isLoad, ScanPos, BB,
945 QueryInst, nullptr, BatchAA);
946
947 // Don't cache results for invariant load.
948 if (isInvariantLoad)
949 return Dep;
950
951 // If we had a dirty entry for the block, update it. Otherwise, just add
952 // a new entry.
953 if (ExistingResult)
954 ExistingResult->setResult(Dep);
955 else
956 Cache->push_back(NonLocalDepEntry(BB, Dep));
957
958 // If the block has a dependency (i.e. it isn't completely transparent to
959 // the value), remember the reverse association because we just added it
960 // to Cache!
961 if (!Dep.isLocal())
962 return Dep;
963
964 // Keep the ReverseNonLocalPtrDeps map up to date so we can efficiently
965 // update MemDep when we remove instructions.
966 Instruction *Inst = Dep.getInst();
967 assert(Inst && "Didn't depend on anything?");
968 ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
969 ReverseNonLocalPtrDeps[Inst].insert(CacheKey);
970 return Dep;
971}
972
973/// Sort the NonLocalDepInfo cache, given a certain number of elements in the
974/// array that are already properly ordered.
975///
976/// This is optimized for the case when only a few entries are added.
977static void
979 unsigned NumSortedEntries) {
980
981 // If only one entry, don't sort.
982 if (Cache.size() < 2)
983 return;
984
985 unsigned s = Cache.size() - NumSortedEntries;
986
987 // If the cache is already sorted, don't sort it again.
988 if (s == 0)
989 return;
990
991 // If no entry is sorted, sort the whole cache.
992 if (NumSortedEntries == 0) {
993 llvm::sort(Cache);
994 return;
995 }
996
997 // If the number of unsorted entires is small and the cache size is big, using
998 // insertion sort is faster. Here use Log2_32 to quickly choose the sort
999 // method.
1000 if (s < Log2_32(Cache.size())) {
1001 while (s > 0) {
1002 NonLocalDepEntry Val = Cache.back();
1003 Cache.pop_back();
1004 MemoryDependenceResults::NonLocalDepInfo::iterator Entry =
1005 std::upper_bound(Cache.begin(), Cache.end() - s + 1, Val);
1006 Cache.insert(Entry, Val);
1007 s--;
1008 }
1009 } else {
1010 llvm::sort(Cache);
1011 }
1012}
1013
1014void MemoryDependenceResults::setNonLocalPointerDepVisited(BasicBlock *BB,
1015 Value *V) {
1016 NonLocalPointerDepVisited[BB->getNumber()] = {V, NonLocalPointerDepEpoch};
1017}
1018
1019bool MemoryDependenceResults::isNonLocalPointerDepVisited(
1020 BasicBlock *BB) const {
1021 return NonLocalPointerDepVisited[BB->getNumber()].second ==
1022 NonLocalPointerDepEpoch;
1023}
1024
1025Value *
1026MemoryDependenceResults::lookupNonLocalPointerDepVisited(BasicBlock *BB) const {
1027 assert(isNonLocalPointerDepVisited(BB) &&
1028 "Visited value requested for unseen block");
1029 return NonLocalPointerDepVisited[BB->getNumber()].first;
1030}
1031
1032/// Perform a dependency query based on pointer/pointeesize starting at the end
1033/// of StartBB.
1034///
1035/// Add any clobber/def results to the results vector and keep track of which
1036/// blocks are visited in 'NonLocalPointerDepVisited'.
1037///
1038/// This has special behavior for the first block queries (when SkipFirstBlock
1039/// is true). In this special case, it ignores the contents of the specified
1040/// block and starts returning dependence info for its predecessors.
1041///
1042/// This function returns true on success, or false to indicate that it could
1043/// not compute dependence information for some reason. This should be treated
1044/// as a clobber dependence on the first instruction in the predecessor block.
1045bool MemoryDependenceResults::getNonLocalPointerDepFromBB(
1046 Instruction *QueryInst, const PHITransAddr &Pointer,
1047 const MemoryLocation &Loc, bool isLoad, BasicBlock *StartBB,
1048 SmallVectorImpl<NonLocalDepResult> &Result, bool SkipFirstBlock,
1049 bool IsIncomplete) {
1050 // Look up the cached info for Pointer.
1051 ValueIsLoadPair CacheKey(Pointer.getAddr(), isLoad);
1052
1053 // Set up a temporary NLPI value. If the map doesn't yet have an entry for
1054 // CacheKey, this value will be inserted as the associated value. Otherwise,
1055 // it'll be ignored, and we'll have to check to see if the cached size and
1056 // aa tags are consistent with the current query.
1057 NonLocalPointerInfo InitialNLPI;
1058 InitialNLPI.Size = Loc.Size;
1059 InitialNLPI.AATags = Loc.AATags;
1060
1061 bool isInvariantLoad = false;
1062 if (QueryInst)
1063 isInvariantLoad = QueryInst->hasMetadata(LLVMContext::MD_invariant_load);
1064
1065 // Get the NLPI for CacheKey, inserting one into the map if it doesn't
1066 // already have one.
1067 std::pair<CachedNonLocalPointerInfo::iterator, bool> Pair =
1068 NonLocalPointerDeps.insert(std::make_pair(CacheKey, InitialNLPI));
1069 NonLocalPointerInfo *CacheInfo = &Pair.first->second;
1070
1071 // If we already have a cache entry for this CacheKey, we may need to do some
1072 // work to reconcile the cache entry and the current query.
1073 // Invariant loads don't participate in caching. Thus no need to reconcile.
1074 if (!isInvariantLoad && !Pair.second) {
1075 if (CacheInfo->Size != Loc.Size) {
1076 // The query's Size is not equal to the cached one. Throw out the cached
1077 // data and proceed with the query with the new size.
1078 CacheInfo->Pair = BBSkipFirstBlockPair();
1079 CacheInfo->Size = Loc.Size;
1080 for (auto &Entry : CacheInfo->NonLocalDeps)
1081 if (Instruction *Inst = Entry.getResult().getInst())
1082 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
1083 CacheInfo->NonLocalDeps.clear();
1084 // The cache is cleared (in the above line) so we will have lost
1085 // information about blocks we have already visited. We therefore must
1086 // assume that the cache information is incomplete.
1087 IsIncomplete = true;
1088 }
1089
1090 // If the query's AATags are inconsistent with the cached one,
1091 // conservatively throw out the cached data and restart the query with
1092 // no tag if needed.
1093 if (CacheInfo->AATags != Loc.AATags) {
1094 if (CacheInfo->AATags) {
1095 CacheInfo->Pair = BBSkipFirstBlockPair();
1096 CacheInfo->AATags = AAMDNodes();
1097 for (auto &Entry : CacheInfo->NonLocalDeps)
1098 if (Instruction *Inst = Entry.getResult().getInst())
1099 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
1100 CacheInfo->NonLocalDeps.clear();
1101 // The cache is cleared (in the above line) so we will have lost
1102 // information about blocks we have already visited. We therefore must
1103 // assume that the cache information is incomplete.
1104 IsIncomplete = true;
1105 }
1106 if (Loc.AATags)
1107 return getNonLocalPointerDepFromBB(
1108 QueryInst, Pointer, Loc.getWithoutAATags(), isLoad, StartBB, Result,
1109 SkipFirstBlock, IsIncomplete);
1110 }
1111 }
1112
1113 NonLocalDepInfo *Cache = &CacheInfo->NonLocalDeps;
1114
1115 // If we have valid cached information for exactly the block we are
1116 // investigating, just return it with no recomputation.
1117 // Don't use cached information for invariant loads since it is valid for
1118 // non-invariant loads only.
1119 if (!IsIncomplete && !isInvariantLoad &&
1120 CacheInfo->Pair == BBSkipFirstBlockPair(StartBB, SkipFirstBlock)) {
1121 // We have a fully cached result for this query then we can just return the
1122 // cached results and populate the visited set. However, we have to verify
1123 // that we don't already have conflicting results for these blocks. Check
1124 // to ensure that if a block in the results set is in the visited set that
1125 // it was for the same pointer query.
1126 for (auto &Entry : *Cache) {
1127 if (!isNonLocalPointerDepVisited(Entry.getBB()))
1128 continue;
1129 Value *Prev = lookupNonLocalPointerDepVisited(Entry.getBB());
1130 if (Prev == Pointer.getAddr())
1131 continue;
1132
1133 // We have a pointer mismatch in a block. Just return false, saying
1134 // that something was clobbered in this result. We could also do a
1135 // non-fully cached query, but there is little point in doing this.
1136 return false;
1137 }
1138
1139 Value *Addr = Pointer.getAddr();
1140 for (auto &Entry : *Cache) {
1141 setNonLocalPointerDepVisited(Entry.getBB(), Addr);
1142 if (Entry.getResult().isNonLocal()) {
1143 continue;
1144 }
1145
1146 if (DT.isReachableFromEntry(Entry.getBB())) {
1147 Result.push_back(
1148 NonLocalDepResult(Entry.getBB(), Entry.getResult(), Addr));
1149 }
1150 }
1151 ++NumCacheCompleteNonLocalPtr;
1152 return true;
1153 }
1154
1155 // If the size of this cache has surpassed the global limit, stop here.
1156 if (Cache->size() > CacheGlobalLimit)
1157 return false;
1158
1159 // Otherwise, either this is a new block, a block with an invalid cache
1160 // pointer or one that we're about to invalidate by putting more info into
1161 // it than its valid cache info. If empty and not explicitly indicated as
1162 // incomplete, the result will be valid cache info, otherwise it isn't.
1163 //
1164 // Invariant loads don't affect cache in any way thus no need to update
1165 // CacheInfo as well.
1166 if (!isInvariantLoad) {
1167 if (!IsIncomplete && Cache->empty())
1168 CacheInfo->Pair = BBSkipFirstBlockPair(StartBB, SkipFirstBlock);
1169 else
1170 CacheInfo->Pair = BBSkipFirstBlockPair();
1171 }
1172
1174 Worklist.push_back(StartBB);
1175
1176 // PredList used inside loop.
1178
1179 // Keep track of the entries that we know are sorted. Previously cached
1180 // entries will all be sorted. The entries we add we only sort on demand (we
1181 // don't insert every element into its sorted position). We know that we
1182 // won't get any reuse from currently inserted values, because we don't
1183 // revisit blocks after we insert info for them.
1184 unsigned NumSortedEntries = Cache->size();
1185 unsigned WorklistEntries = BlockNumberLimit;
1186 bool GotWorklistLimit = false;
1187 LLVM_DEBUG(AssertSorted(*Cache));
1188
1189 BatchAAResults BatchAA(AA, &EEA);
1190 while (!Worklist.empty()) {
1191 BasicBlock *BB = Worklist.pop_back_val();
1192
1193 // If we do process a large number of blocks it becomes very expensive and
1194 // likely it isn't worth worrying about
1195 if (Result.size() > NumResultsLimit) {
1196 // Sort it now (if needed) so that recursive invocations of
1197 // getNonLocalPointerDepFromBB and other routines that could reuse the
1198 // cache value will only see properly sorted cache arrays.
1199 if (Cache && NumSortedEntries != Cache->size()) {
1200 SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1201 }
1202 // Since we bail out, the "Cache" set won't contain all of the
1203 // results for the query. This is ok (we can still use it to accelerate
1204 // specific block queries) but we can't do the fastpath "return all
1205 // results from the set". Clear out the indicator for this.
1206 CacheInfo->Pair = BBSkipFirstBlockPair();
1207 return false;
1208 }
1209
1210 // Skip the first block if we have it.
1211 if (!SkipFirstBlock) {
1212 // Analyze the dependency of *Pointer in FromBB. See if we already have
1213 // been here.
1214 assert(isNonLocalPointerDepVisited(BB) &&
1215 "Should check 'visited' before adding to WL");
1216
1217 // Get the dependency info for Pointer in BB. If we have cached
1218 // information, we will use it, otherwise we compute it.
1219 LLVM_DEBUG(AssertSorted(*Cache, NumSortedEntries));
1220 MemDepResult Dep = getNonLocalInfoForBlock(
1221 QueryInst, Loc, isLoad, BB, Cache, NumSortedEntries, BatchAA);
1222
1223 // If we got a Def or Clobber, add this to the list of results.
1224 if (!Dep.isNonLocal()) {
1225 if (DT.isReachableFromEntry(BB)) {
1226 Result.push_back(NonLocalDepResult(BB, Dep, Pointer.getAddr()));
1227 continue;
1228 }
1229 }
1230 }
1231
1232 // If 'Pointer' is an instruction defined in this block, then we need to do
1233 // phi translation to change it into a value live in the predecessor block.
1234 // If not, we just add the predecessors to the worklist and scan them with
1235 // the same Pointer.
1236 if (!Pointer.needsPHITranslationFromBlock(BB)) {
1237 SkipFirstBlock = false;
1238 SmallVector<BasicBlock *, 16> NewBlocks;
1239 for (BasicBlock *Pred : PredCache.get(BB)) {
1240 // Verify that we haven't looked at this block yet.
1241 if (!isNonLocalPointerDepVisited(Pred)) {
1242 setNonLocalPointerDepVisited(Pred, Pointer.getAddr());
1243 // First time we've looked at *PI.
1244 NewBlocks.push_back(Pred);
1245 continue;
1246 }
1247 Value *Prev = lookupNonLocalPointerDepVisited(Pred);
1248 // If we have seen this block before, but it was with a different
1249 // pointer then we have a phi translation failure and we have to treat
1250 // this as a clobber.
1251 if (Prev != Pointer.getAddr()) {
1252 // Make sure to clean up the Visited map before continuing on to
1253 // PredTranslationFailure.
1254 for (auto *NewBlock : NewBlocks)
1255 setNonLocalPointerDepVisited(NewBlock, nullptr);
1256 goto PredTranslationFailure;
1257 }
1258 }
1259 if (NewBlocks.size() > WorklistEntries) {
1260 // Make sure to clean up the Visited map before continuing on to
1261 // PredTranslationFailure.
1262 for (auto *NewBlock : NewBlocks)
1263 setNonLocalPointerDepVisited(NewBlock, nullptr);
1264 GotWorklistLimit = true;
1265 goto PredTranslationFailure;
1266 }
1267 WorklistEntries -= NewBlocks.size();
1268 Worklist.append(NewBlocks.begin(), NewBlocks.end());
1269 continue;
1270 }
1271
1272 // We do need to do phi translation, if we know ahead of time we can't phi
1273 // translate this value, don't even try.
1274 if (!Pointer.isPotentiallyPHITranslatable())
1275 goto PredTranslationFailure;
1276
1277 // We may have added values to the cache list before this PHI translation.
1278 // If so, we haven't done anything to ensure that the cache remains sorted.
1279 // Sort it now (if needed) so that recursive invocations of
1280 // getNonLocalPointerDepFromBB and other routines that could reuse the cache
1281 // value will only see properly sorted cache arrays.
1282 if (Cache && NumSortedEntries != Cache->size()) {
1283 SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1284 NumSortedEntries = Cache->size();
1285 }
1286 Cache = nullptr;
1287
1288 PredList.clear();
1289 for (BasicBlock *Pred : PredCache.get(BB)) {
1290 PredList.push_back(std::make_pair(Pred, Pointer));
1291
1292 // Get the PHI translated pointer in this predecessor. This can fail if
1293 // not translatable, in which case the getAddr() returns null.
1294 PHITransAddr &PredPointer = PredList.back().second;
1295 Value *PredPtrVal =
1296 PredPointer.translateValue(BB, Pred, &DT, /*MustDominate=*/false);
1297
1298 // Check to see if we have already visited this pred block with another
1299 // pointer. If so, we can't do this lookup. This failure can occur
1300 // with PHI translation when a critical edge exists and the PHI node in
1301 // the successor translates to a pointer value different than the
1302 // pointer the block was first analyzed with.
1303 if (!isNonLocalPointerDepVisited(Pred)) {
1304 setNonLocalPointerDepVisited(Pred, PredPtrVal);
1305 continue;
1306 }
1307 Value *PrevVal = lookupNonLocalPointerDepVisited(Pred);
1308
1309 // We found the pred; take it off the list of preds to visit.
1310 PredList.pop_back();
1311
1312 // If the predecessor was visited with PredPtr, then we already did
1313 // the analysis and can ignore it.
1314 if (PrevVal == PredPtrVal)
1315 continue;
1316
1317 // Otherwise, the block was previously analyzed with a different
1318 // pointer. We can't represent the result of this case, so we just
1319 // treat this as a phi translation failure.
1320
1321 // Make sure to clean up the Visited map before continuing on to
1322 // PredTranslationFailure.
1323 for (const auto &Pred : PredList)
1324 setNonLocalPointerDepVisited(Pred.first, nullptr);
1325
1326 goto PredTranslationFailure;
1327 }
1328
1329 // Actually process results here; this need to be a separate loop to avoid
1330 // calling getNonLocalPointerDepFromBB for blocks we don't want to return
1331 // any results for. (getNonLocalPointerDepFromBB will modify our
1332 // datastructures in ways the code after the PredTranslationFailure label
1333 // doesn't expect.)
1334 for (auto &I : PredList) {
1335 BasicBlock *Pred = I.first;
1336 PHITransAddr &PredPointer = I.second;
1337 Value *PredPtrVal = PredPointer.getAddr();
1338
1339 bool CanTranslate = true;
1340 // If PHI translation was unable to find an available pointer in this
1341 // predecessor, then we have to assume that the pointer is clobbered in
1342 // that predecessor. We can still do PRE of the load, which would insert
1343 // a computation of the pointer in this predecessor.
1344 if (!PredPtrVal) {
1345 // If translation failed but the (partially) translated address
1346 // expression depends on a select instruction, try to translate both
1347 // sides of that select. The select condition is recovered from the
1348 // failed `PredPointer` (the phi has already been resolved to the
1349 // select there), but the two sides must be translated from the
1350 // original, untranslated `Pointer`.
1351 if (Value *Cond = PredPointer.getSelectCondition()) {
1352 SelectAddr::SelectAddrs SelAddrs =
1353 PHITransAddr(Pointer).translateValue(BB, Pred, &DT, Cond);
1354 if (SelAddrs.first && SelAddrs.second) {
1355 Result.push_back(NonLocalDepResult(Pred, MemDepResult::getSelect(),
1356 SelectAddr(Cond, SelAddrs)));
1357 NonLocalPointerInfo &NLPI = NonLocalPointerDeps[CacheKey];
1358 NLPI.Pair = BBSkipFirstBlockPair();
1359 continue;
1360 }
1361 }
1362 CanTranslate = false;
1363 }
1364
1365 // FIXME: it is entirely possible that PHI translating will end up with
1366 // the same value. Consider PHI translating something like:
1367 // X = phi [x, bb1], [y, bb2]. PHI translating for bb1 doesn't *need*
1368 // to recurse here, pedantically speaking.
1369
1370 // If getNonLocalPointerDepFromBB fails here, that means the cached
1371 // result conflicted with the Visited list; we have to conservatively
1372 // assume it is unknown, but this also does not block PRE of the load.
1373 if (!CanTranslate ||
1374 !getNonLocalPointerDepFromBB(QueryInst, PredPointer,
1375 Loc.getWithNewPtr(PredPtrVal), isLoad,
1376 Pred, Result)) {
1377 // Add the entry to the Result list.
1378 NonLocalDepResult Entry(Pred, MemDepResult::getUnknown(), PredPtrVal);
1379 Result.push_back(Entry);
1380
1381 // Since we had a phi translation failure, the cache for CacheKey won't
1382 // include all of the entries that we need to immediately satisfy future
1383 // queries. Mark this in NonLocalPointerDeps by setting the
1384 // BBSkipFirstBlockPair pointer to null. This requires reuse of the
1385 // cached value to do more work but not miss the phi trans failure.
1386 NonLocalPointerInfo &NLPI = NonLocalPointerDeps[CacheKey];
1387 NLPI.Pair = BBSkipFirstBlockPair();
1388 continue;
1389 }
1390 }
1391
1392 // Refresh the CacheInfo/Cache pointer so that it isn't invalidated.
1393 CacheInfo = &NonLocalPointerDeps[CacheKey];
1394 Cache = &CacheInfo->NonLocalDeps;
1395 NumSortedEntries = Cache->size();
1396
1397 // Since we did phi translation, the "Cache" set won't contain all of the
1398 // results for the query. This is ok (we can still use it to accelerate
1399 // specific block queries) but we can't do the fastpath "return all
1400 // results from the set" Clear out the indicator for this.
1401 CacheInfo->Pair = BBSkipFirstBlockPair();
1402 SkipFirstBlock = false;
1403 continue;
1404
1405 PredTranslationFailure:
1406 // The following code is "failure"; we can't produce a sane translation
1407 // for the given block. It assumes that we haven't modified any of
1408 // our datastructures while processing the current block.
1409
1410 if (!Cache) {
1411 // Refresh the CacheInfo/Cache pointer if it got invalidated.
1412 CacheInfo = &NonLocalPointerDeps[CacheKey];
1413 Cache = &CacheInfo->NonLocalDeps;
1414 NumSortedEntries = Cache->size();
1415 }
1416
1417 // Since we failed phi translation, the "Cache" set won't contain all of the
1418 // results for the query. This is ok (we can still use it to accelerate
1419 // specific block queries) but we can't do the fastpath "return all
1420 // results from the set". Clear out the indicator for this.
1421 CacheInfo->Pair = BBSkipFirstBlockPair();
1422
1423 // If *nothing* works, mark the pointer as unknown.
1424 //
1425 // If this is the magic first block, return this as a clobber of the whole
1426 // incoming value. Since we can't phi translate to one of the predecessors,
1427 // we have to bail out.
1428 if (SkipFirstBlock)
1429 return false;
1430
1431 // Results of invariant loads are not cached thus no need to update cached
1432 // information.
1433 if (!isInvariantLoad) {
1434 for (NonLocalDepEntry &I : llvm::reverse(*Cache)) {
1435 if (I.getBB() != BB)
1436 continue;
1437
1438 assert((GotWorklistLimit || I.getResult().isNonLocal() ||
1439 !DT.isReachableFromEntry(BB)) &&
1440 "Should only be here with transparent block");
1441
1442 I.setResult(MemDepResult::getUnknown());
1443
1444
1445 break;
1446 }
1447 }
1448 (void)GotWorklistLimit;
1449 // Go ahead and report unknown dependence.
1450 Result.push_back(
1451 NonLocalDepResult(BB, MemDepResult::getUnknown(), Pointer.getAddr()));
1452 }
1453
1454 // Okay, we're done now. If we added new values to the cache, re-sort it.
1455 SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1456 LLVM_DEBUG(AssertSorted(*Cache));
1457 return true;
1458}
1459
1460/// If P exists in CachedNonLocalPointerInfo or NonLocalDefsCache, remove it.
1461void MemoryDependenceResults::removeCachedNonLocalPointerDependencies(
1462 ValueIsLoadPair P) {
1463
1464 // Most of the time this cache is empty.
1465 if (!NonLocalDefsCache.empty()) {
1466 auto it = NonLocalDefsCache.find(P.getPointer());
1467 if (it != NonLocalDefsCache.end()) {
1468 RemoveFromReverseMap(ReverseNonLocalDefsCache,
1469 it->second.getResult().getInst(), P.getPointer());
1470 NonLocalDefsCache.erase(it);
1471 }
1472
1473 if (auto *I = dyn_cast<Instruction>(P.getPointer())) {
1474 auto toRemoveIt = ReverseNonLocalDefsCache.find(I);
1475 if (toRemoveIt != ReverseNonLocalDefsCache.end()) {
1476 for (const auto *Entry : toRemoveIt->second) {
1477 [[maybe_unused]] bool Removed = NonLocalDefsCache.erase(Entry);
1478 assert(Removed && "Reverse non-local def map out of sync?");
1479 }
1480 ReverseNonLocalDefsCache.erase(toRemoveIt);
1481 }
1482 }
1483 }
1484
1485 CachedNonLocalPointerInfo::iterator It = NonLocalPointerDeps.find(P);
1486 if (It == NonLocalPointerDeps.end())
1487 return;
1488
1489 // Remove all of the entries in the BB->val map. This involves removing
1490 // instructions from the reverse map.
1491 NonLocalDepInfo &PInfo = It->second.NonLocalDeps;
1492
1493 for (const NonLocalDepEntry &DE : PInfo) {
1494 Instruction *Target = DE.getResult().getInst();
1495 if (!Target)
1496 continue; // Ignore non-local dep results.
1497 assert(Target->getParent() == DE.getBB());
1498
1499 // Eliminating the dirty entry from 'Cache', so update the reverse info.
1500 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Target, P);
1501 }
1502
1503 // Remove P from NonLocalPointerDeps (which deletes NonLocalDepInfo).
1504 NonLocalPointerDeps.erase(It);
1505}
1506
1508 // If Ptr isn't really a pointer, just ignore it.
1509 if (!Ptr->getType()->isPointerTy())
1510 return;
1511 // Flush store info for the pointer.
1512 removeCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, false));
1513 // Flush load info for the pointer.
1514 removeCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, true));
1515}
1516
1518 PredCache.clear();
1519}
1520
1522 EEA.removeInstruction(RemInst);
1523
1524 // Walk through the Non-local dependencies, removing this one as the value
1525 // for any cached queries.
1526 NonLocalDepMapType::iterator NLDI = NonLocalDepsMap.find(RemInst);
1527 if (NLDI != NonLocalDepsMap.end()) {
1528 NonLocalDepInfo &BlockMap = NLDI->second.first;
1529 for (auto &Entry : BlockMap)
1530 if (Instruction *Inst = Entry.getResult().getInst())
1531 RemoveFromReverseMap(ReverseNonLocalDeps, Inst, RemInst);
1532 NonLocalDepsMap.erase(NLDI);
1533 }
1534
1535 // If we have a cached local dependence query for this instruction, remove it.
1536 LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst);
1537 if (LocalDepEntry != LocalDeps.end()) {
1538 // Remove us from DepInst's reverse set now that the local dep info is gone.
1539 if (Instruction *Inst = LocalDepEntry->second.getInst())
1540 RemoveFromReverseMap(ReverseLocalDeps, Inst, RemInst);
1541
1542 // Remove this local dependency info.
1543 LocalDeps.erase(LocalDepEntry);
1544 }
1545
1546 // If we have any cached dependencies on this instruction, remove
1547 // them.
1548
1549 // If the instruction is a pointer, remove it from both the load info and the
1550 // store info.
1551 if (RemInst->getType()->isPointerTy()) {
1552 removeCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, false));
1553 removeCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, true));
1554 } else {
1555 // Otherwise, if the instructions is in the map directly, it must be a load.
1556 // Remove it.
1557 auto toRemoveIt = NonLocalDefsCache.find(RemInst);
1558 if (toRemoveIt != NonLocalDefsCache.end()) {
1559 assert(isa<LoadInst>(RemInst) &&
1560 "only load instructions should be added directly");
1561 Instruction *DepV = toRemoveIt->second.getResult().getInst();
1562 RemoveFromReverseMap<const Value *>(ReverseNonLocalDefsCache, DepV,
1563 RemInst);
1564 NonLocalDefsCache.erase(toRemoveIt);
1565 }
1566 }
1567
1568 auto ReverseNonLocalDefIt = ReverseNonLocalDefsCache.find(RemInst);
1569 if (ReverseNonLocalDefIt != ReverseNonLocalDefsCache.end()) {
1570 for (const Value *QueryInst : ReverseNonLocalDefIt->second) {
1571 [[maybe_unused]] bool Removed = NonLocalDefsCache.erase(QueryInst);
1572 assert(Removed && "Reverse non-local def map out of sync?");
1573 }
1574 ReverseNonLocalDefsCache.erase(ReverseNonLocalDefIt);
1575 }
1576
1577 // Loop over all of the things that depend on the instruction we're removing.
1579
1580 // If we find RemInst as a clobber or Def in any of the maps for other values,
1581 // we need to replace its entry with a dirty version of the instruction after
1582 // it. If RemInst is a terminator, we use a null dirty value.
1583 //
1584 // Using a dirty version of the instruction after RemInst saves having to scan
1585 // the entire block to get to this point.
1586 MemDepResult NewDirtyVal;
1587 if (!RemInst->isTerminator())
1588 NewDirtyVal = MemDepResult::getDirty(&*++RemInst->getIterator());
1589
1590 ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
1591 if (ReverseDepIt != ReverseLocalDeps.end()) {
1592 // RemInst can't be the terminator if it has local stuff depending on it.
1593 assert(!ReverseDepIt->second.empty() && !RemInst->isTerminator() &&
1594 "Nothing can locally depend on a terminator");
1595
1596 for (Instruction *InstDependingOnRemInst : ReverseDepIt->second) {
1597 assert(InstDependingOnRemInst != RemInst &&
1598 "Already removed our local dep info");
1599
1600 LocalDeps[InstDependingOnRemInst] = NewDirtyVal;
1601
1602 // Make sure to remember that new things depend on NewDepInst.
1603 assert(NewDirtyVal.getInst() &&
1604 "There is no way something else can have "
1605 "a local dep on this if it is a terminator!");
1606 ReverseDepsToAdd.push_back(
1607 std::make_pair(NewDirtyVal.getInst(), InstDependingOnRemInst));
1608 }
1609
1610 ReverseLocalDeps.erase(ReverseDepIt);
1611
1612 // Add new reverse deps after scanning the set, to avoid invalidating the
1613 // 'ReverseDeps' reference.
1614 while (!ReverseDepsToAdd.empty()) {
1615 ReverseLocalDeps[ReverseDepsToAdd.back().first].insert(
1616 ReverseDepsToAdd.back().second);
1617 ReverseDepsToAdd.pop_back();
1618 }
1619 }
1620
1621 ReverseDepIt = ReverseNonLocalDeps.find(RemInst);
1622 if (ReverseDepIt != ReverseNonLocalDeps.end()) {
1623 for (Instruction *I : ReverseDepIt->second) {
1624 assert(I != RemInst && "Already removed NonLocalDep info for RemInst");
1625
1626 PerInstNLInfo &INLD = NonLocalDepsMap[I];
1627 // The information is now dirty!
1628 INLD.second = true;
1629
1630 for (auto &Entry : INLD.first) {
1631 if (Entry.getResult().getInst() != RemInst)
1632 continue;
1633
1634 // Convert to a dirty entry for the subsequent instruction.
1635 Entry.setResult(NewDirtyVal);
1636
1637 if (Instruction *NextI = NewDirtyVal.getInst())
1638 ReverseDepsToAdd.push_back(std::make_pair(NextI, I));
1639 }
1640 }
1641
1642 ReverseNonLocalDeps.erase(ReverseDepIt);
1643
1644 // Add new reverse deps after scanning the set, to avoid invalidating 'Set'
1645 while (!ReverseDepsToAdd.empty()) {
1646 ReverseNonLocalDeps[ReverseDepsToAdd.back().first].insert(
1647 ReverseDepsToAdd.back().second);
1648 ReverseDepsToAdd.pop_back();
1649 }
1650 }
1651
1652 // If the instruction is in ReverseNonLocalPtrDeps then it appears as a
1653 // value in the NonLocalPointerDeps info.
1654 ReverseNonLocalPtrDepTy::iterator ReversePtrDepIt =
1655 ReverseNonLocalPtrDeps.find(RemInst);
1656 if (ReversePtrDepIt != ReverseNonLocalPtrDeps.end()) {
1658 ReversePtrDepsToAdd;
1659
1660 for (ValueIsLoadPair P : ReversePtrDepIt->second) {
1661 assert(P.getPointer() != RemInst &&
1662 "Already removed NonLocalPointerDeps info for RemInst");
1663
1664 auto &NLPD = NonLocalPointerDeps[P];
1665
1666 NonLocalDepInfo &NLPDI = NLPD.NonLocalDeps;
1667
1668 // The cache is not valid for any specific block anymore.
1669 NLPD.Pair = BBSkipFirstBlockPair();
1670
1671 // Update any entries for RemInst to use the instruction after it.
1672 for (auto &Entry : NLPDI) {
1673 if (Entry.getResult().getInst() != RemInst)
1674 continue;
1675
1676 // Convert to a dirty entry for the subsequent instruction.
1677 Entry.setResult(NewDirtyVal);
1678
1679 if (Instruction *NewDirtyInst = NewDirtyVal.getInst())
1680 ReversePtrDepsToAdd.push_back(std::make_pair(NewDirtyInst, P));
1681 }
1682
1683 // Re-sort the NonLocalDepInfo. Changing the dirty entry to its
1684 // subsequent value may invalidate the sortedness.
1685 llvm::sort(NLPDI);
1686 }
1687
1688 ReverseNonLocalPtrDeps.erase(ReversePtrDepIt);
1689
1690 while (!ReversePtrDepsToAdd.empty()) {
1691 ReverseNonLocalPtrDeps[ReversePtrDepsToAdd.back().first].insert(
1692 ReversePtrDepsToAdd.back().second);
1693 ReversePtrDepsToAdd.pop_back();
1694 }
1695 }
1696
1697 assert(!NonLocalDepsMap.count(RemInst) && "RemInst got reinserted?");
1698 LLVM_DEBUG(verifyRemoved(RemInst));
1699}
1700
1701/// Verify that the specified instruction does not occur in our internal data
1702/// structures.
1703///
1704/// This function verifies by asserting in debug builds.
1705void MemoryDependenceResults::verifyRemoved(Instruction *D) const {
1706#ifndef NDEBUG
1707 for (const auto &DepKV : LocalDeps) {
1708 assert(DepKV.first != D && "Inst occurs in data structures");
1709 assert(DepKV.second.getInst() != D && "Inst occurs in data structures");
1710 }
1711
1712 for (const auto &DepKV : NonLocalPointerDeps) {
1713 assert(DepKV.first.getPointer() != D && "Inst occurs in NLPD map key");
1714 for (const auto &Entry : DepKV.second.NonLocalDeps)
1715 assert(Entry.getResult().getInst() != D && "Inst occurs as NLPD value");
1716 }
1717
1718 for (const auto &DepKV : NonLocalDepsMap) {
1719 assert(DepKV.first != D && "Inst occurs in data structures");
1720 const PerInstNLInfo &INLD = DepKV.second;
1721 for (const auto &Entry : INLD.first)
1722 assert(Entry.getResult().getInst() != D &&
1723 "Inst occurs in data structures");
1724 }
1725
1726 for (const auto &DepKV : ReverseLocalDeps) {
1727 assert(DepKV.first != D && "Inst occurs in data structures");
1728 for (Instruction *Inst : DepKV.second)
1729 assert(Inst != D && "Inst occurs in data structures");
1730 }
1731
1732 for (const auto &DepKV : ReverseNonLocalDeps) {
1733 assert(DepKV.first != D && "Inst occurs in data structures");
1734 for (Instruction *Inst : DepKV.second)
1735 assert(Inst != D && "Inst occurs in data structures");
1736 }
1737
1738 for (const auto &DepKV : ReverseNonLocalPtrDeps) {
1739 assert(DepKV.first != D && "Inst occurs in rev NLPD map");
1740
1741 for (ValueIsLoadPair P : DepKV.second)
1742 assert(P != ValueIsLoadPair(D, false) && P != ValueIsLoadPair(D, true) &&
1743 "Inst occurs in ReverseNonLocalPtrDeps map");
1744 }
1745#endif
1746}
1747
1748AnalysisKey MemoryDependenceAnalysis::Key;
1749
1752
1755 auto &AA = AM.getResult<AAManager>(F);
1756 auto &AC = AM.getResult<AssumptionAnalysis>(F);
1757 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1758 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1759 return MemoryDependenceResults(AA, AC, TLI, DT, DefaultBlockScanLimit);
1760}
1761
1763
1765 "Memory Dependence Analysis", false, true)
1771 "Memory Dependence Analysis", false, true)
1772
1774
1776
1778 MemDep.reset();
1779}
1780
1788
1790 FunctionAnalysisManager::Invalidator &Inv) {
1791 // Check whether our analysis is preserved.
1792 auto PAC = PA.getChecker<MemoryDependenceAnalysis>();
1793 if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<Function>>())
1794 // If not, give up now.
1795 return true;
1796
1797 // Check whether the analyses we depend on became invalid for any reason.
1798 if (Inv.invalidate<AAManager>(F, PA) ||
1799 Inv.invalidate<AssumptionAnalysis>(F, PA) ||
1800 Inv.invalidate<DominatorTreeAnalysis>(F, PA))
1801 return true;
1802
1803 // Otherwise this analysis result remains valid.
1804 return false;
1805}
1806
1808 return DefaultBlockScanLimit;
1809}
1810
1812 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1813 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1814 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1815 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1816 MemDep.emplace(AA, AC, TLI, DT, BlockScanLimit);
1817 return false;
1818}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool isLoad(int Opcode)
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Atomic ordering constants.
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
This file defines the DenseMap class.
Module.h This file contains the declarations for the Module class.
This defines the Use class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static const unsigned int NumResultsLimit
static cl::opt< unsigned > CacheGlobalLimit("memdep-cache-global-limit", cl::Hidden, cl::init(10000), cl::desc("The max number of entries allowed in a cache (default = 10000)"))
static ModRefInfo GetLocation(const Instruction *Inst, MemoryLocation &Loc, const TargetLibraryInfo &TLI)
If the given instruction references a specific memory location, fill in Loc with the details,...
static cl::opt< unsigned > BlockNumberLimit("memdep-block-number-limit", cl::Hidden, cl::init(200), cl::desc("The number of blocks to scan during memory " "dependency analysis (default = 200)"))
static void RemoveFromReverseMap(DenseMap< Instruction *, SmallPtrSet< KeyTy, 4 > > &ReverseMap, Instruction *Inst, KeyTy Val)
This is a helper function that removes Val from 'Inst's set in ReverseMap.
static void SortNonLocalDepInfoCache(MemoryDependenceResults::NonLocalDepInfo &Cache, unsigned NumSortedEntries)
Sort the NonLocalDepInfo cache, given a certain number of elements in the array that are already prop...
static void AssertSorted(MemoryDependenceResults::NonLocalDepInfo &Cache, int Count=-1)
This method is used when -debug is specified to verify that cache arrays are properly kept sorted.
static cl::opt< unsigned > BlockScanLimit("memdep-block-scan-limit", cl::Hidden, cl::init(100), cl::desc("The number of instructions to scan in a block in memory " "dependency analysis (default = 100)"))
This file provides utility analysis objects describing memory locations.
static bool isOrdered(const Instruction *I)
This file contains the declarations for metadata subclasses.
static bool isInvariantLoad(const Instruction *I, const Value *Ptr, const bool IsKernelFn)
uint64_t IntrinsicInst * II
#define P(N)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
const SmallVectorImpl< MachineOperand > & Cond
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
A manager for alias analyses.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
The possible results of an alias query.
@ NoAlias
The two locations do not alias at all.
@ PartialAlias
The two locations alias, but only due to a partial overlap.
@ MustAlias
The two locations precisely alias each other.
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
AnalysisUsage & addRequiredTransitive()
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:459
unsigned getNumber() const
Definition BasicBlock.h:95
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB)
bool isMustAlias(const MemoryLocation &LocA, const MemoryLocation &LocB)
ModRefInfo getModRefInfo(const Instruction *I, const std::optional< MemoryLocation > &OptLoc)
ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, bool IgnoreLocals=false)
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
bool erase(const KeyT &Val)
Definition DenseMap.h:426
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT > iterator
Definition DenseMap.h:168
bool empty() const
Definition DenseMap.h:206
iterator end()
Definition DenseMap.h:176
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
An instruction for ordering other memory operations.
FunctionPass(char &pid)
Definition Pass.h:316
const BasicBlock & getEntryBlock() const
Definition Function.h:794
unsigned getMaxBlockNumber() const
Return a value larger than the largest block number.
Definition Function.h:813
LLVM_ABI bool mayWriteToMemory() const LLVM_READONLY
Return true if this instruction may modify memory.
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
LLVM_ABI bool isIdenticalToWhenDefined(const Instruction *I, bool IntersectAttrs=false) const LLVM_READONLY
This is like isIdenticalTo, except that it ignores the SubclassOptionalData flags,...
bool isTerminator() const
LLVM_ABI bool mayReadFromMemory() const LLVM_READONLY
Return true if this instruction may read memory.
LLVM_ABI bool isVolatile() const LLVM_READONLY
Return true if this instruction has a volatile memory access.
A wrapper class for inspecting calls to intrinsic functions.
An instruction for reading from memory.
Value * getPointerOperand()
A memory dependence query can return one of three different answers.
bool isNonLocal() const
Tests if this MemDepResult represents a query that is transparent to the start of the block,...
static MemDepResult getNonLocal()
bool isNonFuncLocal() const
Tests if this MemDepResult represents a query that is transparent to the start of the function.
static MemDepResult getSelect()
static MemDepResult getClobber(Instruction *Inst)
bool isDef() const
Tests if this MemDepResult represents a query that is an instruction definition dependency.
static MemDepResult getUnknown()
bool isLocal() const
Tests if this MemDepResult represents a valid local query (Clobber/Def).
bool isUnknown() const
Tests if this MemDepResult represents a query which cannot and/or will not be computed.
static MemDepResult getNonFuncLocal()
static MemDepResult getDef(Instruction *Inst)
get methods: These are static ctor methods for creating various MemDepResult kinds.
Instruction * getInst() const
If this is a normal dependency, returns the instruction that is depended on.
An analysis that produces MemoryDependenceResults for a function.
LLVM_ABI MemoryDependenceResults run(Function &F, FunctionAnalysisManager &AM)
Provides a lazy, caching interface for making common memory aliasing information queries,...
LLVM_ABI MemDepResult getSimplePointerDependencyFrom(const MemoryLocation &MemLoc, bool isLoad, BasicBlock::iterator ScanIt, BasicBlock *BB, Instruction *QueryInst, unsigned *Limit, BatchAAResults &BatchAA)
std::vector< NonLocalDepEntry > NonLocalDepInfo
LLVM_ABI void invalidateCachedPredecessors()
Clears the PredIteratorCache info.
LLVM_ABI void invalidateCachedPointerInfo(Value *Ptr)
Invalidates cached information about the specified pointer, because it may be too conservative in mem...
LLVM_ABI MemDepResult getPointerDependencyFrom(const MemoryLocation &Loc, bool isLoad, BasicBlock::iterator ScanIt, BasicBlock *BB, Instruction *QueryInst=nullptr, unsigned *Limit=nullptr)
Returns the instruction on which a memory location depends.
LLVM_ABI void removeInstruction(Instruction *InstToRemove)
Removes an instruction from the dependence analysis, updating the dependence of instructions that pre...
LLVM_ABI MemDepResult getInvariantGroupPointerDependency(LoadInst *LI, BasicBlock *BB)
This analysis looks for other loads and stores with invariant.group metadata and the same pointer ope...
LLVM_ABI unsigned getDefaultBlockScanLimit() const
Some methods limit the number of instructions they will examine.
LLVM_ABI MemDepResult getDependency(Instruction *QueryInst)
Returns the instruction on which a memory operation depends.
LLVM_ABI const NonLocalDepInfo & getNonLocalCallDependency(CallBase *QueryCall)
Perform a full dependency query for the specified call, returning the set of blocks that the value is...
LLVM_ABI void getNonLocalPointerDependency(Instruction *QueryInst, SmallVectorImpl< NonLocalDepResult > &Result)
Perform a full dependency query for an access to the QueryInst's specified memory location,...
LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
Handle invalidation in the new PM.
A wrapper analysis pass for the legacy pass manager that exposes a MemoryDepnedenceResults instance.
bool runOnFunction(Function &) override
Pass Implementation stuff. This doesn't do any analysis eagerly.
void getAnalysisUsage(AnalysisUsage &AU) const override
Does not modify anything. It uses Value Numbering and Alias Analysis.
void releaseMemory() override
Clean up memory in between runs.
Representation for a specific memory location.
MemoryLocation getWithoutAATags() const
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
LocationSize Size
The maximum size of the location, in address-units, or UnknownSize if the size is not known.
static MemoryLocation getAfter(const Value *Ptr, const AAMDNodes &AATags=AAMDNodes())
Return a location that may access any location after Ptr, while remaining within the underlying objec...
MemoryLocation getWithNewPtr(const Value *NewPtr) const
AAMDNodes AATags
The metadata nodes which describes the aliasing of the location (each member is null if that kind of ...
const Value * Ptr
The address of the start of the location.
static LLVM_ABI MemoryLocation getForArgument(const CallBase *Call, unsigned ArgIdx, const TargetLibraryInfo *TLI)
Return a location representing a particular argument of a call.
This is an entry in the NonLocalDepInfo cache.
void setResult(const MemDepResult &R)
const MemDepResult & getResult() const
This is a result from a NonLocal dependence query.
PHITransAddr - An address value which tracks and handles phi translation.
LLVM_ABI Value * translateValue(BasicBlock *CurBB, BasicBlock *PredBB, const DominatorTree *DT, bool MustDominate)
translateValue - PHI translate the current address up the CFG from CurBB to Pred, updating our state ...
LLVM_ABI Value * getSelectCondition() const
If the address expression depends on a select instruction (possibly through casts or GEPs),...
Value * getAddr() const
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
std::pair< Value *, Value * > SelectAddrs
size_type size() const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition Value.cpp:1002
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:713
iterator_range< use_iterator > uses()
Definition Value.h:382
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
CallInst * Call
Abstract Attribute helper functions.
Definition Attributor.h:165
@ Entry
Definition COFF.h:862
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
initializer< Ty > init(const Ty &Val)
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool isStorePreservingMemoryLocation(const StoreInst *SI, const MemoryLocation &MemLoc, Align MemLocAlign, BatchAAResults &AA, unsigned ScanLimit)
Check whether SI, which may alias MemLoc, can be safely skipped.
Definition Loads.cpp:816
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
bool isStrongerThanUnordered(AtomicOrdering AO)
LLVM_ABI bool isNoAliasCall(const Value *V)
Return true if this pointer is returned by a noalias function.
const Value * getPointerOperand(const Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
bool isModOrRefSet(const ModRefInfo MRI)
Definition ModRef.h:43
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
AtomicOrdering
Atomic ordering for LLVM's memory model.
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
Definition ModRef.h:28
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
@ ModRef
The access may reference and may modify the value stored in memory.
Definition ModRef.h:36
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
@ NoModRef
The access neither references nor modifies the value stored in memory.
Definition ModRef.h:30
@ Other
Any other memory.
Definition ModRef.h:68
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
LLVM_ABI Value * getFreedOperand(const CallBase *CB, const TargetLibraryInfo *TLI)
If this if a call to a free function, return the freed operand.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
bool isNoModRef(const ModRefInfo MRI)
Definition ModRef.h:40
bool isStrongerThan(AtomicOrdering AO, AtomicOrdering Other)
Returns true if ao is stronger than other as defined by the AtomicOrdering lattice,...
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29