LLVM 24.0.0git
MemorySSA.h
Go to the documentation of this file.
1//===- MemorySSA.h - Build Memory SSA ---------------------------*- C++ -*-===//
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/// \file
10/// This file exposes an interface to building/using memory SSA to
11/// walk memory instructions using a use/def graph.
12///
13/// Memory SSA class builds an SSA form that links together memory access
14/// instructions such as loads, stores, atomics, and calls. Additionally, it
15/// does a trivial form of "heap versioning" Every time the memory state changes
16/// in the program, we generate a new heap version. It generates
17/// MemoryDef/Uses/Phis that are overlayed on top of the existing instructions.
18///
19/// As a trivial example,
20/// define i32 @main() #0 {
21/// entry:
22/// %call = call noalias i8* @_Znwm(i64 4) #2
23/// %0 = bitcast i8* %call to i32*
24/// %call1 = call noalias i8* @_Znwm(i64 4) #2
25/// %1 = bitcast i8* %call1 to i32*
26/// store i32 5, i32* %0, align 4
27/// store i32 7, i32* %1, align 4
28/// %2 = load i32* %0, align 4
29/// %3 = load i32* %1, align 4
30/// %add = add nsw i32 %2, %3
31/// ret i32 %add
32/// }
33///
34/// Will become
35/// define i32 @main() #0 {
36/// entry:
37/// ; 1 = MemoryDef(0)
38/// %call = call noalias i8* @_Znwm(i64 4) #3
39/// %2 = bitcast i8* %call to i32*
40/// ; 2 = MemoryDef(1)
41/// %call1 = call noalias i8* @_Znwm(i64 4) #3
42/// %4 = bitcast i8* %call1 to i32*
43/// ; 3 = MemoryDef(2)
44/// store i32 5, i32* %2, align 4
45/// ; 4 = MemoryDef(3)
46/// store i32 7, i32* %4, align 4
47/// ; MemoryUse(3)
48/// %7 = load i32* %2, align 4
49/// ; MemoryUse(4)
50/// %8 = load i32* %4, align 4
51/// %add = add nsw i32 %7, %8
52/// ret i32 %add
53/// }
54///
55/// Given this form, all the stores that could ever effect the load at %8 can be
56/// gotten by using the MemoryUse associated with it, and walking from use to
57/// def until you hit the top of the function.
58///
59/// Each def also has a list of users associated with it, so you can walk from
60/// both def to users, and users to defs. Note that we disambiguate MemoryUses,
61/// but not the RHS of MemoryDefs. You can see this above at %7, which would
62/// otherwise be a MemoryUse(4). Being disambiguated means that for a given
63/// store, all the MemoryUses on its use lists are may-aliases of that store
64/// (but the MemoryDefs on its use list may not be).
65///
66/// MemoryDefs are not disambiguated because it would require multiple reaching
67/// definitions, which would require multiple phis, and multiple memoryaccesses
68/// per instruction.
69///
70/// In addition to the def/use graph described above, MemoryDefs also contain
71/// an "optimized" definition use. The "optimized" use points to some def
72/// reachable through the memory def chain. The optimized def *may* (but is
73/// not required to) alias the original MemoryDef, but no def *closer* to the
74/// source def may alias it. As the name implies, the purpose of the optimized
75/// use is to allow caching of clobber searches for memory defs. The optimized
76/// def may be nullptr, in which case clients must walk the defining access
77/// chain.
78///
79/// When iterating the uses of a MemoryDef, both defining uses and optimized
80/// uses will be encountered. If only one type is needed, the client must
81/// filter the use walk.
82//
83//===----------------------------------------------------------------------===//
84
85#ifndef LLVM_ANALYSIS_MEMORYSSA_H
86#define LLVM_ANALYSIS_MEMORYSSA_H
87
88#include "llvm/ADT/DenseMap.h"
91#include "llvm/ADT/ilist_node.h"
96#include "llvm/IR/DerivedUser.h"
97#include "llvm/IR/Dominators.h"
98#include "llvm/IR/Type.h"
99#include "llvm/IR/User.h"
100#include "llvm/Pass.h"
102#include <algorithm>
103#include <cassert>
104#include <cstddef>
105#include <iterator>
106#include <memory>
107#include <utility>
108
109namespace llvm {
110
111struct AnalysisOptions;
112template <class GraphType> struct GraphTraits;
113class Function;
114class Loop;
115class LLVMContext;
116class MemoryAccess;
117class MemorySSAWalker;
118class Module;
119class raw_ostream;
120
121namespace MSSAHelpers {
122
123struct AllAccessTag {};
124struct DefsOnlyTag {};
125
126} // end namespace MSSAHelpers
127
128enum : unsigned {
129 // Used to signify what the default invalid ID is for MemoryAccess's
130 // getID()
132};
133
134template <class T> class memoryaccess_def_iterator_base;
138
139// The base for all memory accesses. All memory accesses in a block are
140// linked together using an intrusive list.
142 : public DerivedUser,
143 public ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::AllAccessTag>>,
144 public ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::DefsOnlyTag>> {
145public:
150
151 MemoryAccess(const MemoryAccess &) = delete;
153
154 void *operator new(size_t) = delete;
155
156 // Methods for support type inquiry through isa, cast, and
157 // dyn_cast
158 static bool classof(const Value *V) {
159 unsigned ID = V->getValueID();
160 return ID == MemoryUseVal || ID == MemoryPhiVal || ID == MemoryDefVal;
161 }
162
163 BasicBlock *getBlock() const { return Block; }
164
165 LLVM_ABI void print(raw_ostream &OS) const;
166 LLVM_ABI void dump() const;
167
168 /// The user iterators for a memory access
171
172 /// This iterator walks over all of the defs in a given
173 /// MemoryAccess. For MemoryPhi nodes, this walks arguments. For
174 /// MemoryUse/MemoryDef, this walks the defining access.
179
180 /// Get the iterators for the all access list and the defs only list
181 /// We default to the all access list.
206
207protected:
208 friend class MemoryDef;
209 friend class MemoryPhi;
210 friend class MemorySSA;
211 friend class MemoryUse;
212 friend class MemoryUseOrDef;
213
214 /// Used by MemorySSA to change the block of a MemoryAccess when it is
215 /// moved.
216 void setBlock(BasicBlock *BB) { Block = BB; }
217
218 /// Used for debugging and tracking things about MemoryAccesses.
219 /// Guaranteed unique among MemoryAccesses, no guarantees otherwise.
220 inline unsigned getID() const;
221
222 MemoryAccess(LLVMContext &C, unsigned Vty, DeleteValueTy DeleteValue,
224 : DerivedUser(Type::getVoidTy(C), Vty, AllocInfo, DeleteValue),
225 Block(BB) {}
226
227 // Use deleteValue() to delete a generic MemoryAccess.
228 ~MemoryAccess() = default;
229
230private:
231 BasicBlock *Block;
232};
233
234template <>
236 static void deleteNode(MemoryAccess *MA) { MA->deleteValue(); }
237};
238
240 MA.print(OS);
241 return OS;
242}
243
244/// Class that has the common methods + fields of memory uses/defs. It's
245/// a little awkward to have, but there are many cases where we want either a
246/// use or def, and there are many cases where uses are needed (defs aren't
247/// acceptable), and vice-versa.
248///
249/// This class should never be instantiated directly; make a MemoryUse or
250/// MemoryDef instead.
252public:
253 void *operator new(size_t) = delete;
254
256
257 /// Get the instruction that this MemoryUse represents.
258 Instruction *getMemoryInst() const { return MemoryInstruction; }
259
260 /// Get the access that produces the memory state used by this Use.
262
263 static bool classof(const Value *MA) {
264 return MA->getValueID() == MemoryUseVal || MA->getValueID() == MemoryDefVal;
265 }
266
267 /// Do we have an optimized use?
268 inline bool isOptimized() const;
269 /// Return the MemoryAccess associated with the optimized use, or nullptr.
270 inline MemoryAccess *getOptimized() const;
271 /// Sets the optimized use for a MemoryDef.
272 inline void setOptimized(MemoryAccess *);
273
274 /// Reset the ID of what this MemoryUse was optimized to, causing it to
275 /// be rewalked by the walker if necessary.
276 /// This really should only be called by tests.
277 inline void resetOptimized();
278
279protected:
280 friend class MemorySSA;
281 friend class MemorySSAUpdater;
282
284 DeleteValueTy DeleteValue, Instruction *MI, BasicBlock *BB,
286 : MemoryAccess(C, Vty, DeleteValue, BB, AllocInfo),
287 MemoryInstruction(MI) {
289 }
290
291 // Use deleteValue() to delete a generic MemoryUseOrDef.
292 ~MemoryUseOrDef() = default;
293
294 void setDefiningAccess(MemoryAccess *DMA, bool Optimized = false) {
295 if (!Optimized) {
296 setOperand(0, DMA);
297 return;
298 }
299 setOptimized(DMA);
300 }
301
302private:
303 Instruction *MemoryInstruction;
304};
305
306/// Represents read-only accesses to memory
307///
308/// In particular, the set of Instructions that will be represented by
309/// MemoryUse's is exactly the set of Instructions for which
310/// AliasAnalysis::getModRefInfo returns "Ref".
311class MemoryUse final : public MemoryUseOrDef {
312 constexpr static IntrusiveOperandsAllocMarker AllocMarker{1};
313
314public:
316
318 : MemoryUseOrDef(C, DMA, MemoryUseVal, deleteMe, MI, BB, AllocMarker) {}
319
320 // allocate space for exactly one operand
321 void *operator new(size_t S) { return User::operator new(S, AllocMarker); }
322 void operator delete(void *Ptr) { User::operator delete(Ptr, AllocMarker); }
323
324 static bool classof(const Value *MA) {
325 return MA->getValueID() == MemoryUseVal;
326 }
327
328 LLVM_ABI void print(raw_ostream &OS) const;
329
331 OptimizedID = DMA->getID();
332 setOperand(0, DMA);
333 }
334
335 /// Whether the MemoryUse is optimized. If ensureOptimizedUses() was called,
336 /// uses will usually be optimized, but this is not guaranteed (e.g. due to
337 /// invalidation and optimization limits.)
338 bool isOptimized() const {
339 return getDefiningAccess() && OptimizedID == getDefiningAccess()->getID();
340 }
341
343 return getDefiningAccess();
344 }
345
347 OptimizedID = INVALID_MEMORYACCESS_ID;
348 }
349
350protected:
351 friend class MemorySSA;
352
353private:
354 static void deleteMe(DerivedUser *Self);
355
356 unsigned OptimizedID = INVALID_MEMORYACCESS_ID;
357};
358
359template <>
360struct OperandTraits<MemoryUse> : public FixedNumOperandTraits<MemoryUse, 1> {};
362
363/// Represents a read-write access to memory, whether it is a must-alias,
364/// or a may-alias.
365///
366/// In particular, the set of Instructions that will be represented by
367/// MemoryDef's is exactly the set of Instructions for which
368/// AliasAnalysis::getModRefInfo returns "Mod" or "ModRef".
369/// Note that, in order to provide def-def chains, all defs also have a use
370/// associated with them. This use points to the nearest reaching
371/// MemoryDef/MemoryPhi.
372class MemoryDef final : public MemoryUseOrDef {
373 constexpr static IntrusiveOperandsAllocMarker AllocMarker{2};
374
375public:
376 friend class MemorySSA;
377
379
381 unsigned Ver)
382 : MemoryUseOrDef(C, DMA, MemoryDefVal, deleteMe, MI, BB, AllocMarker),
383 ID(Ver) {}
384
385 // allocate space for exactly two operands
386 void *operator new(size_t S) { return User::operator new(S, AllocMarker); }
387 void operator delete(void *Ptr) { User::operator delete(Ptr, AllocMarker); }
388
389 static bool classof(const Value *MA) {
390 return MA->getValueID() == MemoryDefVal;
391 }
392
394 setOperand(1, MA);
395 OptimizedID = MA->getID();
396 }
397
401
402 bool isOptimized() const {
403 return getOptimized() && OptimizedID == getOptimized()->getID();
404 }
405
407 OptimizedID = INVALID_MEMORYACCESS_ID;
408 setOperand(1, nullptr);
409 }
410
411 LLVM_ABI void print(raw_ostream &OS) const;
412
413 unsigned getID() const { return ID; }
414
415private:
416 static void deleteMe(DerivedUser *Self);
417
418 const unsigned ID;
419 unsigned OptimizedID = INVALID_MEMORYACCESS_ID;
420};
421
422template <>
423struct OperandTraits<MemoryDef> : public FixedNumOperandTraits<MemoryDef, 2> {};
425
426template <>
429 if (auto *MU = dyn_cast<MemoryUse>(MUD))
432 }
433
434 static Use *op_end(MemoryUseOrDef *MUD) {
435 if (auto *MU = dyn_cast<MemoryUse>(MUD))
438 }
439
440 static unsigned operands(const MemoryUseOrDef *MUD) {
441 if (const auto *MU = dyn_cast<MemoryUse>(MUD))
444 }
445};
446DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryUseOrDef, MemoryAccess)
447
448/// Represents phi nodes for memory accesses.
449///
450/// These have the same semantic as regular phi nodes, with the exception that
451/// only one phi will ever exist in a given basic block.
452/// Guaranteeing one phi per block means guaranteeing there is only ever one
453/// valid reaching MemoryDef/MemoryPHI along each path to the phi node.
454/// This is ensured by not allowing disambiguation of the RHS of a MemoryDef or
455/// a MemoryPhi's operands.
456/// That is, given
457/// if (a) {
458/// store %a
459/// store %b
460/// }
461/// it *must* be transformed into
462/// if (a) {
463/// 1 = MemoryDef(liveOnEntry)
464/// store %a
465/// 2 = MemoryDef(1)
466/// store %b
467/// }
468/// and *not*
469/// if (a) {
470/// 1 = MemoryDef(liveOnEntry)
471/// store %a
472/// 2 = MemoryDef(liveOnEntry)
473/// store %b
474/// }
475/// even if the two stores do not conflict. Otherwise, both 1 and 2 reach the
476/// end of the branch, and if there are not two phi nodes, one will be
477/// disconnected completely from the SSA graph below that point.
478/// Because MemoryUse's do not generate new definitions, they do not have this
479/// issue.
480class MemoryPhi final : public MemoryAccess {
481 constexpr static HungOffOperandsAllocMarker AllocMarker{};
482
483 // allocate space for exactly zero operands
484 void *operator new(size_t S) { return User::operator new(S, AllocMarker); }
485
486public:
487 void operator delete(void *Ptr) { User::operator delete(Ptr, AllocMarker); }
488
489 /// Provide fast operand accessors
491
492 MemoryPhi(LLVMContext &C, BasicBlock *BB, unsigned Ver, unsigned NumPreds = 0)
493 : MemoryAccess(C, MemoryPhiVal, deleteMe, BB, AllocMarker), ID(Ver),
494 ReservedSpace(NumPreds) {
495 allocHungoffUses(ReservedSpace);
496 }
497
498 // Block iterator interface. This provides access to the list of incoming
499 // basic blocks, which parallels the list of incoming values.
502
504 return reinterpret_cast<block_iterator>(op_begin() + ReservedSpace);
505 }
506
508 return reinterpret_cast<const_block_iterator>(op_begin() + ReservedSpace);
509 }
510
512
514 return block_begin() + getNumOperands();
515 }
516
520
524
526
528
529 /// Return the number of incoming edges
530 unsigned getNumIncomingValues() const { return getNumOperands(); }
531
532 /// Return incoming value number x
533 MemoryAccess *getIncomingValue(unsigned I) const { return getOperand(I); }
534 void setIncomingValue(unsigned I, MemoryAccess *V) {
535 assert(V && "PHI node got a null value!");
536 setOperand(I, V);
537 }
538
539 static unsigned getOperandNumForIncomingValue(unsigned I) { return I; }
540 static unsigned getIncomingValueNumForOperand(unsigned I) { return I; }
541
542 /// Return incoming basic block number @p i.
543 BasicBlock *getIncomingBlock(unsigned I) const { return block_begin()[I]; }
544
545 /// Return incoming basic block corresponding
546 /// to an operand of the PHI.
547 BasicBlock *getIncomingBlock(const Use &U) const {
548 assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?");
549 return getIncomingBlock(unsigned(&U - op_begin()));
550 }
551
552 /// Return incoming basic block corresponding
553 /// to value use iterator.
557
558 void setIncomingBlock(unsigned I, BasicBlock *BB) {
559 assert(BB && "PHI node got a null basic block!");
560 block_begin()[I] = BB;
561 }
562
563 /// Add an incoming value to the end of the PHI list
565 if (getNumOperands() == ReservedSpace)
566 growOperands(); // Get more space!
567 // Initialize some new operands.
571 }
572
573 /// Return the first index of the specified basic
574 /// block in the value list for this PHI. Returns -1 if no instance.
575 int getBasicBlockIndex(const BasicBlock *BB) const {
576 for (unsigned I = 0, E = getNumOperands(); I != E; ++I)
577 if (block_begin()[I] == BB)
578 return I;
579 return -1;
580 }
581
583 int Idx = getBasicBlockIndex(BB);
584 assert(Idx >= 0 && "Invalid basic block argument!");
585 return getIncomingValue(Idx);
586 }
587
588 // After deleting incoming position I, the order of incoming may be changed.
589 void unorderedDeleteIncoming(unsigned I) {
590 unsigned E = getNumOperands();
591 assert(I < E && "Cannot remove out of bounds Phi entry.");
592 // MemoryPhi must have at least two incoming values, otherwise the MemoryPhi
593 // itself should be deleted.
594 assert(E >= 2 && "Cannot only remove incoming values in MemoryPhis with "
595 "at least 2 values.");
598 setOperand(E - 1, nullptr);
599 block_begin()[E - 1] = nullptr;
601 }
602
603 // After deleting entries that satisfy Pred, remaining entries may have
604 // changed order.
605 template <typename Fn> void unorderedDeleteIncomingIf(Fn &&Pred) {
606 for (unsigned I = 0, E = getNumOperands(); I != E; ++I)
607 if (Pred(getIncomingValue(I), getIncomingBlock(I))) {
609 E = getNumOperands();
610 --I;
611 }
612 assert(getNumOperands() >= 1 &&
613 "Cannot remove all incoming blocks in a MemoryPhi.");
614 }
615
616 // After deleting incoming block BB, the incoming blocks order may be changed.
619 [&](const MemoryAccess *, const BasicBlock *B) { return BB == B; });
620 }
621
622 static bool classof(const Value *V) {
623 return V->getValueID() == MemoryPhiVal;
624 }
625
626 LLVM_ABI void print(raw_ostream &OS) const;
627
628 unsigned getID() const { return ID; }
629
630protected:
631 friend class MemorySSA;
632
633 /// this is more complicated than the generic
634 /// User::allocHungoffUses, because we have to allocate Uses for the incoming
635 /// values and pointers to the incoming blocks, all in one allocation.
636 void allocHungoffUses(unsigned N) {
637 User::allocHungoffUses(N, /* IsPhi */ true);
638 }
639
640private:
641 // For debugging only
642 const unsigned ID;
643 unsigned ReservedSpace;
644
645 /// This grows the operand list in response to a push_back style of
646 /// operation. This grows the number of ops by 1.5 times.
647 void growOperands() {
648 unsigned E = getNumOperands();
649 // 2 op PHI nodes are VERY common, so reserve at least enough for that.
650 ReservedSpace = std::max(E + E / 2, 2u);
651 growHungoffUses(ReservedSpace, /* IsPhi */ true);
652 }
653
654 static void deleteMe(DerivedUser *Self);
655};
656
657inline unsigned MemoryAccess::getID() const {
658 assert((isa<MemoryDef>(this) || isa<MemoryPhi>(this)) &&
659 "only memory defs and phis have ids");
660 if (const auto *MD = dyn_cast<MemoryDef>(this))
661 return MD->getID();
662 return cast<MemoryPhi>(this)->getID();
663}
664
665inline bool MemoryUseOrDef::isOptimized() const {
666 if (const auto *MD = dyn_cast<MemoryDef>(this))
667 return MD->isOptimized();
668 return cast<MemoryUse>(this)->isOptimized();
669}
670
672 if (const auto *MD = dyn_cast<MemoryDef>(this))
673 return MD->getOptimized();
674 return cast<MemoryUse>(this)->getOptimized();
675}
676
678 if (auto *MD = dyn_cast<MemoryDef>(this))
679 MD->setOptimized(MA);
680 else
681 cast<MemoryUse>(this)->setOptimized(MA);
682}
683
685 if (auto *MD = dyn_cast<MemoryDef>(this))
686 MD->resetOptimized();
687 else
688 cast<MemoryUse>(this)->resetOptimized();
689}
690
691template <> struct OperandTraits<MemoryPhi> : public HungoffOperandTraits {};
693
694/// Encapsulates MemorySSA, including all data associated with memory
695/// accesses.
697public:
700
701 // MemorySSA must remain where it's constructed; Walkers it creates store
702 // pointers to it.
703 MemorySSA(MemorySSA &&) = delete;
704
706
709
710 /// Given a memory Mod/Ref'ing instruction, get the MemorySSA
711 /// access associated with it. If passed a basic block gets the memory phi
712 /// node that exists for that block, if there is one. Otherwise, this will get
713 /// a MemoryUseOrDef.
715 return cast_or_null<MemoryUseOrDef>(ValueToMemoryAccess.lookup(I));
716 }
717
719 return cast_or_null<MemoryPhi>(ValueToMemoryAccess.lookup(cast<Value>(BB)));
720 }
721
722 DominatorTree &getDomTree() const { return *DT; }
723
724 LLVM_ABI void dump() const;
725 LLVM_ABI void print(raw_ostream &) const;
726
727 /// Return true if \p MA represents the live on entry value
728 ///
729 /// Loads and stores from pointer arguments and other global values may be
730 /// defined by memory operations that do not occur in the current function, so
731 /// they may be live on entry to the function. MemorySSA represents such
732 /// memory state by the live on entry definition, which is guaranteed to occur
733 /// before any other memory access in the function.
734 inline bool isLiveOnEntryDef(const MemoryAccess *MA) const {
735 return MA == LiveOnEntryDef.get();
736 }
737
739 return LiveOnEntryDef.get();
740 }
741
742 // Sadly, iplists, by default, owns and deletes pointers added to the
743 // list. It's not currently possible to have two iplists for the same type,
744 // where one owns the pointers, and one does not. This is because the traits
745 // are per-type, not per-tag. If this ever changes, we should make the
746 // DefList an iplist.
748 using DefsList =
750
751 /// Return the list of MemoryAccess's for a given basic block.
753 auto It = PerBlockAccesses.find(BB);
754 return It == PerBlockAccesses.end() ? nullptr : It->second.get();
755 }
756
757 /// Return the list of MemoryDef's and MemoryPhi's for a given basic
758 /// block.
759 DefsList *getBlockDefs(const BasicBlock *BB) const {
760 auto It = PerBlockDefs.find(BB);
761 return It == PerBlockDefs.end() ? nullptr : It->second.get();
762 }
763
764 /// Given two memory accesses in the same basic block, determine
765 /// whether MemoryAccess \p A dominates MemoryAccess \p B.
766 LLVM_ABI bool locallyDominates(const MemoryAccess *A,
767 const MemoryAccess *B) const;
768
769 /// Given two memory accesses in potentially different blocks,
770 /// determine whether MemoryAccess \p A dominates MemoryAccess \p B.
771 LLVM_ABI bool dominates(const MemoryAccess *A, const MemoryAccess *B) const;
772
773 /// Given a MemoryAccess and a Use, determine whether MemoryAccess \p A
774 /// dominates Use \p B.
775 LLVM_ABI bool dominates(const MemoryAccess *A, const Use &B) const;
776
777 enum class VerificationLevel { Fast, Full };
778 /// Verify that MemorySSA is self consistent (IE definitions dominate
779 /// all uses, uses appear in the right places). This is used by unit tests.
780 LLVM_ABI void
781 verifyMemorySSA(VerificationLevel = VerificationLevel::Fast) const;
782
783 /// Used in various insertion functions to specify whether we are talking
784 /// about the beginning or end of a block.
786
787 /// By default, uses are *not* optimized during MemorySSA construction.
788 /// Calling this method will attempt to optimize all MemoryUses, if this has
789 /// not happened yet for this MemorySSA instance. This should be done if you
790 /// plan to query the clobbering access for most uses, or if you walk the
791 /// def-use chain of uses.
792 LLVM_ABI void ensureOptimizedUses();
793
794 AliasAnalysis &getAA() { return *AA; }
795
796protected:
797 // Used by Memory SSA dumpers and wrapper pass
798 friend class MemorySSAUpdater;
799
800 template <typename IterT>
802 IterT Blocks, VerificationLevel = VerificationLevel::Fast) const;
803 template <typename IterT> void verifyDominationNumbers(IterT Blocks) const;
804 template <typename IterT> void verifyPrevDefInPhis(IterT Blocks) const;
805
806 // These is used by the updater to perform various internal MemorySSA
807 // machinsations. They do not always leave the IR in a correct state, and
808 // relies on the updater to fixup what it breaks, so it is not public.
809
812 LLVM_ABI void moveTo(MemoryAccess *What, BasicBlock *BB,
813 InsertionPlace Point);
814
815 // Rename the dominator tree branch rooted at BB.
816 void renamePass(BasicBlock *BB, MemoryAccess *IncomingVal,
818 renamePass(DT->getNode(BB), IncomingVal, Visited, true, true);
819 }
820
821 LLVM_ABI void removeFromLookups(MemoryAccess *);
822 LLVM_ABI void removeFromLists(MemoryAccess *, bool ShouldDelete = true);
823 LLVM_ABI void insertIntoListsForBlock(MemoryAccess *, const BasicBlock *,
824 InsertionPlace);
825 LLVM_ABI void insertIntoListsBefore(MemoryAccess *, const BasicBlock *,
826 AccessList::iterator);
828 createDefinedAccess(Instruction *, MemoryAccess *,
829 const MemoryUseOrDef *Template = nullptr,
830 bool CreationMustSucceed = true);
831
832private:
833 class ClobberWalkerBase;
834 class CachingWalker;
835 class SkipSelfWalker;
836 class OptimizeUses;
837
838 CachingWalker *getWalkerImpl();
839 template <typename IterT>
840 void buildMemorySSA(BatchAAResults &BAA, IterT Blocks);
841
842 void prepareForMoveTo(MemoryAccess *, BasicBlock *);
843 void verifyUseInDefs(MemoryAccess *, MemoryAccess *) const;
844
847
848 void markUnreachableAsLiveOnEntry(BasicBlock *BB);
849 MemoryPhi *createMemoryPhi(BasicBlock *BB);
850 template <typename AliasAnalysisType>
851 MemoryUseOrDef *createNewAccess(Instruction *, AliasAnalysisType *,
852 const MemoryUseOrDef *Template = nullptr);
853 void placePHINodes(const SmallPtrSetImpl<BasicBlock *> &);
854 MemoryAccess *renameBlock(BasicBlock *, MemoryAccess *, bool);
855 void renameSuccessorPhis(BasicBlock *, MemoryAccess *, bool);
856 LLVM_ABI void renamePass(DomTreeNode *, MemoryAccess *IncomingVal,
858 bool SkipVisited = false,
859 bool RenameAllUses = false);
860 AccessList *getOrCreateAccessList(const BasicBlock *);
861 DefsList *getOrCreateDefsList(const BasicBlock *);
862 void renumberBlock(const BasicBlock *) const;
863 const AnalysisOptions &Opts;
864 AliasAnalysis *AA = nullptr;
865 DominatorTree *DT;
866 Function *F = nullptr;
867 Loop *L = nullptr;
868
869 // Memory SSA mappings
870 DenseMap<const Value *, MemoryAccess *> ValueToMemoryAccess;
871
872 // These two mappings contain the main block to access/def mappings for
873 // MemorySSA. The list contained in PerBlockAccesses really owns all the
874 // MemoryAccesses.
875 // Both maps maintain the invariant that if a block is found in them, the
876 // corresponding list is not empty, and if a block is not found in them, the
877 // corresponding list is empty.
878 AccessMap PerBlockAccesses;
879 DefsMap PerBlockDefs;
880 std::unique_ptr<MemoryAccess, ValueDeleter> LiveOnEntryDef;
881
882 // Domination mappings
883 // Note that the numbering is local to a block, even though the map is
884 // global.
885 mutable SmallPtrSet<const BasicBlock *, 16> BlockNumberingValid;
887
888 // Memory SSA building info
889 std::unique_ptr<ClobberWalkerBase> WalkerBase;
890 std::unique_ptr<CachingWalker> Walker;
891 std::unique_ptr<SkipSelfWalker> SkipWalker;
892 unsigned NextID = 0;
893 bool IsOptimized = false;
894};
895
896/// Enables verification of MemorySSA.
897///
898/// The checks which this flag enables is exensive and disabled by default
899/// unless `EXPENSIVE_CHECKS` is defined. The flag `-verify-memoryssa` can be
900/// used to selectively enable the verification without re-compilation.
901LLVM_ABI extern bool VerifyMemorySSA;
902
903// Internal MemorySSA utils, for use by MemorySSA classes and walkers
905protected:
906 friend class GVNHoist;
907 friend class MemorySSAWalker;
908
909 // This function should not be used by new passes.
910 LLVM_ABI static bool defClobbersUseOrDef(MemoryDef *MD,
911 const MemoryUseOrDef *MU,
913};
914
915/// An analysis that produces \c MemorySSA for a function.
916///
917class MemorySSAAnalysis : public AnalysisInfoMixin<MemorySSAAnalysis> {
919
920 LLVM_ABI static AnalysisKey Key;
921
922public:
923 // Wrap MemorySSA result to ensure address stability of internal MemorySSA
924 // pointers after construction. Use a wrapper class instead of plain
925 // unique_ptr<MemorySSA> to avoid build breakage on MSVC.
926 struct Result {
927 Result(std::unique_ptr<MemorySSA> &&MSSA) : MSSA(std::move(MSSA)) {}
928
929 MemorySSA &getMSSA() { return *MSSA; }
930
931 std::unique_ptr<MemorySSA> MSSA;
932
934 FunctionAnalysisManager::Invalidator &Inv);
935 };
936
938};
939
940/// Printer pass for \c MemorySSA.
942 : public RequiredPassInfoMixin<MemorySSAPrinterPass> {
943 raw_ostream &OS;
944 bool EnsureOptimizedUses;
945
946public:
947 explicit MemorySSAPrinterPass(raw_ostream &OS, bool EnsureOptimizedUses)
948 : OS(OS), EnsureOptimizedUses(EnsureOptimizedUses) {}
949
951};
952
953/// Printer pass for \c MemorySSA via the walker.
955 : public RequiredPassInfoMixin<MemorySSAWalkerPrinterPass> {
956 raw_ostream &OS;
957
958public:
959 explicit MemorySSAWalkerPrinterPass(raw_ostream &OS) : OS(OS) {}
960
962};
963
964/// Verifier pass for \c MemorySSA.
968
969/// Legacy analysis pass which computes \c MemorySSA.
971public:
973
974 static char ID;
975
976 bool runOnFunction(Function &) override;
977 void releaseMemory() override;
978 MemorySSA &getMSSA() { return *MSSA; }
979 const MemorySSA &getMSSA() const { return *MSSA; }
980
981 void getAnalysisUsage(AnalysisUsage &AU) const override;
982
983 void verifyAnalysis() const override;
984 void print(raw_ostream &OS, const Module *M = nullptr) const override;
985
986private:
987 std::unique_ptr<MemorySSA> MSSA;
988};
989
990/// This is the generic walker interface for walkers of MemorySSA.
991/// Walkers are used to be able to further disambiguate the def-use chains
992/// MemorySSA gives you, or otherwise produce better info than MemorySSA gives
993/// you.
994/// In particular, while the def-use chains provide basic information, and are
995/// guaranteed to give, for example, the nearest may-aliasing MemoryDef for a
996/// MemoryUse as AliasAnalysis considers it, a user mant want better or other
997/// information. In particular, they may want to use SCEV info to further
998/// disambiguate memory accesses, or they may want the nearest dominating
999/// may-aliasing MemoryDef for a call or a store. This API enables a
1000/// standardized interface to getting and using that info.
1002public:
1004 virtual ~MemorySSAWalker() = default;
1005
1007
1008 /// Given a memory Mod/Ref/ModRef'ing instruction, calling this
1009 /// will give you the nearest dominating MemoryAccess that Mod's the location
1010 /// the instruction accesses (by skipping any def which AA can prove does not
1011 /// alias the location(s) accessed by the instruction given).
1012 ///
1013 /// Note that this will return a single access, and it must dominate the
1014 /// Instruction, so if an operand of a MemoryPhi node Mod's the instruction,
1015 /// this will return the MemoryPhi, not the operand. This means that
1016 /// given:
1017 /// if (a) {
1018 /// 1 = MemoryDef(liveOnEntry)
1019 /// store %a
1020 /// } else {
1021 /// 2 = MemoryDef(liveOnEntry)
1022 /// store %b
1023 /// }
1024 /// 3 = MemoryPhi(2, 1)
1025 /// MemoryUse(3)
1026 /// load %a
1027 ///
1028 /// calling this API on load(%a) will return the MemoryPhi, not the MemoryDef
1029 /// in the if (a) branch.
1031 BatchAAResults &AA) {
1032 MemoryAccess *MA = MSSA->getMemoryAccess(I);
1033 assert(MA && "Handed an instruction that MemorySSA doesn't recognize?");
1034 return getClobberingMemoryAccess(MA, AA);
1035 }
1036
1037 /// Does the same thing as getClobberingMemoryAccess(const Instruction *I),
1038 /// but takes a MemoryAccess instead of an Instruction.
1040 BatchAAResults &AA) = 0;
1041
1042 /// Given a potentially clobbering memory access and a new location,
1043 /// calling this will give you the nearest dominating clobbering MemoryAccess
1044 /// (by skipping non-aliasing def links).
1045 ///
1046 /// This version of the function is mainly used to disambiguate phi translated
1047 /// pointers, where the value of a pointer may have changed from the initial
1048 /// memory access. Note that this expects to be handed a potentially
1049 /// clobbering access (either a MemoryDef or a MemoryPhi). Unlike the above
1050 /// API, if given a MemoryDef that clobbers the pointer as the starting
1051 /// access, it will return that MemoryDef, whereas the above would return the
1052 /// clobber starting from the use side of the memory def.
1054 const MemoryLocation &,
1055 BatchAAResults &AA) = 0;
1056
1058 BatchAAResults BAA(MSSA->getAA());
1059 return getClobberingMemoryAccess(I, BAA);
1060 }
1061
1066
1068 const MemoryLocation &Loc) {
1069 BatchAAResults BAA(MSSA->getAA());
1070 return getClobberingMemoryAccess(MA, Loc, BAA);
1071 }
1072
1073 /// Given a memory access, invalidate anything this walker knows about
1074 /// that access.
1075 /// This API is used by walkers that store information to perform basic cache
1076 /// invalidation. This will be called by MemorySSA at appropriate times for
1077 /// the walker it uses or returns.
1078 virtual void invalidateInfo(MemoryAccess *) {}
1079
1080protected:
1081 friend class MemorySSA; // For updating MSSA pointer in MemorySSA move
1082 // constructor.
1084};
1085
1086/// A MemorySSAWalker that does no alias queries, or anything else. It
1087/// simply returns the links as they were constructed by the builder.
1089public:
1090 // Keep the overrides below from hiding the Instruction overload of
1091 // getClobberingMemoryAccess.
1093
1095 BatchAAResults &) override;
1097 const MemoryLocation &,
1098 BatchAAResults &) override;
1099};
1100
1101/// Iterator base class used to implement const and non-const iterators
1102/// over the defining accesses of a MemoryAccess.
1103template <class T>
1105 : public iterator_facade_base<memoryaccess_def_iterator_base<T>,
1106 std::forward_iterator_tag, T, ptrdiff_t, T *,
1107 T *> {
1108 using BaseT = typename memoryaccess_def_iterator_base::iterator_facade_base;
1109
1110public:
1111 memoryaccess_def_iterator_base(T *Start) : Access(Start) {}
1113
1115 return Access == Other.Access && (!Access || ArgNo == Other.ArgNo);
1116 }
1117
1118 // This is a bit ugly, but for MemoryPHI's, unlike PHINodes, you can't get the
1119 // block from the operand in constant time (In a PHINode, the uselist has
1120 // both, so it's just subtraction). We provide it as part of the
1121 // iterator to avoid callers having to linear walk to get the block.
1122 // If the operation becomes constant time on MemoryPHI's, this bit of
1123 // abstraction breaking should be removed.
1125 MemoryPhi *MP = dyn_cast<MemoryPhi>(Access);
1126 assert(MP && "Tried to get phi arg block when not iterating over a PHI");
1127 return MP->getIncomingBlock(ArgNo);
1128 }
1129
1130 typename std::iterator_traits<BaseT>::pointer operator*() const {
1131 assert(Access && "Tried to access past the end of our iterator");
1132 // Go to the first argument for phis, and the defining access for everything
1133 // else.
1134 if (const MemoryPhi *MP = dyn_cast<MemoryPhi>(Access))
1135 return MP->getIncomingValue(ArgNo);
1136 return cast<MemoryUseOrDef>(Access)->getDefiningAccess();
1137 }
1138
1139 using BaseT::operator++;
1141 assert(Access && "Hit end of iterator");
1142 if (const MemoryPhi *MP = dyn_cast<MemoryPhi>(Access)) {
1143 if (++ArgNo >= MP->getNumIncomingValues()) {
1144 ArgNo = 0;
1145 Access = nullptr;
1146 }
1147 } else {
1148 Access = nullptr;
1149 }
1150 return *this;
1151 }
1152
1153private:
1154 T *Access = nullptr;
1155 unsigned ArgNo = 0;
1156};
1157
1161
1165
1169
1173
1174/// GraphTraits for a MemoryAccess, which walks defs in the normal case,
1175/// and uses in the inverse case.
1176template <> struct GraphTraits<MemoryAccess *> {
1179
1180 static NodeRef getEntryNode(NodeRef N) { return N; }
1181 static ChildIteratorType child_begin(NodeRef N) { return N->defs_begin(); }
1182 static ChildIteratorType child_end(NodeRef N) { return N->defs_end(); }
1183};
1184
1185template <> struct GraphTraits<Inverse<MemoryAccess *>> {
1188
1189 static NodeRef getEntryNode(NodeRef N) { return N; }
1190 static ChildIteratorType child_begin(NodeRef N) { return N->user_begin(); }
1191 static ChildIteratorType child_end(NodeRef N) { return N->user_end(); }
1192};
1193
1199
1200template <> struct DenseMapInfo<UpwardDefsElem> {
1206
1207 static bool isEqual(const UpwardDefsElem &LHS, const UpwardDefsElem &RHS) {
1208 return LHS.MA == RHS.MA && LHS.Loc == RHS.Loc &&
1209 LHS.MayBeCrossIteration == RHS.MayBeCrossIteration;
1210 }
1211};
1212
1213/// Provide an iterator that walks defs, giving both the memory access,
1214/// and the current pointer location, updating the pointer location as it
1215/// changes due to phi node translation.
1216///
1217/// This iterator, while somewhat specialized, is what most clients actually
1218/// want when walking upwards through MemorySSA def chains. It takes a pair of
1219/// <MemoryAccess,MemoryLocation>, and walks defs, properly translating the
1220/// memory location through phi nodes for the user.
1222 : public iterator_facade_base<upward_defs_iterator,
1223 std::forward_iterator_tag,
1224 const UpwardDefsElem> {
1225 using BaseT = upward_defs_iterator::iterator_facade_base;
1226
1227public:
1229 : DefIterator(Elem.MA), Location(Elem.Loc), OriginalAccess(Elem.MA),
1230 DT(DT) {
1231 CurrentElem.MA = nullptr;
1232 CurrentElem.MayBeCrossIteration = Elem.MayBeCrossIteration;
1233
1234 WalkingPhi = Elem.MA && isa<MemoryPhi>(Elem.MA);
1235 fillInCurrentElem();
1236 }
1237
1238 upward_defs_iterator() { CurrentElem.MA = nullptr; }
1239
1241 return DefIterator == Other.DefIterator;
1242 }
1243
1244 std::iterator_traits<BaseT>::reference operator*() const {
1245 assert(DefIterator != OriginalAccess->defs_end() &&
1246 "Tried to access past the end of our iterator");
1247 return CurrentElem;
1248 }
1249
1250 using BaseT::operator++;
1252 assert(DefIterator != OriginalAccess->defs_end() &&
1253 "Tried to access past the end of the iterator");
1254 ++DefIterator;
1255 if (DefIterator != OriginalAccess->defs_end())
1256 fillInCurrentElem();
1257 return *this;
1258 }
1259
1260 BasicBlock *getPhiArgBlock() const { return DefIterator.getPhiArgBlock(); }
1261
1262private:
1263 /// Returns true if \p Ptr is guaranteed to be loop invariant for any possible
1264 /// loop. In particular, this guarantees that it only references a single
1265 /// MemoryLocation during execution of the containing function.
1266 LLVM_ABI bool IsGuaranteedLoopInvariant(const Value *Ptr) const;
1267
1268 void fillInCurrentElem() {
1269 CurrentElem.MA = *DefIterator;
1270 CurrentElem.Loc = Location;
1271 // No need for phi translation or handling of cross-iteration dependences
1272 // if we're not walking past a phi.
1273 if (!WalkingPhi)
1274 return;
1275
1276 if (Location.Ptr) {
1277 PHITransAddr Translator(
1278 const_cast<Value *>(Location.Ptr),
1279 OriginalAccess->getBlock()->getDataLayout(), nullptr);
1280
1281 if (Value *Addr =
1282 Translator.translateValue(OriginalAccess->getBlock(),
1283 DefIterator.getPhiArgBlock(), DT, true))
1284 if (Addr != CurrentElem.Loc.Ptr)
1285 CurrentElem.Loc = CurrentElem.Loc.getWithNewPtr(Addr);
1286
1287 // Mark size as unknown, if the location is not guaranteed to be
1288 // loop-invariant for any possible loop in the function. Setting the size
1289 // to unknown guarantees that any memory accesses that access locations
1290 // after the pointer are considered as clobbers, which is important to
1291 // catch loop carried dependences.
1292 if (!IsGuaranteedLoopInvariant(CurrentElem.Loc.Ptr))
1293 // TODO: We should be using MayBeCrossIteration here as well.
1294 CurrentElem.Loc = CurrentElem.Loc.getWithNewSize(
1296 } else {
1297 // We can't easily analyze invariance for calls, so conservatively assume
1298 // they may be introducing cross-iteration dependences for any phi
1299 // translation.
1300 CurrentElem.MayBeCrossIteration = true;
1301 }
1302 }
1303
1304 UpwardDefsElem CurrentElem;
1305 memoryaccess_def_iterator DefIterator;
1306 MemoryLocation Location;
1307 MemoryAccess *OriginalAccess = nullptr;
1308 DominatorTree *DT = nullptr;
1309 bool WalkingPhi = false;
1310};
1311
1313 DominatorTree &DT) {
1314 return upward_defs_iterator(Pair, &DT);
1315}
1316
1318
1319/// Walks the defining accesses of MemoryDefs. Stops after we hit something that
1320/// has no defining use (e.g. a MemoryPhi or liveOnEntry). Note that, when
1321/// comparing against a null def_chain_iterator, this will compare equal only
1322/// after walking said Phi/liveOnEntry.
1323///
1324/// The UseOptimizedChain flag specifies whether to walk the clobbering
1325/// access chain, or all the accesses.
1326///
1327/// Normally, MemoryDef are all just def/use linked together, so a def_chain on
1328/// a MemoryDef will walk all MemoryDefs above it in the program until it hits
1329/// a phi node. The optimized chain walks the clobbering access of a store.
1330/// So if you are just trying to find, given a store, what the next
1331/// thing that would clobber the same memory is, you want the optimized chain.
1332template <class T, bool UseOptimizedChain = false>
1334 : public iterator_facade_base<def_chain_iterator<T, UseOptimizedChain>,
1335 std::forward_iterator_tag, MemoryAccess *> {
1336 def_chain_iterator() : MA(nullptr) {}
1337 def_chain_iterator(T MA) : MA(MA) {}
1338
1339 T operator*() const { return MA; }
1340
1342 // N.B. liveOnEntry has a null defining access.
1343 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
1344 if (UseOptimizedChain && MUD->isOptimized())
1345 MA = MUD->getOptimized();
1346 else
1347 MA = MUD->getDefiningAccess();
1348 } else {
1349 MA = nullptr;
1350 }
1351
1352 return *this;
1353 }
1354
1355 bool operator==(const def_chain_iterator &O) const { return MA == O.MA; }
1356
1357private:
1358 T MA;
1359};
1360
1361template <class T>
1363def_chain(T MA, MemoryAccess *UpTo = nullptr) {
1364#ifdef EXPENSIVE_CHECKS
1365 assert((!UpTo || find(def_chain(MA), UpTo) != def_chain_iterator<T>()) &&
1366 "UpTo isn't in the def chain!");
1367#endif
1369}
1370
1371template <class T>
1376
1377} // end namespace llvm
1378
1379#endif // LLVM_ANALYSIS_MEMORYSSA_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_ABI
Definition Compiler.h:211
DXIL Resource Access
This file defines the DenseMap class.
early cse Early CSE w MemorySSA
static bool runOnFunction(Function &F, bool PostInlining)
IRTranslator LLVM IR MI
static MemoryAccess * getClobberingMemoryAccess(MemorySSA &MSSA, BatchAAResults &BAA, SinkAndHoistLICMFlags &Flags, MemoryUseOrDef *MA)
Definition LICM.cpp:885
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file provides utility analysis objects describing memory locations.
#define T
#define DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CLASS, VALUECLASS)
Macro for generating out-of-class operand accessor definitions.
static bool dominates(InstrPosIndexes &PosIndexes, const MachineInstr &A, const MachineInstr &B)
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
Value * RHS
Value * LHS
Represent the analysis usage information of a pass.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
Extension point for the Value hierarchy.
Definition DerivedUser.h:27
void(*)(DerivedUser *) DeleteValueTy
Definition DerivedUser.h:29
DerivedUser(Type *Ty, unsigned VK, AllocInfo AllocInfo, DeleteValueTy DeleteValue)
Definition DerivedUser.h:37
friend class Value
Definition DerivedUser.h:32
A MemorySSAWalker that does no alias queries, or anything else.
Definition MemorySSA.h:1088
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
FunctionPass(char &pid)
Definition Pass.h:314
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
static constexpr LocationSize beforeOrAfterPointer()
Any location before or after the base pointer (but still within the underlying object).
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
LLVM_ABI void dump() const
AllAccessType::reverse_self_iterator getReverseIterator()
Definition MemorySSA.h:188
friend class MemorySSA
Definition MemorySSA.h:210
AllAccessType::const_self_iterator getIterator() const
Definition MemorySSA.h:185
MemoryAccess(const MemoryAccess &)=delete
static bool classof(const Value *V)
Definition MemorySSA.h:158
friend class MemoryUse
Definition MemorySSA.h:211
friend class MemoryUseOrDef
Definition MemorySSA.h:212
DefsOnlyType::const_self_iterator getDefsIterator() const
Definition MemorySSA.h:197
friend class MemoryPhi
Definition MemorySSA.h:209
DefsOnlyType::self_iterator getDefsIterator()
Definition MemorySSA.h:194
DefsOnlyType::reverse_self_iterator getReverseDefsIterator()
Definition MemorySSA.h:200
ilist_node< MemoryAccess, ilist_tag< MSSAHelpers::AllAccessTag > > AllAccessType
Definition MemorySSA.h:146
DefsOnlyType::const_reverse_self_iterator getReverseDefsIterator() const
Definition MemorySSA.h:203
memoryaccess_def_iterator defs_end()
Definition MemorySSA.h:1166
~MemoryAccess()=default
MemoryAccess(LLVMContext &C, unsigned Vty, DeleteValueTy DeleteValue, BasicBlock *BB, AllocInfo AllocInfo)
Definition MemorySSA.h:222
ilist_node< MemoryAccess, ilist_tag< MSSAHelpers::DefsOnlyTag > > DefsOnlyType
Definition MemorySSA.h:148
friend class MemoryDef
Definition MemorySSA.h:208
BasicBlock * getBlock() const
Definition MemorySSA.h:163
user_iterator iterator
The user iterators for a memory access.
Definition MemorySSA.h:169
AllAccessType::const_reverse_self_iterator getReverseIterator() const
Definition MemorySSA.h:191
LLVM_ABI void print(raw_ostream &OS) const
unsigned getID() const
Used for debugging and tracking things about MemoryAccesses.
Definition MemorySSA.h:657
MemoryAccess & operator=(const MemoryAccess &)=delete
void setBlock(BasicBlock *BB)
Used by MemorySSA to change the block of a MemoryAccess when it is moved.
Definition MemorySSA.h:216
const_user_iterator const_iterator
Definition MemorySSA.h:170
memoryaccess_def_iterator defs_begin()
This iterator walks over all of the defs in a given MemoryAccess.
Definition MemorySSA.h:1158
AllAccessType::self_iterator getIterator()
Get the iterators for the all access list and the defs only list We default to the all access list.
Definition MemorySSA.h:182
Represents a read-write access to memory, whether it is a must-alias, or a may-alias.
Definition MemorySSA.h:372
friend class MemorySSA
Definition MemorySSA.h:376
static bool classof(const Value *MA)
Definition MemorySSA.h:389
void resetOptimized()
Definition MemorySSA.h:406
MemoryAccess * getOptimized() const
Definition MemorySSA.h:398
unsigned getID() const
Definition MemorySSA.h:413
DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess)
bool isOptimized() const
Definition MemorySSA.h:402
MemoryDef(LLVMContext &C, MemoryAccess *DMA, Instruction *MI, BasicBlock *BB, unsigned Ver)
Definition MemorySSA.h:380
void setOptimized(MemoryAccess *MA)
Definition MemorySSA.h:393
Representation for a specific memory location.
MemoryLocation getWithNewSize(LocationSize NewSize) const
MemoryLocation getWithNewPtr(const Value *NewPtr) const
const Value * Ptr
The address of the start of the location.
Represents phi nodes for memory accesses.
Definition MemorySSA.h:480
void setIncomingBlock(unsigned I, BasicBlock *BB)
Definition MemorySSA.h:558
void allocHungoffUses(unsigned N)
this is more complicated than the generic User::allocHungoffUses, because we have to allocate Uses fo...
Definition MemorySSA.h:636
friend class MemorySSA
Definition MemorySSA.h:631
void setIncomingValue(unsigned I, MemoryAccess *V)
Definition MemorySSA.h:534
static bool classof(const Value *V)
Definition MemorySSA.h:622
const_block_iterator block_end() const
Definition MemorySSA.h:513
BasicBlock * getIncomingBlock(const Use &U) const
Return incoming basic block corresponding to an operand of the PHI.
Definition MemorySSA.h:547
DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess)
Provide fast operand accessors.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
Definition MemorySSA.h:530
MemoryAccess * getIncomingValueForBlock(const BasicBlock *BB) const
Definition MemorySSA.h:582
block_iterator block_end()
Definition MemorySSA.h:511
const_block_iterator block_begin() const
Definition MemorySSA.h:507
iterator_range< block_iterator > blocks()
Definition MemorySSA.h:517
void unorderedDeleteIncomingIf(Fn &&Pred)
Definition MemorySSA.h:605
void unorderedDeleteIncoming(unsigned I)
Definition MemorySSA.h:589
BasicBlock * getIncomingBlock(unsigned I) const
Return incoming basic block number i.
Definition MemorySSA.h:543
const_op_range incoming_values() const
Definition MemorySSA.h:527
BasicBlock ** block_iterator
Definition MemorySSA.h:500
BasicBlock * getIncomingBlock(MemoryAccess::const_user_iterator I) const
Return incoming basic block corresponding to value use iterator.
Definition MemorySSA.h:554
static unsigned getIncomingValueNumForOperand(unsigned I)
Definition MemorySSA.h:540
void addIncoming(MemoryAccess *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
Definition MemorySSA.h:564
op_range incoming_values()
Definition MemorySSA.h:525
void unorderedDeleteIncomingBlock(const BasicBlock *BB)
Definition MemorySSA.h:617
MemoryPhi(LLVMContext &C, BasicBlock *BB, unsigned Ver, unsigned NumPreds=0)
Definition MemorySSA.h:492
MemoryAccess * getIncomingValue(unsigned I) const
Return incoming value number x.
Definition MemorySSA.h:533
static unsigned getOperandNumForIncomingValue(unsigned I)
Definition MemorySSA.h:539
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
Definition MemorySSA.h:575
iterator_range< const_block_iterator > blocks() const
Definition MemorySSA.h:521
unsigned getID() const
Definition MemorySSA.h:628
BasicBlock *const * const_block_iterator
Definition MemorySSA.h:501
block_iterator block_begin()
Definition MemorySSA.h:503
An analysis that produces MemorySSA for a function.
Definition MemorySSA.h:917
LLVM_ABI Result run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
MemorySSAPrinterPass(raw_ostream &OS, bool EnsureOptimizedUses)
Definition MemorySSA.h:947
static LLVM_ABI bool defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU, AliasAnalysis &AA)
friend class MemorySSAWalker
Definition MemorySSA.h:907
friend class GVNHoist
Definition MemorySSA.h:906
MemorySSAWalkerPrinterPass(raw_ostream &OS)
Definition MemorySSA.h:959
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
This is the generic walker interface for walkers of MemorySSA.
Definition MemorySSA.h:1001
SmallVector< MemoryAccess *, 8 > MemoryAccessSet
Definition MemorySSA.h:1006
friend class MemorySSA
Definition MemorySSA.h:1081
MemoryAccess * getClobberingMemoryAccess(const Instruction *I, BatchAAResults &AA)
Given a memory Mod/Ref/ModRef'ing instruction, calling this will give you the nearest dominating Memo...
Definition MemorySSA.h:1030
LLVM_ABI MemorySSAWalker(MemorySSA *)
virtual ~MemorySSAWalker()=default
MemoryAccess * getClobberingMemoryAccess(MemoryAccess *MA, const MemoryLocation &Loc)
Definition MemorySSA.h:1067
virtual void invalidateInfo(MemoryAccess *)
Given a memory access, invalidate anything this walker knows about that access.
Definition MemorySSA.h:1078
virtual MemoryAccess * getClobberingMemoryAccess(MemoryAccess *, const MemoryLocation &, BatchAAResults &AA)=0
Given a potentially clobbering memory access and a new location, calling this will give you the neare...
virtual MemoryAccess * getClobberingMemoryAccess(MemoryAccess *, BatchAAResults &AA)=0
Does the same thing as getClobberingMemoryAccess(const Instruction *I), but takes a MemoryAccess inst...
MemoryAccess * getClobberingMemoryAccess(const Instruction *I)
Definition MemorySSA.h:1057
MemoryAccess * getClobberingMemoryAccess(MemoryAccess *MA)
Definition MemorySSA.h:1062
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
const MemorySSA & getMSSA() const
Definition MemorySSA.h:979
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition MemorySSA.h:696
simple_ilist< MemoryAccess, ilist_tag< MSSAHelpers::DefsOnlyTag > > DefsList
Definition MemorySSA.h:748
AliasAnalysis & getAA()
Definition MemorySSA.h:794
LLVM_ABI void moveTo(MemoryUseOrDef *What, BasicBlock *BB, AccessList::iterator Where)
void renamePass(BasicBlock *BB, MemoryAccess *IncomingVal, SmallPtrSetImpl< BasicBlock * > &Visited)
Definition MemorySSA.h:816
DefsList * getBlockDefs(const BasicBlock *BB) const
Return the list of MemoryDef's and MemoryPhi's for a given basic block.
Definition MemorySSA.h:759
LLVM_ABI MemorySSAWalker * getSkipSelfWalker()
LLVM_ABI MemorySSA(Function &, AliasAnalysis *, DominatorTree *)
iplist< MemoryAccess, ilist_tag< MSSAHelpers::AllAccessTag > > AccessList
Definition MemorySSA.h:747
AccessList * getBlockAccesses(const BasicBlock *BB) const
Return the list of MemoryAccess's for a given basic block.
Definition MemorySSA.h:752
void verifyOrderingDominationAndDefUses(IterT Blocks, VerificationLevel=VerificationLevel::Fast) const
Verify ordering: the order and existence of MemoryAccesses matches the order and existence of memory ...
LLVM_ABI MemorySSAWalker * getWalker()
InsertionPlace
Used in various insertion functions to specify whether we are talking about the beginning or end of a...
Definition MemorySSA.h:785
MemorySSA(MemorySSA &&)=delete
DominatorTree & getDomTree() const
Definition MemorySSA.h:722
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
Definition MemorySSA.h:714
friend class MemorySSAUpdater
Definition MemorySSA.h:798
MemoryPhi * getMemoryAccess(const BasicBlock *BB) const
Definition MemorySSA.h:718
MemoryAccess * getLiveOnEntryDef() const
Definition MemorySSA.h:738
void verifyDominationNumbers(IterT Blocks) const
Verify that all of the blocks we believe to have valid domination numbers actually have valid dominat...
void verifyPrevDefInPhis(IterT Blocks) const
bool isLiveOnEntryDef(const MemoryAccess *MA) const
Return true if MA represents the live on entry value.
Definition MemorySSA.h:734
Class that has the common methods + fields of memory uses/defs.
Definition MemorySSA.h:251
friend class MemorySSA
Definition MemorySSA.h:280
MemoryUseOrDef(LLVMContext &C, MemoryAccess *DMA, unsigned Vty, DeleteValueTy DeleteValue, Instruction *MI, BasicBlock *BB, AllocInfo AllocInfo)
Definition MemorySSA.h:283
~MemoryUseOrDef()=default
MemoryAccess * getDefiningAccess() const
Get the access that produces the memory state used by this Use.
Definition MemorySSA.h:261
void resetOptimized()
Reset the ID of what this MemoryUse was optimized to, causing it to be rewalked by the walker if nece...
Definition MemorySSA.h:684
MemoryAccess * getOptimized() const
Return the MemoryAccess associated with the optimized use, or nullptr.
Definition MemorySSA.h:671
void setDefiningAccess(MemoryAccess *DMA, bool Optimized=false)
Definition MemorySSA.h:294
void setOptimized(MemoryAccess *)
Sets the optimized use for a MemoryDef.
Definition MemorySSA.h:677
DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess)
Instruction * getMemoryInst() const
Get the instruction that this MemoryUse represents.
Definition MemorySSA.h:258
friend class MemorySSAUpdater
Definition MemorySSA.h:281
static bool classof(const Value *MA)
Definition MemorySSA.h:263
bool isOptimized() const
Do we have an optimized use?
Definition MemorySSA.h:665
Represents read-only accesses to memory.
Definition MemorySSA.h:311
friend class MemorySSA
Definition MemorySSA.h:351
MemoryAccess * getOptimized() const
Definition MemorySSA.h:342
DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess)
MemoryUse(LLVMContext &C, MemoryAccess *DMA, Instruction *MI, BasicBlock *BB)
Definition MemorySSA.h:317
LLVM_ABI void print(raw_ostream &OS) const
void resetOptimized()
Definition MemorySSA.h:346
bool isOptimized() const
Whether the MemoryUse is optimized.
Definition MemorySSA.h:338
static bool classof(const Value *MA)
Definition MemorySSA.h:324
void setOptimized(MemoryAccess *DMA)
Definition MemorySSA.h:330
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
PHITransAddr - An address value which tracks and handles phi translation.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
iterator_range< const_op_iterator > const_op_range
Definition User.h:257
op_range operands()
Definition User.h:267
op_iterator op_begin()
Definition User.h:259
LLVM_ABI void allocHungoffUses(unsigned N, bool WithExtraValues=false)
Allocate the array of Uses, followed by a pointer (with bottom bit set) to the User.
Definition User.cpp:48
void setOperand(unsigned i, Value *Val)
Definition User.h:212
void setNumHungOffUseOperands(unsigned NumOps)
Subclasses with hung off uses need to manage the operand count themselves.
Definition User.h:240
iterator_range< op_iterator > op_range
Definition User.h:256
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
user_iterator_impl< const User > const_user_iterator
Definition Value.h:394
unsigned getValueID() const
Return an ID for the concrete type of this object.
Definition Value.h:545
LLVM_ABI void deleteValue()
Delete a pointer to a generic Value.
Definition Value.cpp:104
user_iterator_impl< User > user_iterator
Definition Value.h:393
ilist_select_iterator_type< OptionsT, false, true > const_self_iterator
Definition ilist_node.h:94
ilist_select_iterator_type< OptionsT, true, false > reverse_self_iterator
Definition ilist_node.h:95
reverse_self_iterator getReverseIterator()
Definition ilist_node.h:126
ilist_select_iterator_type< OptionsT, true, true > const_reverse_self_iterator
Definition ilist_node.h:97
self_iterator getIterator()
Definition ilist_node.h:123
ilist_select_iterator_type< OptionsT, false, false > self_iterator
Definition ilist_node.h:93
typename base_list_type::iterator iterator
Definition ilist.h:121
An intrusive list with ownership and callbacks specified/controlled by ilist_traits,...
Definition ilist.h:328
CRTP base class which implements the entire standard iterator facade in terms of a minimal subset of ...
Definition iterator.h:80
A range adaptor for a pair of iterators.
Iterator base class used to implement const and non-const iterators over the defining accesses of a M...
Definition MemorySSA.h:1107
BasicBlock * getPhiArgBlock() const
Definition MemorySSA.h:1124
std::iterator_traits< BaseT >::pointer operator*() const
Definition MemorySSA.h:1130
bool operator==(const memoryaccess_def_iterator_base &Other) const
Definition MemorySSA.h:1114
memoryaccess_def_iterator_base & operator++()
Definition MemorySSA.h:1140
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A simple intrusive list implementation.
Provide an iterator that walks defs, giving both the memory access, and the current pointer location,...
Definition MemorySSA.h:1224
std::iterator_traits< BaseT >::reference operator*() const
Definition MemorySSA.h:1244
upward_defs_iterator(const UpwardDefsElem &Elem, DominatorTree *DT)
Definition MemorySSA.h:1228
BasicBlock * getPhiArgBlock() const
Definition MemorySSA.h:1260
upward_defs_iterator & operator++()
Definition MemorySSA.h:1251
bool operator==(const upward_defs_iterator &Other) const
Definition MemorySSA.h:1240
This file defines the ilist_node class template, which is a convenient base class for creating classe...
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
Abstract Attribute helper functions.
Definition Attributor.h:164
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
@ INVALID_MEMORYACCESS_ID
Definition MemorySSA.h:131
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
auto cast_or_null(const Y &Val)
Definition Casting.h:714
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition Dominators.h:65
iterator_range< def_chain_iterator< T > > def_chain(T MA, MemoryAccess *UpTo=nullptr)
Definition MemorySSA.h:1363
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition MemorySSA.cpp:76
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
iterator_range(Container &&) -> iterator_range< llvm::detail::IterOfRange< Container > >
@ Other
Any other memory.
Definition ModRef.h:68
upward_defs_iterator upward_defs_end()
Definition MemorySSA.h:1317
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
memoryaccess_def_iterator_base< const MemoryAccess > const_memoryaccess_def_iterator
Definition MemorySSA.h:136
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition Hashing.h:307
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
upward_defs_iterator upward_defs_begin(const UpwardDefsElem &Pair, DominatorTree &DT)
Definition MemorySSA.h:1312
memoryaccess_def_iterator_base< MemoryAccess > memoryaccess_def_iterator
Definition MemorySSA.h:135
iterator_range< def_chain_iterator< T, true > > optimized_def_chain(T MA)
Definition MemorySSA.h:1372
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
#define N
A CRTP mix-in that provides informational APIs needed for analysis passes.
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
static unsigned getHashValue(const UpwardDefsElem &Val)
Definition MemorySSA.h:1201
static bool isEqual(const UpwardDefsElem &LHS, const UpwardDefsElem &RHS)
Definition MemorySSA.h:1207
An information struct used to provide DenseMap with the various necessary components for a given valu...
FixedNumOperandTraits - determine the allocation regime of the Use array when it is a prefix to the U...
static ChildIteratorType child_begin(NodeRef N)
Definition MemorySSA.h:1190
static ChildIteratorType child_end(NodeRef N)
Definition MemorySSA.h:1191
static ChildIteratorType child_begin(NodeRef N)
Definition MemorySSA.h:1181
static ChildIteratorType child_end(NodeRef N)
Definition MemorySSA.h:1182
static NodeRef getEntryNode(NodeRef N)
Definition MemorySSA.h:1180
memoryaccess_def_iterator ChildIteratorType
Definition MemorySSA.h:1178
HungoffOperandTraits - determine the allocation regime of the Use array when it is not a prefix to th...
Result(std::unique_ptr< MemorySSA > &&MSSA)
Definition MemorySSA.h:927
LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
std::unique_ptr< MemorySSA > MSSA
Definition MemorySSA.h:931
Verifier pass for MemorySSA.
Definition MemorySSA.h:965
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
static unsigned operands(const MemoryUseOrDef *MUD)
Definition MemorySSA.h:440
static Use * op_end(MemoryUseOrDef *MUD)
Definition MemorySSA.h:434
static Use * op_begin(MemoryUseOrDef *MUD)
Definition MemorySSA.h:428
Compile-time customization of User operands.
Definition User.h:42
A CRTP mix-in for passes that should not be skipped.
MemoryLocation Loc
Definition MemorySSA.h:1196
MemoryAccess * MA
Definition MemorySSA.h:1195
Information about how a User object was allocated, to be passed into the User constructor.
Definition User.h:79
Indicates this User has operands "hung off" in another allocation.
Definition User.h:57
Indicates this User has operands co-allocated.
Definition User.h:60
Walks the defining accesses of MemoryDefs.
Definition MemorySSA.h:1335
bool operator==(const def_chain_iterator &O) const
Definition MemorySSA.h:1355
def_chain_iterator & operator++()
Definition MemorySSA.h:1341
static void deleteNode(MemoryAccess *MA)
Definition MemorySSA.h:236
Use delete by default for iplist and ilist.
Definition ilist.h:41