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