blob: 289989060386525b8a82f890547a953c761155d5 [file] [log] [blame]
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001//===- MemorySSA.h - Build Memory SSA ---------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10/// \file
11/// \brief This file exposes an interface to building/using memory SSA to
12/// walk memory instructions using a use/def graph.
13///
14/// Memory SSA class builds an SSA form that links together memory access
15/// instructions such as loads, stores, atomics, and calls. Additionally, it
16/// does a trivial form of "heap versioning" Every time the memory state changes
17/// in the program, we generate a new heap version. It generates
18/// MemoryDef/Uses/Phis that are overlayed on top of the existing instructions.
19///
20/// As a trivial example,
21/// define i32 @main() #0 {
22/// entry:
23/// %call = call noalias i8* @_Znwm(i64 4) #2
24/// %0 = bitcast i8* %call to i32*
25/// %call1 = call noalias i8* @_Znwm(i64 4) #2
26/// %1 = bitcast i8* %call1 to i32*
27/// store i32 5, i32* %0, align 4
28/// store i32 7, i32* %1, align 4
29/// %2 = load i32* %0, align 4
30/// %3 = load i32* %1, align 4
31/// %add = add nsw i32 %2, %3
32/// ret i32 %add
33/// }
34///
35/// Will become
36/// define i32 @main() #0 {
37/// entry:
38/// ; 1 = MemoryDef(0)
39/// %call = call noalias i8* @_Znwm(i64 4) #3
40/// %2 = bitcast i8* %call to i32*
41/// ; 2 = MemoryDef(1)
42/// %call1 = call noalias i8* @_Znwm(i64 4) #3
43/// %4 = bitcast i8* %call1 to i32*
44/// ; 3 = MemoryDef(2)
45/// store i32 5, i32* %2, align 4
46/// ; 4 = MemoryDef(3)
47/// store i32 7, i32* %4, align 4
48/// ; MemoryUse(3)
49/// %7 = load i32* %2, align 4
50/// ; MemoryUse(4)
51/// %8 = load i32* %4, align 4
52/// %add = add nsw i32 %7, %8
53/// ret i32 %add
54/// }
55///
56/// Given this form, all the stores that could ever effect the load at %8 can be
57/// gotten by using the MemoryUse associated with it, and walking from use to
58/// def until you hit the top of the function.
59///
60/// Each def also has a list of users associated with it, so you can walk from
61/// both def to users, and users to defs. Note that we disambiguate MemoryUses,
62/// but not the RHS of MemoryDefs. You can see this above at %7, which would
63/// otherwise be a MemoryUse(4). Being disambiguated means that for a given
64/// store, all the MemoryUses on its use lists are may-aliases of that store
65/// (but the MemoryDefs on its use list may not be).
66///
67/// MemoryDefs are not disambiguated because it would require multiple reaching
68/// definitions, which would require multiple phis, and multiple memoryaccesses
69/// per instruction.
70//
71//===----------------------------------------------------------------------===//
72
73#ifndef LLVM_ANALYSIS_MEMORYSSA_H
74#define LLVM_ANALYSIS_MEMORYSSA_H
75
76#include "llvm/ADT/DenseMap.h"
77#include "llvm/ADT/GraphTraits.h"
78#include "llvm/ADT/SmallPtrSet.h"
79#include "llvm/ADT/SmallVector.h"
80#include "llvm/ADT/ilist.h"
81#include "llvm/ADT/ilist_node.h"
82#include "llvm/ADT/iterator.h"
83#include "llvm/ADT/iterator_range.h"
84#include "llvm/ADT/simple_ilist.h"
85#include "llvm/Analysis/AliasAnalysis.h"
86#include "llvm/Analysis/MemoryLocation.h"
87#include "llvm/Analysis/PHITransAddr.h"
88#include "llvm/IR/BasicBlock.h"
89#include "llvm/IR/DerivedUser.h"
90#include "llvm/IR/Dominators.h"
91#include "llvm/IR/Module.h"
92#include "llvm/IR/Type.h"
93#include "llvm/IR/Use.h"
94#include "llvm/IR/User.h"
95#include "llvm/IR/Value.h"
96#include "llvm/IR/ValueHandle.h"
97#include "llvm/Pass.h"
98#include "llvm/Support/Casting.h"
99#include <algorithm>
100#include <cassert>
101#include <cstddef>
102#include <iterator>
103#include <memory>
104#include <utility>
105
106namespace llvm {
107
108class Function;
109class Instruction;
110class MemoryAccess;
111class MemorySSAWalker;
112class LLVMContext;
113class raw_ostream;
114
115namespace MSSAHelpers {
116
117struct AllAccessTag {};
118struct DefsOnlyTag {};
119
120} // end namespace MSSAHelpers
121
122enum : unsigned {
123 // Used to signify what the default invalid ID is for MemoryAccess's
124 // getID()
125 INVALID_MEMORYACCESS_ID = -1U
126};
127
128template <class T> class memoryaccess_def_iterator_base;
129using memoryaccess_def_iterator = memoryaccess_def_iterator_base<MemoryAccess>;
130using const_memoryaccess_def_iterator =
131 memoryaccess_def_iterator_base<const MemoryAccess>;
132
133// \brief The base for all memory accesses. All memory accesses in a block are
134// linked together using an intrusive list.
135class MemoryAccess
136 : public DerivedUser,
137 public ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::AllAccessTag>>,
138 public ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::DefsOnlyTag>> {
139public:
140 using AllAccessType =
141 ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::AllAccessTag>>;
142 using DefsOnlyType =
143 ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::DefsOnlyTag>>;
144
145 MemoryAccess(const MemoryAccess &) = delete;
146 MemoryAccess &operator=(const MemoryAccess &) = delete;
147
148 void *operator new(size_t) = delete;
149
150 // Methods for support type inquiry through isa, cast, and
151 // dyn_cast
152 static bool classof(const Value *V) {
153 unsigned ID = V->getValueID();
154 return ID == MemoryUseVal || ID == MemoryPhiVal || ID == MemoryDefVal;
155 }
156
157 BasicBlock *getBlock() const { return Block; }
158
159 void print(raw_ostream &OS) const;
160 void dump() const;
161
162 /// \brief The user iterators for a memory access
163 using iterator = user_iterator;
164 using const_iterator = const_user_iterator;
165
166 /// \brief This iterator walks over all of the defs in a given
167 /// MemoryAccess. For MemoryPhi nodes, this walks arguments. For
168 /// MemoryUse/MemoryDef, this walks the defining access.
169 memoryaccess_def_iterator defs_begin();
170 const_memoryaccess_def_iterator defs_begin() const;
171 memoryaccess_def_iterator defs_end();
172 const_memoryaccess_def_iterator defs_end() const;
173
174 /// \brief Get the iterators for the all access list and the defs only list
175 /// We default to the all access list.
176 AllAccessType::self_iterator getIterator() {
177 return this->AllAccessType::getIterator();
178 }
179 AllAccessType::const_self_iterator getIterator() const {
180 return this->AllAccessType::getIterator();
181 }
182 AllAccessType::reverse_self_iterator getReverseIterator() {
183 return this->AllAccessType::getReverseIterator();
184 }
185 AllAccessType::const_reverse_self_iterator getReverseIterator() const {
186 return this->AllAccessType::getReverseIterator();
187 }
188 DefsOnlyType::self_iterator getDefsIterator() {
189 return this->DefsOnlyType::getIterator();
190 }
191 DefsOnlyType::const_self_iterator getDefsIterator() const {
192 return this->DefsOnlyType::getIterator();
193 }
194 DefsOnlyType::reverse_self_iterator getReverseDefsIterator() {
195 return this->DefsOnlyType::getReverseIterator();
196 }
197 DefsOnlyType::const_reverse_self_iterator getReverseDefsIterator() const {
198 return this->DefsOnlyType::getReverseIterator();
199 }
200
201protected:
202 friend class MemoryDef;
203 friend class MemoryPhi;
204 friend class MemorySSA;
205 friend class MemoryUse;
206 friend class MemoryUseOrDef;
207
208 /// \brief Used by MemorySSA to change the block of a MemoryAccess when it is
209 /// moved.
210 void setBlock(BasicBlock *BB) { Block = BB; }
211
212 /// \brief Used for debugging and tracking things about MemoryAccesses.
213 /// Guaranteed unique among MemoryAccesses, no guarantees otherwise.
214 inline unsigned getID() const;
215
216 MemoryAccess(LLVMContext &C, unsigned Vty, DeleteValueTy DeleteValue,
217 BasicBlock *BB, unsigned NumOperands)
218 : DerivedUser(Type::getVoidTy(C), Vty, nullptr, NumOperands, DeleteValue),
219 Block(BB) {}
220
221 // Use deleteValue() to delete a generic MemoryAccess.
222 ~MemoryAccess() = default;
223
224private:
225 BasicBlock *Block;
226};
227
228template <>
229struct ilist_alloc_traits<MemoryAccess> {
230 static void deleteNode(MemoryAccess *MA) { MA->deleteValue(); }
231};
232
233inline raw_ostream &operator<<(raw_ostream &OS, const MemoryAccess &MA) {
234 MA.print(OS);
235 return OS;
236}
237
238/// \brief Class that has the common methods + fields of memory uses/defs. It's
239/// a little awkward to have, but there are many cases where we want either a
240/// use or def, and there are many cases where uses are needed (defs aren't
241/// acceptable), and vice-versa.
242///
243/// This class should never be instantiated directly; make a MemoryUse or
244/// MemoryDef instead.
245class MemoryUseOrDef : public MemoryAccess {
246public:
247 void *operator new(size_t) = delete;
248
249 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess);
250
251 /// \brief Get the instruction that this MemoryUse represents.
252 Instruction *getMemoryInst() const { return MemoryInstruction; }
253
254 /// \brief Get the access that produces the memory state used by this Use.
255 MemoryAccess *getDefiningAccess() const { return getOperand(0); }
256
257 static bool classof(const Value *MA) {
258 return MA->getValueID() == MemoryUseVal || MA->getValueID() == MemoryDefVal;
259 }
260
261 // Sadly, these have to be public because they are needed in some of the
262 // iterators.
263 inline bool isOptimized() const;
264 inline MemoryAccess *getOptimized() const;
265 inline void setOptimized(MemoryAccess *);
266
267 // Retrieve AliasResult type of the optimized access. Ideally this would be
268 // returned by the caching walker and may go away in the future.
269 Optional<AliasResult> getOptimizedAccessType() const {
270 return OptimizedAccessAlias;
271 }
272
273 /// \brief Reset the ID of what this MemoryUse was optimized to, causing it to
274 /// be rewalked by the walker if necessary.
275 /// This really should only be called by tests.
276 inline void resetOptimized();
277
278protected:
279 friend class MemorySSA;
280 friend class MemorySSAUpdater;
281
282 MemoryUseOrDef(LLVMContext &C, MemoryAccess *DMA, unsigned Vty,
283 DeleteValueTy DeleteValue, Instruction *MI, BasicBlock *BB)
284 : MemoryAccess(C, Vty, DeleteValue, BB, 1), MemoryInstruction(MI),
285 OptimizedAccessAlias(MayAlias) {
286 setDefiningAccess(DMA);
287 }
288
289 // Use deleteValue() to delete a generic MemoryUseOrDef.
290 ~MemoryUseOrDef() = default;
291
292 void setOptimizedAccessType(Optional<AliasResult> AR) {
293 OptimizedAccessAlias = AR;
294 }
295
296 void setDefiningAccess(MemoryAccess *DMA, bool Optimized = false,
297 Optional<AliasResult> AR = MayAlias) {
298 if (!Optimized) {
299 setOperand(0, DMA);
300 return;
301 }
302 setOptimized(DMA);
303 setOptimizedAccessType(AR);
304 }
305
306private:
307 Instruction *MemoryInstruction;
308 Optional<AliasResult> OptimizedAccessAlias;
309};
310
311template <>
312struct OperandTraits<MemoryUseOrDef>
313 : public FixedNumOperandTraits<MemoryUseOrDef, 1> {};
314DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryUseOrDef, MemoryAccess)
315
316/// \brief Represents read-only accesses to memory
317///
318/// In particular, the set of Instructions that will be represented by
319/// MemoryUse's is exactly the set of Instructions for which
320/// AliasAnalysis::getModRefInfo returns "Ref".
321class MemoryUse final : public MemoryUseOrDef {
322public:
323 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess);
324
325 MemoryUse(LLVMContext &C, MemoryAccess *DMA, Instruction *MI, BasicBlock *BB)
326 : MemoryUseOrDef(C, DMA, MemoryUseVal, deleteMe, MI, BB) {}
327
328 // allocate space for exactly one operand
329 void *operator new(size_t s) { return User::operator new(s, 1); }
330
331 static bool classof(const Value *MA) {
332 return MA->getValueID() == MemoryUseVal;
333 }
334
335 void print(raw_ostream &OS) const;
336
337 void setOptimized(MemoryAccess *DMA) {
338 OptimizedID = DMA->getID();
339 setOperand(0, DMA);
340 }
341
342 bool isOptimized() const {
343 return getDefiningAccess() && OptimizedID == getDefiningAccess()->getID();
344 }
345
346 MemoryAccess *getOptimized() const {
347 return getDefiningAccess();
348 }
349
350 void resetOptimized() {
351 OptimizedID = INVALID_MEMORYACCESS_ID;
352 }
353
354protected:
355 friend class MemorySSA;
356
357private:
358 static void deleteMe(DerivedUser *Self);
359
360 unsigned OptimizedID = INVALID_MEMORYACCESS_ID;
361};
362
363template <>
364struct OperandTraits<MemoryUse> : public FixedNumOperandTraits<MemoryUse, 1> {};
365DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryUse, MemoryAccess)
366
367/// \brief Represents a read-write access to memory, whether it is a must-alias,
368/// or a may-alias.
369///
370/// In particular, the set of Instructions that will be represented by
371/// MemoryDef's is exactly the set of Instructions for which
372/// AliasAnalysis::getModRefInfo returns "Mod" or "ModRef".
373/// Note that, in order to provide def-def chains, all defs also have a use
374/// associated with them. This use points to the nearest reaching
375/// MemoryDef/MemoryPhi.
376class MemoryDef final : public MemoryUseOrDef {
377public:
378 friend class MemorySSA;
379
380 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess);
381
382 MemoryDef(LLVMContext &C, MemoryAccess *DMA, Instruction *MI, BasicBlock *BB,
383 unsigned Ver)
384 : MemoryUseOrDef(C, DMA, MemoryDefVal, deleteMe, MI, BB), ID(Ver) {}
385
386 // allocate space for exactly one operand
387 void *operator new(size_t s) { return User::operator new(s, 1); }
388
389 static bool classof(const Value *MA) {
390 return MA->getValueID() == MemoryDefVal;
391 }
392
393 void setOptimized(MemoryAccess *MA) {
394 Optimized = MA;
395 OptimizedID = getDefiningAccess()->getID();
396 }
397
398 MemoryAccess *getOptimized() const {
399 return cast_or_null<MemoryAccess>(Optimized);
400 }
401
402 bool isOptimized() const {
403 return getOptimized() && getDefiningAccess() &&
404 OptimizedID == getDefiningAccess()->getID();
405 }
406
407 void resetOptimized() {
408 OptimizedID = INVALID_MEMORYACCESS_ID;
409 }
410
411 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 WeakVH Optimized;
421};
422
423template <>
424struct OperandTraits<MemoryDef> : public FixedNumOperandTraits<MemoryDef, 1> {};
425DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryDef, MemoryAccess)
426
427/// \brief Represents phi nodes for memory accesses.
428///
429/// These have the same semantic as regular phi nodes, with the exception that
430/// only one phi will ever exist in a given basic block.
431/// Guaranteeing one phi per block means guaranteeing there is only ever one
432/// valid reaching MemoryDef/MemoryPHI along each path to the phi node.
433/// This is ensured by not allowing disambiguation of the RHS of a MemoryDef or
434/// a MemoryPhi's operands.
435/// That is, given
436/// if (a) {
437/// store %a
438/// store %b
439/// }
440/// it *must* be transformed into
441/// if (a) {
442/// 1 = MemoryDef(liveOnEntry)
443/// store %a
444/// 2 = MemoryDef(1)
445/// store %b
446/// }
447/// and *not*
448/// if (a) {
449/// 1 = MemoryDef(liveOnEntry)
450/// store %a
451/// 2 = MemoryDef(liveOnEntry)
452/// store %b
453/// }
454/// even if the two stores do not conflict. Otherwise, both 1 and 2 reach the
455/// end of the branch, and if there are not two phi nodes, one will be
456/// disconnected completely from the SSA graph below that point.
457/// Because MemoryUse's do not generate new definitions, they do not have this
458/// issue.
459class MemoryPhi final : public MemoryAccess {
460 // allocate space for exactly zero operands
461 void *operator new(size_t s) { return User::operator new(s); }
462
463public:
464 /// Provide fast operand accessors
465 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess);
466
467 MemoryPhi(LLVMContext &C, BasicBlock *BB, unsigned Ver, unsigned NumPreds = 0)
468 : MemoryAccess(C, MemoryPhiVal, deleteMe, BB, 0), ID(Ver),
469 ReservedSpace(NumPreds) {
470 allocHungoffUses(ReservedSpace);
471 }
472
473 // Block iterator interface. This provides access to the list of incoming
474 // basic blocks, which parallels the list of incoming values.
475 using block_iterator = BasicBlock **;
476 using const_block_iterator = BasicBlock *const *;
477
478 block_iterator block_begin() {
479 auto *Ref = reinterpret_cast<Use::UserRef *>(op_begin() + ReservedSpace);
480 return reinterpret_cast<block_iterator>(Ref + 1);
481 }
482
483 const_block_iterator block_begin() const {
484 const auto *Ref =
485 reinterpret_cast<const Use::UserRef *>(op_begin() + ReservedSpace);
486 return reinterpret_cast<const_block_iterator>(Ref + 1);
487 }
488
489 block_iterator block_end() { return block_begin() + getNumOperands(); }
490
491 const_block_iterator block_end() const {
492 return block_begin() + getNumOperands();
493 }
494
495 iterator_range<block_iterator> blocks() {
496 return make_range(block_begin(), block_end());
497 }
498
499 iterator_range<const_block_iterator> blocks() const {
500 return make_range(block_begin(), block_end());
501 }
502
503 op_range incoming_values() { return operands(); }
504
505 const_op_range incoming_values() const { return operands(); }
506
507 /// \brief Return the number of incoming edges
508 unsigned getNumIncomingValues() const { return getNumOperands(); }
509
510 /// \brief Return incoming value number x
511 MemoryAccess *getIncomingValue(unsigned I) const { return getOperand(I); }
512 void setIncomingValue(unsigned I, MemoryAccess *V) {
513 assert(V && "PHI node got a null value!");
514 setOperand(I, V);
515 }
516
517 static unsigned getOperandNumForIncomingValue(unsigned I) { return I; }
518 static unsigned getIncomingValueNumForOperand(unsigned I) { return I; }
519
520 /// \brief Return incoming basic block number @p i.
521 BasicBlock *getIncomingBlock(unsigned I) const { return block_begin()[I]; }
522
523 /// \brief Return incoming basic block corresponding
524 /// to an operand of the PHI.
525 BasicBlock *getIncomingBlock(const Use &U) const {
526 assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?");
527 return getIncomingBlock(unsigned(&U - op_begin()));
528 }
529
530 /// \brief Return incoming basic block corresponding
531 /// to value use iterator.
532 BasicBlock *getIncomingBlock(MemoryAccess::const_user_iterator I) const {
533 return getIncomingBlock(I.getUse());
534 }
535
536 void setIncomingBlock(unsigned I, BasicBlock *BB) {
537 assert(BB && "PHI node got a null basic block!");
538 block_begin()[I] = BB;
539 }
540
541 /// \brief Add an incoming value to the end of the PHI list
542 void addIncoming(MemoryAccess *V, BasicBlock *BB) {
543 if (getNumOperands() == ReservedSpace)
544 growOperands(); // Get more space!
545 // Initialize some new operands.
546 setNumHungOffUseOperands(getNumOperands() + 1);
547 setIncomingValue(getNumOperands() - 1, V);
548 setIncomingBlock(getNumOperands() - 1, BB);
549 }
550
551 /// \brief Return the first index of the specified basic
552 /// block in the value list for this PHI. Returns -1 if no instance.
553 int getBasicBlockIndex(const BasicBlock *BB) const {
554 for (unsigned I = 0, E = getNumOperands(); I != E; ++I)
555 if (block_begin()[I] == BB)
556 return I;
557 return -1;
558 }
559
560 Value *getIncomingValueForBlock(const BasicBlock *BB) const {
561 int Idx = getBasicBlockIndex(BB);
562 assert(Idx >= 0 && "Invalid basic block argument!");
563 return getIncomingValue(Idx);
564 }
565
566 static bool classof(const Value *V) {
567 return V->getValueID() == MemoryPhiVal;
568 }
569
570 void print(raw_ostream &OS) const;
571
572 unsigned getID() const { return ID; }
573
574protected:
575 friend class MemorySSA;
576
577 /// \brief this is more complicated than the generic
578 /// User::allocHungoffUses, because we have to allocate Uses for the incoming
579 /// values and pointers to the incoming blocks, all in one allocation.
580 void allocHungoffUses(unsigned N) {
581 User::allocHungoffUses(N, /* IsPhi */ true);
582 }
583
584private:
585 // For debugging only
586 const unsigned ID;
587 unsigned ReservedSpace;
588
589 /// \brief This grows the operand list in response to a push_back style of
590 /// operation. This grows the number of ops by 1.5 times.
591 void growOperands() {
592 unsigned E = getNumOperands();
593 // 2 op PHI nodes are VERY common, so reserve at least enough for that.
594 ReservedSpace = std::max(E + E / 2, 2u);
595 growHungoffUses(ReservedSpace, /* IsPhi */ true);
596 }
597
598 static void deleteMe(DerivedUser *Self);
599};
600
601inline unsigned MemoryAccess::getID() const {
602 assert((isa<MemoryDef>(this) || isa<MemoryPhi>(this)) &&
603 "only memory defs and phis have ids");
604 if (const auto *MD = dyn_cast<MemoryDef>(this))
605 return MD->getID();
606 return cast<MemoryPhi>(this)->getID();
607}
608
609inline bool MemoryUseOrDef::isOptimized() const {
610 if (const auto *MD = dyn_cast<MemoryDef>(this))
611 return MD->isOptimized();
612 return cast<MemoryUse>(this)->isOptimized();
613}
614
615inline MemoryAccess *MemoryUseOrDef::getOptimized() const {
616 if (const auto *MD = dyn_cast<MemoryDef>(this))
617 return MD->getOptimized();
618 return cast<MemoryUse>(this)->getOptimized();
619}
620
621inline void MemoryUseOrDef::setOptimized(MemoryAccess *MA) {
622 if (auto *MD = dyn_cast<MemoryDef>(this))
623 MD->setOptimized(MA);
624 else
625 cast<MemoryUse>(this)->setOptimized(MA);
626}
627
628inline void MemoryUseOrDef::resetOptimized() {
629 if (auto *MD = dyn_cast<MemoryDef>(this))
630 MD->resetOptimized();
631 else
632 cast<MemoryUse>(this)->resetOptimized();
633}
634
635template <> struct OperandTraits<MemoryPhi> : public HungoffOperandTraits<2> {};
636DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryPhi, MemoryAccess)
637
638/// \brief Encapsulates MemorySSA, including all data associated with memory
639/// accesses.
640class MemorySSA {
641public:
642 MemorySSA(Function &, AliasAnalysis *, DominatorTree *);
643 ~MemorySSA();
644
645 MemorySSAWalker *getWalker();
646
647 /// \brief Given a memory Mod/Ref'ing instruction, get the MemorySSA
648 /// access associated with it. If passed a basic block gets the memory phi
649 /// node that exists for that block, if there is one. Otherwise, this will get
650 /// a MemoryUseOrDef.
651 MemoryUseOrDef *getMemoryAccess(const Instruction *) const;
652 MemoryPhi *getMemoryAccess(const BasicBlock *BB) const;
653
654 void dump() const;
655 void print(raw_ostream &) const;
656
657 /// \brief Return true if \p MA represents the live on entry value
658 ///
659 /// Loads and stores from pointer arguments and other global values may be
660 /// defined by memory operations that do not occur in the current function, so
661 /// they may be live on entry to the function. MemorySSA represents such
662 /// memory state by the live on entry definition, which is guaranteed to occur
663 /// before any other memory access in the function.
664 inline bool isLiveOnEntryDef(const MemoryAccess *MA) const {
665 return MA == LiveOnEntryDef.get();
666 }
667
668 inline MemoryAccess *getLiveOnEntryDef() const {
669 return LiveOnEntryDef.get();
670 }
671
672 // Sadly, iplists, by default, owns and deletes pointers added to the
673 // list. It's not currently possible to have two iplists for the same type,
674 // where one owns the pointers, and one does not. This is because the traits
675 // are per-type, not per-tag. If this ever changes, we should make the
676 // DefList an iplist.
677 using AccessList = iplist<MemoryAccess, ilist_tag<MSSAHelpers::AllAccessTag>>;
678 using DefsList =
679 simple_ilist<MemoryAccess, ilist_tag<MSSAHelpers::DefsOnlyTag>>;
680
681 /// \brief Return the list of MemoryAccess's for a given basic block.
682 ///
683 /// This list is not modifiable by the user.
684 const AccessList *getBlockAccesses(const BasicBlock *BB) const {
685 return getWritableBlockAccesses(BB);
686 }
687
688 /// \brief Return the list of MemoryDef's and MemoryPhi's for a given basic
689 /// block.
690 ///
691 /// This list is not modifiable by the user.
692 const DefsList *getBlockDefs(const BasicBlock *BB) const {
693 return getWritableBlockDefs(BB);
694 }
695
696 /// \brief Given two memory accesses in the same basic block, determine
697 /// whether MemoryAccess \p A dominates MemoryAccess \p B.
698 bool locallyDominates(const MemoryAccess *A, const MemoryAccess *B) const;
699
700 /// \brief Given two memory accesses in potentially different blocks,
701 /// determine whether MemoryAccess \p A dominates MemoryAccess \p B.
702 bool dominates(const MemoryAccess *A, const MemoryAccess *B) const;
703
704 /// \brief Given a MemoryAccess and a Use, determine whether MemoryAccess \p A
705 /// dominates Use \p B.
706 bool dominates(const MemoryAccess *A, const Use &B) const;
707
708 /// \brief Verify that MemorySSA is self consistent (IE definitions dominate
709 /// all uses, uses appear in the right places). This is used by unit tests.
710 void verifyMemorySSA() const;
711
712 /// Used in various insertion functions to specify whether we are talking
713 /// about the beginning or end of a block.
714 enum InsertionPlace { Beginning, End };
715
716protected:
717 // Used by Memory SSA annotater, dumpers, and wrapper pass
718 friend class MemorySSAAnnotatedWriter;
719 friend class MemorySSAPrinterLegacyPass;
720 friend class MemorySSAUpdater;
721
722 void verifyDefUses(Function &F) const;
723 void verifyDomination(Function &F) const;
724 void verifyOrdering(Function &F) const;
725
726 // This is used by the use optimizer and updater.
727 AccessList *getWritableBlockAccesses(const BasicBlock *BB) const {
728 auto It = PerBlockAccesses.find(BB);
729 return It == PerBlockAccesses.end() ? nullptr : It->second.get();
730 }
731
732 // This is used by the use optimizer and updater.
733 DefsList *getWritableBlockDefs(const BasicBlock *BB) const {
734 auto It = PerBlockDefs.find(BB);
735 return It == PerBlockDefs.end() ? nullptr : It->second.get();
736 }
737
738 // These is used by the updater to perform various internal MemorySSA
739 // machinsations. They do not always leave the IR in a correct state, and
740 // relies on the updater to fixup what it breaks, so it is not public.
741
742 void moveTo(MemoryUseOrDef *What, BasicBlock *BB, AccessList::iterator Where);
743 void moveTo(MemoryUseOrDef *What, BasicBlock *BB, InsertionPlace Point);
744
745 // Rename the dominator tree branch rooted at BB.
746 void renamePass(BasicBlock *BB, MemoryAccess *IncomingVal,
747 SmallPtrSetImpl<BasicBlock *> &Visited) {
748 renamePass(DT->getNode(BB), IncomingVal, Visited, true, true);
749 }
750
751 void removeFromLookups(MemoryAccess *);
752 void removeFromLists(MemoryAccess *, bool ShouldDelete = true);
753 void insertIntoListsForBlock(MemoryAccess *, const BasicBlock *,
754 InsertionPlace);
755 void insertIntoListsBefore(MemoryAccess *, const BasicBlock *,
756 AccessList::iterator);
757 MemoryUseOrDef *createDefinedAccess(Instruction *, MemoryAccess *);
758
759private:
760 class CachingWalker;
761 class OptimizeUses;
762
763 CachingWalker *getWalkerImpl();
764 void buildMemorySSA();
765 void optimizeUses();
766
767 void verifyUseInDefs(MemoryAccess *, MemoryAccess *) const;
768
769 using AccessMap = DenseMap<const BasicBlock *, std::unique_ptr<AccessList>>;
770 using DefsMap = DenseMap<const BasicBlock *, std::unique_ptr<DefsList>>;
771
772 void
773 determineInsertionPoint(const SmallPtrSetImpl<BasicBlock *> &DefiningBlocks);
774 void markUnreachableAsLiveOnEntry(BasicBlock *BB);
775 bool dominatesUse(const MemoryAccess *, const MemoryAccess *) const;
776 MemoryPhi *createMemoryPhi(BasicBlock *BB);
777 MemoryUseOrDef *createNewAccess(Instruction *);
778 MemoryAccess *findDominatingDef(BasicBlock *, enum InsertionPlace);
779 void placePHINodes(const SmallPtrSetImpl<BasicBlock *> &,
780 const DenseMap<const BasicBlock *, unsigned int> &);
781 MemoryAccess *renameBlock(BasicBlock *, MemoryAccess *, bool);
782 void renameSuccessorPhis(BasicBlock *, MemoryAccess *, bool);
783 void renamePass(DomTreeNode *, MemoryAccess *IncomingVal,
784 SmallPtrSetImpl<BasicBlock *> &Visited,
785 bool SkipVisited = false, bool RenameAllUses = false);
786 AccessList *getOrCreateAccessList(const BasicBlock *);
787 DefsList *getOrCreateDefsList(const BasicBlock *);
788 void renumberBlock(const BasicBlock *) const;
789 AliasAnalysis *AA;
790 DominatorTree *DT;
791 Function &F;
792
793 // Memory SSA mappings
794 DenseMap<const Value *, MemoryAccess *> ValueToMemoryAccess;
795
796 // These two mappings contain the main block to access/def mappings for
797 // MemorySSA. The list contained in PerBlockAccesses really owns all the
798 // MemoryAccesses.
799 // Both maps maintain the invariant that if a block is found in them, the
800 // corresponding list is not empty, and if a block is not found in them, the
801 // corresponding list is empty.
802 AccessMap PerBlockAccesses;
803 DefsMap PerBlockDefs;
804 std::unique_ptr<MemoryAccess, ValueDeleter> LiveOnEntryDef;
805
806 // Domination mappings
807 // Note that the numbering is local to a block, even though the map is
808 // global.
809 mutable SmallPtrSet<const BasicBlock *, 16> BlockNumberingValid;
810 mutable DenseMap<const MemoryAccess *, unsigned long> BlockNumbering;
811
812 // Memory SSA building info
813 std::unique_ptr<CachingWalker> Walker;
814 unsigned NextID;
815};
816
817// Internal MemorySSA utils, for use by MemorySSA classes and walkers
818class MemorySSAUtil {
819protected:
820 friend class GVNHoist;
821 friend class MemorySSAWalker;
822
823 // This function should not be used by new passes.
824 static bool defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU,
825 AliasAnalysis &AA);
826};
827
828// This pass does eager building and then printing of MemorySSA. It is used by
829// the tests to be able to build, dump, and verify Memory SSA.
830class MemorySSAPrinterLegacyPass : public FunctionPass {
831public:
832 MemorySSAPrinterLegacyPass();
833
834 bool runOnFunction(Function &) override;
835 void getAnalysisUsage(AnalysisUsage &AU) const override;
836
837 static char ID;
838};
839
840/// An analysis that produces \c MemorySSA for a function.
841///
842class MemorySSAAnalysis : public AnalysisInfoMixin<MemorySSAAnalysis> {
843 friend AnalysisInfoMixin<MemorySSAAnalysis>;
844
845 static AnalysisKey Key;
846
847public:
848 // Wrap MemorySSA result to ensure address stability of internal MemorySSA
849 // pointers after construction. Use a wrapper class instead of plain
850 // unique_ptr<MemorySSA> to avoid build breakage on MSVC.
851 struct Result {
852 Result(std::unique_ptr<MemorySSA> &&MSSA) : MSSA(std::move(MSSA)) {}
853
854 MemorySSA &getMSSA() { return *MSSA.get(); }
855
856 std::unique_ptr<MemorySSA> MSSA;
857 };
858
859 Result run(Function &F, FunctionAnalysisManager &AM);
860};
861
862/// \brief Printer pass for \c MemorySSA.
863class MemorySSAPrinterPass : public PassInfoMixin<MemorySSAPrinterPass> {
864 raw_ostream &OS;
865
866public:
867 explicit MemorySSAPrinterPass(raw_ostream &OS) : OS(OS) {}
868
869 PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
870};
871
872/// \brief Verifier pass for \c MemorySSA.
873struct MemorySSAVerifierPass : PassInfoMixin<MemorySSAVerifierPass> {
874 PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
875};
876
877/// \brief Legacy analysis pass which computes \c MemorySSA.
878class MemorySSAWrapperPass : public FunctionPass {
879public:
880 MemorySSAWrapperPass();
881
882 static char ID;
883
884 bool runOnFunction(Function &) override;
885 void releaseMemory() override;
886 MemorySSA &getMSSA() { return *MSSA; }
887 const MemorySSA &getMSSA() const { return *MSSA; }
888
889 void getAnalysisUsage(AnalysisUsage &AU) const override;
890
891 void verifyAnalysis() const override;
892 void print(raw_ostream &OS, const Module *M = nullptr) const override;
893
894private:
895 std::unique_ptr<MemorySSA> MSSA;
896};
897
898/// \brief This is the generic walker interface for walkers of MemorySSA.
899/// Walkers are used to be able to further disambiguate the def-use chains
900/// MemorySSA gives you, or otherwise produce better info than MemorySSA gives
901/// you.
902/// In particular, while the def-use chains provide basic information, and are
903/// guaranteed to give, for example, the nearest may-aliasing MemoryDef for a
904/// MemoryUse as AliasAnalysis considers it, a user mant want better or other
905/// information. In particular, they may want to use SCEV info to further
906/// disambiguate memory accesses, or they may want the nearest dominating
907/// may-aliasing MemoryDef for a call or a store. This API enables a
908/// standardized interface to getting and using that info.
909class MemorySSAWalker {
910public:
911 MemorySSAWalker(MemorySSA *);
912 virtual ~MemorySSAWalker() = default;
913
914 using MemoryAccessSet = SmallVector<MemoryAccess *, 8>;
915
916 /// \brief Given a memory Mod/Ref/ModRef'ing instruction, calling this
917 /// will give you the nearest dominating MemoryAccess that Mod's the location
918 /// the instruction accesses (by skipping any def which AA can prove does not
919 /// alias the location(s) accessed by the instruction given).
920 ///
921 /// Note that this will return a single access, and it must dominate the
922 /// Instruction, so if an operand of a MemoryPhi node Mod's the instruction,
923 /// this will return the MemoryPhi, not the operand. This means that
924 /// given:
925 /// if (a) {
926 /// 1 = MemoryDef(liveOnEntry)
927 /// store %a
928 /// } else {
929 /// 2 = MemoryDef(liveOnEntry)
930 /// store %b
931 /// }
932 /// 3 = MemoryPhi(2, 1)
933 /// MemoryUse(3)
934 /// load %a
935 ///
936 /// calling this API on load(%a) will return the MemoryPhi, not the MemoryDef
937 /// in the if (a) branch.
938 MemoryAccess *getClobberingMemoryAccess(const Instruction *I) {
939 MemoryAccess *MA = MSSA->getMemoryAccess(I);
940 assert(MA && "Handed an instruction that MemorySSA doesn't recognize?");
941 return getClobberingMemoryAccess(MA);
942 }
943
944 /// Does the same thing as getClobberingMemoryAccess(const Instruction *I),
945 /// but takes a MemoryAccess instead of an Instruction.
946 virtual MemoryAccess *getClobberingMemoryAccess(MemoryAccess *) = 0;
947
948 /// \brief Given a potentially clobbering memory access and a new location,
949 /// calling this will give you the nearest dominating clobbering MemoryAccess
950 /// (by skipping non-aliasing def links).
951 ///
952 /// This version of the function is mainly used to disambiguate phi translated
953 /// pointers, where the value of a pointer may have changed from the initial
954 /// memory access. Note that this expects to be handed either a MemoryUse,
955 /// or an already potentially clobbering access. Unlike the above API, if
956 /// given a MemoryDef that clobbers the pointer as the starting access, it
957 /// will return that MemoryDef, whereas the above would return the clobber
958 /// starting from the use side of the memory def.
959 virtual MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
960 const MemoryLocation &) = 0;
961
962 /// \brief Given a memory access, invalidate anything this walker knows about
963 /// that access.
964 /// This API is used by walkers that store information to perform basic cache
965 /// invalidation. This will be called by MemorySSA at appropriate times for
966 /// the walker it uses or returns.
967 virtual void invalidateInfo(MemoryAccess *) {}
968
969 virtual void verify(const MemorySSA *MSSA) { assert(MSSA == this->MSSA); }
970
971protected:
972 friend class MemorySSA; // For updating MSSA pointer in MemorySSA move
973 // constructor.
974 MemorySSA *MSSA;
975};
976
977/// \brief A MemorySSAWalker that does no alias queries, or anything else. It
978/// simply returns the links as they were constructed by the builder.
979class DoNothingMemorySSAWalker final : public MemorySSAWalker {
980public:
981 // Keep the overrides below from hiding the Instruction overload of
982 // getClobberingMemoryAccess.
983 using MemorySSAWalker::getClobberingMemoryAccess;
984
985 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *) override;
986 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
987 const MemoryLocation &) override;
988};
989
990using MemoryAccessPair = std::pair<MemoryAccess *, MemoryLocation>;
991using ConstMemoryAccessPair = std::pair<const MemoryAccess *, MemoryLocation>;
992
993/// \brief Iterator base class used to implement const and non-const iterators
994/// over the defining accesses of a MemoryAccess.
995template <class T>
996class memoryaccess_def_iterator_base
997 : public iterator_facade_base<memoryaccess_def_iterator_base<T>,
998 std::forward_iterator_tag, T, ptrdiff_t, T *,
999 T *> {
1000 using BaseT = typename memoryaccess_def_iterator_base::iterator_facade_base;
1001
1002public:
1003 memoryaccess_def_iterator_base(T *Start) : Access(Start) {}
1004 memoryaccess_def_iterator_base() = default;
1005
1006 bool operator==(const memoryaccess_def_iterator_base &Other) const {
1007 return Access == Other.Access && (!Access || ArgNo == Other.ArgNo);
1008 }
1009
1010 // This is a bit ugly, but for MemoryPHI's, unlike PHINodes, you can't get the
1011 // block from the operand in constant time (In a PHINode, the uselist has
1012 // both, so it's just subtraction). We provide it as part of the
1013 // iterator to avoid callers having to linear walk to get the block.
1014 // If the operation becomes constant time on MemoryPHI's, this bit of
1015 // abstraction breaking should be removed.
1016 BasicBlock *getPhiArgBlock() const {
1017 MemoryPhi *MP = dyn_cast<MemoryPhi>(Access);
1018 assert(MP && "Tried to get phi arg block when not iterating over a PHI");
1019 return MP->getIncomingBlock(ArgNo);
1020 }
1021
1022 typename BaseT::iterator::pointer operator*() const {
1023 assert(Access && "Tried to access past the end of our iterator");
1024 // Go to the first argument for phis, and the defining access for everything
1025 // else.
1026 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(Access))
1027 return MP->getIncomingValue(ArgNo);
1028 return cast<MemoryUseOrDef>(Access)->getDefiningAccess();
1029 }
1030
1031 using BaseT::operator++;
1032 memoryaccess_def_iterator &operator++() {
1033 assert(Access && "Hit end of iterator");
1034 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(Access)) {
1035 if (++ArgNo >= MP->getNumIncomingValues()) {
1036 ArgNo = 0;
1037 Access = nullptr;
1038 }
1039 } else {
1040 Access = nullptr;
1041 }
1042 return *this;
1043 }
1044
1045private:
1046 T *Access = nullptr;
1047 unsigned ArgNo = 0;
1048};
1049
1050inline memoryaccess_def_iterator MemoryAccess::defs_begin() {
1051 return memoryaccess_def_iterator(this);
1052}
1053
1054inline const_memoryaccess_def_iterator MemoryAccess::defs_begin() const {
1055 return const_memoryaccess_def_iterator(this);
1056}
1057
1058inline memoryaccess_def_iterator MemoryAccess::defs_end() {
1059 return memoryaccess_def_iterator();
1060}
1061
1062inline const_memoryaccess_def_iterator MemoryAccess::defs_end() const {
1063 return const_memoryaccess_def_iterator();
1064}
1065
1066/// \brief GraphTraits for a MemoryAccess, which walks defs in the normal case,
1067/// and uses in the inverse case.
1068template <> struct GraphTraits<MemoryAccess *> {
1069 using NodeRef = MemoryAccess *;
1070 using ChildIteratorType = memoryaccess_def_iterator;
1071
1072 static NodeRef getEntryNode(NodeRef N) { return N; }
1073 static ChildIteratorType child_begin(NodeRef N) { return N->defs_begin(); }
1074 static ChildIteratorType child_end(NodeRef N) { return N->defs_end(); }
1075};
1076
1077template <> struct GraphTraits<Inverse<MemoryAccess *>> {
1078 using NodeRef = MemoryAccess *;
1079 using ChildIteratorType = MemoryAccess::iterator;
1080
1081 static NodeRef getEntryNode(NodeRef N) { return N; }
1082 static ChildIteratorType child_begin(NodeRef N) { return N->user_begin(); }
1083 static ChildIteratorType child_end(NodeRef N) { return N->user_end(); }
1084};
1085
1086/// \brief Provide an iterator that walks defs, giving both the memory access,
1087/// and the current pointer location, updating the pointer location as it
1088/// changes due to phi node translation.
1089///
1090/// This iterator, while somewhat specialized, is what most clients actually
1091/// want when walking upwards through MemorySSA def chains. It takes a pair of
1092/// <MemoryAccess,MemoryLocation>, and walks defs, properly translating the
1093/// memory location through phi nodes for the user.
1094class upward_defs_iterator
1095 : public iterator_facade_base<upward_defs_iterator,
1096 std::forward_iterator_tag,
1097 const MemoryAccessPair> {
1098 using BaseT = upward_defs_iterator::iterator_facade_base;
1099
1100public:
1101 upward_defs_iterator(const MemoryAccessPair &Info)
1102 : DefIterator(Info.first), Location(Info.second),
1103 OriginalAccess(Info.first) {
1104 CurrentPair.first = nullptr;
1105
1106 WalkingPhi = Info.first && isa<MemoryPhi>(Info.first);
1107 fillInCurrentPair();
1108 }
1109
1110 upward_defs_iterator() { CurrentPair.first = nullptr; }
1111
1112 bool operator==(const upward_defs_iterator &Other) const {
1113 return DefIterator == Other.DefIterator;
1114 }
1115
1116 BaseT::iterator::reference operator*() const {
1117 assert(DefIterator != OriginalAccess->defs_end() &&
1118 "Tried to access past the end of our iterator");
1119 return CurrentPair;
1120 }
1121
1122 using BaseT::operator++;
1123 upward_defs_iterator &operator++() {
1124 assert(DefIterator != OriginalAccess->defs_end() &&
1125 "Tried to access past the end of the iterator");
1126 ++DefIterator;
1127 if (DefIterator != OriginalAccess->defs_end())
1128 fillInCurrentPair();
1129 return *this;
1130 }
1131
1132 BasicBlock *getPhiArgBlock() const { return DefIterator.getPhiArgBlock(); }
1133
1134private:
1135 void fillInCurrentPair() {
1136 CurrentPair.first = *DefIterator;
1137 if (WalkingPhi && Location.Ptr) {
1138 PHITransAddr Translator(
1139 const_cast<Value *>(Location.Ptr),
1140 OriginalAccess->getBlock()->getModule()->getDataLayout(), nullptr);
1141 if (!Translator.PHITranslateValue(OriginalAccess->getBlock(),
1142 DefIterator.getPhiArgBlock(), nullptr,
1143 false))
1144 if (Translator.getAddr() != Location.Ptr) {
1145 CurrentPair.second = Location.getWithNewPtr(Translator.getAddr());
1146 return;
1147 }
1148 }
1149 CurrentPair.second = Location;
1150 }
1151
1152 MemoryAccessPair CurrentPair;
1153 memoryaccess_def_iterator DefIterator;
1154 MemoryLocation Location;
1155 MemoryAccess *OriginalAccess = nullptr;
1156 bool WalkingPhi = false;
1157};
1158
1159inline upward_defs_iterator upward_defs_begin(const MemoryAccessPair &Pair) {
1160 return upward_defs_iterator(Pair);
1161}
1162
1163inline upward_defs_iterator upward_defs_end() { return upward_defs_iterator(); }
1164
1165inline iterator_range<upward_defs_iterator>
1166upward_defs(const MemoryAccessPair &Pair) {
1167 return make_range(upward_defs_begin(Pair), upward_defs_end());
1168}
1169
1170/// Walks the defining accesses of MemoryDefs. Stops after we hit something that
1171/// has no defining use (e.g. a MemoryPhi or liveOnEntry). Note that, when
1172/// comparing against a null def_chain_iterator, this will compare equal only
1173/// after walking said Phi/liveOnEntry.
1174///
1175/// The UseOptimizedChain flag specifies whether to walk the clobbering
1176/// access chain, or all the accesses.
1177///
1178/// Normally, MemoryDef are all just def/use linked together, so a def_chain on
1179/// a MemoryDef will walk all MemoryDefs above it in the program until it hits
1180/// a phi node. The optimized chain walks the clobbering access of a store.
1181/// So if you are just trying to find, given a store, what the next
1182/// thing that would clobber the same memory is, you want the optimized chain.
1183template <class T, bool UseOptimizedChain = false>
1184struct def_chain_iterator
1185 : public iterator_facade_base<def_chain_iterator<T, UseOptimizedChain>,
1186 std::forward_iterator_tag, MemoryAccess *> {
1187 def_chain_iterator() : MA(nullptr) {}
1188 def_chain_iterator(T MA) : MA(MA) {}
1189
1190 T operator*() const { return MA; }
1191
1192 def_chain_iterator &operator++() {
1193 // N.B. liveOnEntry has a null defining access.
1194 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
1195 if (UseOptimizedChain && MUD->isOptimized())
1196 MA = MUD->getOptimized();
1197 else
1198 MA = MUD->getDefiningAccess();
1199 } else {
1200 MA = nullptr;
1201 }
1202
1203 return *this;
1204 }
1205
1206 bool operator==(const def_chain_iterator &O) const { return MA == O.MA; }
1207
1208private:
1209 T MA;
1210};
1211
1212template <class T>
1213inline iterator_range<def_chain_iterator<T>>
1214def_chain(T MA, MemoryAccess *UpTo = nullptr) {
1215#ifdef EXPENSIVE_CHECKS
1216 assert((!UpTo || find(def_chain(MA), UpTo) != def_chain_iterator<T>()) &&
1217 "UpTo isn't in the def chain!");
1218#endif
1219 return make_range(def_chain_iterator<T>(MA), def_chain_iterator<T>(UpTo));
1220}
1221
1222template <class T>
1223inline iterator_range<def_chain_iterator<T, true>> optimized_def_chain(T MA) {
1224 return make_range(def_chain_iterator<T, true>(MA),
1225 def_chain_iterator<T, true>(nullptr));
1226}
1227
1228} // end namespace llvm
1229
1230#endif // LLVM_ANALYSIS_MEMORYSSA_H