]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/Analysis/AliasSetTracker.h
Update llvm to release_39 branch r276489, and resolve conflicts.
[FreeBSD/FreeBSD.git] / contrib / llvm / include / llvm / Analysis / AliasSetTracker.h
1 //===- llvm/Analysis/AliasSetTracker.h - Build Alias Sets -------*- 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 // This file defines two classes: AliasSetTracker and AliasSet. These interfaces
11 // are used to classify a collection of pointer references into a maximal number
12 // of disjoint sets. Each AliasSet object constructed by the AliasSetTracker
13 // object refers to memory disjoint from the other sets.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #ifndef LLVM_ANALYSIS_ALIASSETTRACKER_H
18 #define LLVM_ANALYSIS_ALIASSETTRACKER_H
19
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/ilist.h"
22 #include "llvm/ADT/ilist_node.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/IR/Metadata.h"
25 #include "llvm/IR/ValueHandle.h"
26 #include <vector>
27
28 namespace llvm {
29
30 class LoadInst;
31 class StoreInst;
32 class VAArgInst;
33 class MemSetInst;
34 class AliasSetTracker;
35 class AliasSet;
36
37 class AliasSet : public ilist_node<AliasSet> {
38   friend class AliasSetTracker;
39
40   class PointerRec {
41     Value *Val;  // The pointer this record corresponds to.
42     PointerRec **PrevInList, *NextInList;
43     AliasSet *AS;
44     uint64_t Size;
45     AAMDNodes AAInfo;
46
47   public:
48     PointerRec(Value *V)
49       : Val(V), PrevInList(nullptr), NextInList(nullptr), AS(nullptr), Size(0),
50         AAInfo(DenseMapInfo<AAMDNodes>::getEmptyKey()) {}
51
52     Value *getValue() const { return Val; }
53
54     PointerRec *getNext() const { return NextInList; }
55     bool hasAliasSet() const { return AS != nullptr; }
56
57     PointerRec** setPrevInList(PointerRec **PIL) {
58       PrevInList = PIL;
59       return &NextInList;
60     }
61
62     bool updateSizeAndAAInfo(uint64_t NewSize, const AAMDNodes &NewAAInfo) {
63       bool SizeChanged = false;
64       if (NewSize > Size) {
65         Size = NewSize;
66         SizeChanged = true;
67       }
68
69       if (AAInfo == DenseMapInfo<AAMDNodes>::getEmptyKey())
70         // We don't have a AAInfo yet. Set it to NewAAInfo.
71         AAInfo = NewAAInfo;
72       else if (AAInfo != NewAAInfo)
73         // NewAAInfo conflicts with AAInfo.
74         AAInfo = DenseMapInfo<AAMDNodes>::getTombstoneKey();
75
76       return SizeChanged;
77     }
78
79     uint64_t getSize() const { return Size; }
80
81     /// Return the AAInfo, or null if there is no information or conflicting
82     /// information.
83     AAMDNodes getAAInfo() const {
84       // If we have missing or conflicting AAInfo, return null.
85       if (AAInfo == DenseMapInfo<AAMDNodes>::getEmptyKey() ||
86           AAInfo == DenseMapInfo<AAMDNodes>::getTombstoneKey())
87         return AAMDNodes();
88       return AAInfo;
89     }
90
91     AliasSet *getAliasSet(AliasSetTracker &AST) {
92       assert(AS && "No AliasSet yet!");
93       if (AS->Forward) {
94         AliasSet *OldAS = AS;
95         AS = OldAS->getForwardedTarget(AST);
96         AS->addRef();
97         OldAS->dropRef(AST);
98       }
99       return AS;
100     }
101
102     void setAliasSet(AliasSet *as) {
103       assert(!AS && "Already have an alias set!");
104       AS = as;
105     }
106
107     void eraseFromList() {
108       if (NextInList) NextInList->PrevInList = PrevInList;
109       *PrevInList = NextInList;
110       if (AS->PtrListEnd == &NextInList) {
111         AS->PtrListEnd = PrevInList;
112         assert(*AS->PtrListEnd == nullptr && "List not terminated right!");
113       }
114       delete this;
115     }
116   };
117
118   PointerRec *PtrList, **PtrListEnd;  // Doubly linked list of nodes.
119   AliasSet *Forward;             // Forwarding pointer.
120
121   /// All instructions without a specific address in this alias set.
122   std::vector<AssertingVH<Instruction> > UnknownInsts;
123
124   /// Number of nodes pointing to this AliasSet plus the number of AliasSets
125   /// forwarding to it.
126   unsigned RefCount : 28;
127
128   /// The kinds of access this alias set models.
129   ///
130   /// We keep track of whether this alias set merely refers to the locations of
131   /// memory (and not any particular access), whether it modifies or references
132   /// the memory, or whether it does both. The lattice goes from "NoAccess" to
133   /// either RefAccess or ModAccess, then to ModRefAccess as necessary.
134   enum AccessLattice {
135     NoAccess = 0,
136     RefAccess = 1,
137     ModAccess = 2,
138     ModRefAccess = RefAccess | ModAccess
139   };
140   unsigned Access : 2;
141
142   /// The kind of alias relationship between pointers of the set.
143   ///
144   /// These represent conservatively correct alias results between any members
145   /// of the set. We represent these independently of the values of alias
146   /// results in order to pack it into a single bit. Lattice goes from
147   /// MustAlias to MayAlias.
148   enum AliasLattice {
149     SetMustAlias = 0, SetMayAlias = 1
150   };
151   unsigned Alias : 1;
152
153   /// True if this alias set contains volatile loads or stores.
154   unsigned Volatile : 1;
155
156   void addRef() { ++RefCount; }
157   void dropRef(AliasSetTracker &AST) {
158     assert(RefCount >= 1 && "Invalid reference count detected!");
159     if (--RefCount == 0)
160       removeFromTracker(AST);
161   }
162
163   Instruction *getUnknownInst(unsigned i) const {
164     assert(i < UnknownInsts.size());
165     return UnknownInsts[i];
166   }
167
168 public:
169   /// Accessors...
170   bool isRef() const { return Access & RefAccess; }
171   bool isMod() const { return Access & ModAccess; }
172   bool isMustAlias() const { return Alias == SetMustAlias; }
173   bool isMayAlias()  const { return Alias == SetMayAlias; }
174
175   /// Return true if this alias set contains volatile loads or stores.
176   bool isVolatile() const { return Volatile; }
177
178   /// Return true if this alias set should be ignored as part of the
179   /// AliasSetTracker object.
180   bool isForwardingAliasSet() const { return Forward; }
181
182   /// Merge the specified alias set into this alias set.
183   void mergeSetIn(AliasSet &AS, AliasSetTracker &AST);
184
185   // Alias Set iteration - Allow access to all of the pointers which are part of
186   // this alias set.
187   class iterator;
188   iterator begin() const { return iterator(PtrList); }
189   iterator end()   const { return iterator(); }
190   bool empty() const { return PtrList == nullptr; }
191
192   void print(raw_ostream &OS) const;
193   void dump() const;
194
195   /// Define an iterator for alias sets... this is just a forward iterator.
196   class iterator : public std::iterator<std::forward_iterator_tag,
197                                         PointerRec, ptrdiff_t> {
198     PointerRec *CurNode;
199
200   public:
201     explicit iterator(PointerRec *CN = nullptr) : CurNode(CN) {}
202
203     bool operator==(const iterator& x) const {
204       return CurNode == x.CurNode;
205     }
206     bool operator!=(const iterator& x) const { return !operator==(x); }
207
208     value_type &operator*() const {
209       assert(CurNode && "Dereferencing AliasSet.end()!");
210       return *CurNode;
211     }
212     value_type *operator->() const { return &operator*(); }
213
214     Value *getPointer() const { return CurNode->getValue(); }
215     uint64_t getSize() const { return CurNode->getSize(); }
216     AAMDNodes getAAInfo() const { return CurNode->getAAInfo(); }
217
218     iterator& operator++() {                // Preincrement
219       assert(CurNode && "Advancing past AliasSet.end()!");
220       CurNode = CurNode->getNext();
221       return *this;
222     }
223     iterator operator++(int) { // Postincrement
224       iterator tmp = *this; ++*this; return tmp;
225     }
226   };
227
228 private:
229   // Can only be created by AliasSetTracker. Also, ilist creates one
230   // to serve as a sentinel.
231   friend struct ilist_sentinel_traits<AliasSet>;
232   AliasSet()
233     : PtrList(nullptr), PtrListEnd(&PtrList), Forward(nullptr), RefCount(0),
234       Access(NoAccess), Alias(SetMustAlias), Volatile(false) {
235   }
236
237   AliasSet(const AliasSet &AS) = delete;
238   void operator=(const AliasSet &AS) = delete;
239
240   PointerRec *getSomePointer() const {
241     return PtrList;
242   }
243
244   /// Return the real alias set this represents. If this has been merged with
245   /// another set and is forwarding, return the ultimate destination set. This
246   /// also implements the union-find collapsing as well.
247   AliasSet *getForwardedTarget(AliasSetTracker &AST) {
248     if (!Forward) return this;
249
250     AliasSet *Dest = Forward->getForwardedTarget(AST);
251     if (Dest != Forward) {
252       Dest->addRef();
253       Forward->dropRef(AST);
254       Forward = Dest;
255     }
256     return Dest;
257   }
258
259   void removeFromTracker(AliasSetTracker &AST);
260
261   void addPointer(AliasSetTracker &AST, PointerRec &Entry, uint64_t Size,
262                   const AAMDNodes &AAInfo,
263                   bool KnownMustAlias = false);
264   void addUnknownInst(Instruction *I, AliasAnalysis &AA);
265   void removeUnknownInst(AliasSetTracker &AST, Instruction *I) {
266     bool WasEmpty = UnknownInsts.empty();
267     for (size_t i = 0, e = UnknownInsts.size(); i != e; ++i)
268       if (UnknownInsts[i] == I) {
269         UnknownInsts[i] = UnknownInsts.back();
270         UnknownInsts.pop_back();
271         --i; --e;  // Revisit the moved entry.
272       }
273     if (!WasEmpty && UnknownInsts.empty())
274       dropRef(AST);
275   }
276   void setVolatile() { Volatile = true; }
277
278 public:
279   /// Return true if the specified pointer "may" (or must) alias one of the
280   /// members in the set.
281   bool aliasesPointer(const Value *Ptr, uint64_t Size, const AAMDNodes &AAInfo,
282                       AliasAnalysis &AA) const;
283   bool aliasesUnknownInst(const Instruction *Inst, AliasAnalysis &AA) const;
284 };
285
286 inline raw_ostream& operator<<(raw_ostream &OS, const AliasSet &AS) {
287   AS.print(OS);
288   return OS;
289 }
290
291 class AliasSetTracker {
292   /// A CallbackVH to arrange for AliasSetTracker to be notified whenever a
293   /// Value is deleted.
294   class ASTCallbackVH final : public CallbackVH {
295     AliasSetTracker *AST;
296     void deleted() override;
297     void allUsesReplacedWith(Value *) override;
298
299   public:
300     ASTCallbackVH(Value *V, AliasSetTracker *AST = nullptr);
301     ASTCallbackVH &operator=(Value *V);
302   };
303   /// Traits to tell DenseMap that tell us how to compare and hash the value
304   /// handle.
305   struct ASTCallbackVHDenseMapInfo : public DenseMapInfo<Value *> {};
306
307   AliasAnalysis &AA;
308   ilist<AliasSet> AliasSets;
309
310   typedef DenseMap<ASTCallbackVH, AliasSet::PointerRec*,
311                    ASTCallbackVHDenseMapInfo>
312     PointerMapType;
313
314   // Map from pointers to their node
315   PointerMapType PointerMap;
316
317 public:
318   /// Create an empty collection of AliasSets, and use the specified alias
319   /// analysis object to disambiguate load and store addresses.
320   explicit AliasSetTracker(AliasAnalysis &aa) : AA(aa) {}
321   ~AliasSetTracker() { clear(); }
322
323   /// These methods are used to add different types of instructions to the alias
324   /// sets. Adding a new instruction can result in one of three actions
325   /// happening:
326   ///
327   ///   1. If the instruction doesn't alias any other sets, create a new set.
328   ///   2. If the instruction aliases exactly one set, add it to the set
329   ///   3. If the instruction aliases multiple sets, merge the sets, and add
330   ///      the instruction to the result.
331   ///
332   /// These methods return true if inserting the instruction resulted in the
333   /// addition of a new alias set (i.e., the pointer did not alias anything).
334   ///
335   bool add(Value *Ptr, uint64_t Size, const AAMDNodes &AAInfo); // Add a loc.
336   bool add(LoadInst *LI);
337   bool add(StoreInst *SI);
338   bool add(VAArgInst *VAAI);
339   bool add(MemSetInst *MSI);
340   bool add(Instruction *I);       // Dispatch to one of the other add methods...
341   void add(BasicBlock &BB);       // Add all instructions in basic block
342   void add(const AliasSetTracker &AST); // Add alias relations from another AST
343   bool addUnknown(Instruction *I);
344
345   /// These methods are used to remove all entries that might be aliased by the
346   /// specified instruction. These methods return true if any alias sets were
347   /// eliminated.
348   bool remove(Value *Ptr, uint64_t Size, const AAMDNodes &AAInfo);
349   bool remove(LoadInst *LI);
350   bool remove(StoreInst *SI);
351   bool remove(VAArgInst *VAAI);
352   bool remove(MemSetInst *MSI);
353   bool remove(Instruction *I);
354   void remove(AliasSet &AS);
355   bool removeUnknown(Instruction *I);
356
357   void clear();
358
359   /// Return the alias sets that are active.
360   const ilist<AliasSet> &getAliasSets() const { return AliasSets; }
361
362   /// Return the alias set that the specified pointer lives in. If the New
363   /// argument is non-null, this method sets the value to true if a new alias
364   /// set is created to contain the pointer (because the pointer didn't alias
365   /// anything).
366   AliasSet &getAliasSetForPointer(Value *P, uint64_t Size,
367                                   const AAMDNodes &AAInfo,
368                                   bool *New = nullptr);
369
370   /// Return the alias set containing the location specified if one exists,
371   /// otherwise return null.
372   AliasSet *getAliasSetForPointerIfExists(const Value *P, uint64_t Size,
373                                           const AAMDNodes &AAInfo) {
374     return mergeAliasSetsForPointer(P, Size, AAInfo);
375   }
376
377   /// Return true if the specified location is represented by this alias set,
378   /// false otherwise. This does not modify the AST object or alias sets.
379   bool containsPointer(const Value *P, uint64_t Size,
380                        const AAMDNodes &AAInfo) const;
381
382   /// Return true if the specified instruction "may" (or must) alias one of the
383   /// members in any of the sets.
384   bool containsUnknown(const Instruction *I) const;
385
386   /// Return the underlying alias analysis object used by this tracker.
387   AliasAnalysis &getAliasAnalysis() const { return AA; }
388
389   /// This method is used to remove a pointer value from the AliasSetTracker
390   /// entirely. It should be used when an instruction is deleted from the
391   /// program to update the AST. If you don't use this, you would have dangling
392   /// pointers to deleted instructions.
393   void deleteValue(Value *PtrVal);
394
395   /// This method should be used whenever a preexisting value in the program is
396   /// copied or cloned, introducing a new value.  Note that it is ok for clients
397   /// that use this method to introduce the same value multiple times: if the
398   /// tracker already knows about a value, it will ignore the request.
399   void copyValue(Value *From, Value *To);
400
401   typedef ilist<AliasSet>::iterator iterator;
402   typedef ilist<AliasSet>::const_iterator const_iterator;
403
404   const_iterator begin() const { return AliasSets.begin(); }
405   const_iterator end()   const { return AliasSets.end(); }
406
407   iterator begin() { return AliasSets.begin(); }
408   iterator end()   { return AliasSets.end(); }
409
410   void print(raw_ostream &OS) const;
411   void dump() const;
412
413 private:
414   friend class AliasSet;
415   void removeAliasSet(AliasSet *AS);
416
417   /// Just like operator[] on the map, except that it creates an entry for the
418   /// pointer if it doesn't already exist.
419   AliasSet::PointerRec &getEntryFor(Value *V) {
420     AliasSet::PointerRec *&Entry = PointerMap[ASTCallbackVH(V, this)];
421     if (!Entry)
422       Entry = new AliasSet::PointerRec(V);
423     return *Entry;
424   }
425
426   AliasSet &addPointer(Value *P, uint64_t Size, const AAMDNodes &AAInfo,
427                        AliasSet::AccessLattice E,
428                        bool &NewSet) {
429     NewSet = false;
430     AliasSet &AS = getAliasSetForPointer(P, Size, AAInfo, &NewSet);
431     AS.Access |= E;
432     return AS;
433   }
434   AliasSet *mergeAliasSetsForPointer(const Value *Ptr, uint64_t Size,
435                                      const AAMDNodes &AAInfo);
436
437   AliasSet *findAliasSetForUnknownInst(Instruction *Inst);
438 };
439
440 inline raw_ostream& operator<<(raw_ostream &OS, const AliasSetTracker &AST) {
441   AST.print(OS);
442   return OS;
443 }
444
445 } // End llvm namespace
446
447 #endif