Coverage Report

Created: 2018-07-18 22:01

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/include/llvm/Analysis/MemoryDependenceAnalysis.h
Line
Count
Source (jump to first uncovered line)
1
//===- llvm/Analysis/MemoryDependenceAnalysis.h - Memory Deps ---*- 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 the MemoryDependenceAnalysis analysis pass.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#ifndef LLVM_ANALYSIS_MEMORYDEPENDENCEANALYSIS_H
15
#define LLVM_ANALYSIS_MEMORYDEPENDENCEANALYSIS_H
16
17
#include "llvm/ADT/DenseMap.h"
18
#include "llvm/ADT/Optional.h"
19
#include "llvm/ADT/PointerEmbeddedInt.h"
20
#include "llvm/ADT/PointerIntPair.h"
21
#include "llvm/ADT/PointerSumType.h"
22
#include "llvm/ADT/SmallPtrSet.h"
23
#include "llvm/Analysis/AliasAnalysis.h"
24
#include "llvm/Analysis/MemoryLocation.h"
25
#include "llvm/IR/BasicBlock.h"
26
#include "llvm/IR/Metadata.h"
27
#include "llvm/IR/PassManager.h"
28
#include "llvm/IR/PredIteratorCache.h"
29
#include "llvm/IR/ValueHandle.h"
30
#include "llvm/Pass.h"
31
#include "llvm/Support/ErrorHandling.h"
32
#include <cassert>
33
#include <cstdint>
34
#include <utility>
35
#include <vector>
36
37
namespace llvm {
38
39
class AssumptionCache;
40
class CallSite;
41
class DominatorTree;
42
class Function;
43
class Instruction;
44
class LoadInst;
45
class PHITransAddr;
46
class TargetLibraryInfo;
47
class Value;
48
49
/// A memory dependence query can return one of three different answers.
50
0
class MemDepResult {
51
  enum DepType {
52
    /// Clients of MemDep never see this.
53
    ///
54
    /// Entries with this marker occur in a LocalDeps map or NonLocalDeps map
55
    /// when the instruction they previously referenced was removed from
56
    /// MemDep.  In either case, the entry may include an instruction pointer.
57
    /// If so, the pointer is an instruction in the block where scanning can
58
    /// start from, saving some work.
59
    ///
60
    /// In a default-constructed MemDepResult object, the type will be Invalid
61
    /// and the instruction pointer will be null.
62
    Invalid = 0,
63
64
    /// This is a dependence on the specified instruction which clobbers the
65
    /// desired value.  The pointer member of the MemDepResult pair holds the
66
    /// instruction that clobbers the memory.  For example, this occurs when we
67
    /// see a may-aliased store to the memory location we care about.
68
    ///
69
    /// There are several cases that may be interesting here:
70
    ///   1. Loads are clobbered by may-alias stores.
71
    ///   2. Loads are considered clobbered by partially-aliased loads.  The
72
    ///      client may choose to analyze deeper into these cases.
73
    Clobber,
74
75
    /// This is a dependence on the specified instruction which defines or
76
    /// produces the desired memory location.  The pointer member of the
77
    /// MemDepResult pair holds the instruction that defines the memory.
78
    ///
79
    /// Cases of interest:
80
    ///   1. This could be a load or store for dependence queries on
81
    ///      load/store.  The value loaded or stored is the produced value.
82
    ///      Note that the pointer operand may be different than that of the
83
    ///      queried pointer due to must aliases and phi translation. Note
84
    ///      that the def may not be the same type as the query, the pointers
85
    ///      may just be must aliases.
86
    ///   2. For loads and stores, this could be an allocation instruction. In
87
    ///      this case, the load is loading an undef value or a store is the
88
    ///      first store to (that part of) the allocation.
89
    ///   3. Dependence queries on calls return Def only when they are readonly
90
    ///      calls or memory use intrinsics with identical callees and no
91
    ///      intervening clobbers.  No validation is done that the operands to
92
    ///      the calls are the same.
93
    Def,
94
95
    /// This marker indicates that the query has no known dependency in the
96
    /// specified block.
97
    ///
98
    /// More detailed state info is encoded in the upper part of the pair (i.e.
99
    /// the Instruction*)
100
    Other
101
  };
102
103
  /// If DepType is "Other", the upper part of the sum type is an encoding of
104
  /// the following more detailed type information.
105
  enum OtherType {
106
    /// This marker indicates that the query has no dependency in the specified
107
    /// block.
108
    ///
109
    /// To find out more, the client should query other predecessor blocks.
110
    NonLocal = 1,
111
    /// This marker indicates that the query has no dependency in the specified
112
    /// function.
113
    NonFuncLocal,
114
    /// This marker indicates that the query dependency is unknown.
115
    Unknown
116
  };
117
118
  using ValueTy = PointerSumType<
119
      DepType, PointerSumTypeMember<Invalid, Instruction *>,
120
      PointerSumTypeMember<Clobber, Instruction *>,
121
      PointerSumTypeMember<Def, Instruction *>,
122
      PointerSumTypeMember<Other, PointerEmbeddedInt<OtherType, 3>>>;
123
  ValueTy Value;
124
125
26.8M
  explicit MemDepResult(ValueTy V) : Value(V) {}
126
127
public:
128
16.7M
  MemDepResult() = default;
129
130
  /// get methods: These are static ctor methods for creating various
131
  /// MemDepResult kinds.
132
503k
  static MemDepResult getDef(Instruction *Inst) {
133
503k
    assert(Inst && "Def requires inst");
134
503k
    return MemDepResult(ValueTy::create<Def>(Inst));
135
503k
  }
136
2.05M
  static MemDepResult getClobber(Instruction *Inst) {
137
2.05M
    assert(Inst && "Clobber requires inst");
138
2.05M
    return MemDepResult(ValueTy::create<Clobber>(Inst));
139
2.05M
  }
140
5.84M
  static MemDepResult getNonLocal() {
141
5.84M
    return MemDepResult(ValueTy::create<Other>(NonLocal));
142
5.84M
  }
143
584k
  static MemDepResult getNonFuncLocal() {
144
584k
    return MemDepResult(ValueTy::create<Other>(NonFuncLocal));
145
584k
  }
146
17.4M
  static MemDepResult getUnknown() {
147
17.4M
    return MemDepResult(ValueTy::create<Other>(Unknown));
148
17.4M
  }
149
150
  /// Tests if this MemDepResult represents a query that is an instruction
151
  /// clobber dependency.
152
17.2M
  bool isClobber() const { return Value.is<Clobber>(); }
153
154
  /// Tests if this MemDepResult represents a query that is an instruction
155
  /// definition dependency.
156
30.3M
  bool isDef() const { return Value.is<Def>(); }
157
158
  /// Tests if this MemDepResult represents a query that is transparent to the
159
  /// start of the block, but where a non-local hasn't been done.
160
25.0M
  bool isNonLocal() const {
161
25.0M
    return Value.is<Other>() && 
Value.cast<Other>() == NonLocal20.7M
;
162
25.0M
  }
163
164
  /// Tests if this MemDepResult represents a query that is transparent to the
165
  /// start of the function.
166
0
  bool isNonFuncLocal() const {
167
0
    return Value.is<Other>() && Value.cast<Other>() == NonFuncLocal;
168
0
  }
169
170
  /// Tests if this MemDepResult represents a query which cannot and/or will
171
  /// not be computed.
172
26.3k
  bool isUnknown() const {
173
26.3k
    return Value.is<Other>() && 
Value.cast<Other>() == Unknown26.0k
;
174
26.3k
  }
175
176
  /// If this is a normal dependency, returns the instruction that is depended
177
  /// on.  Otherwise, returns null.
178
20.2M
  Instruction *getInst() const {
179
20.2M
    switch (Value.getTag()) {
180
20.2M
    case Invalid:
181
3.12M
      return Value.cast<Invalid>();
182
20.2M
    case Clobber:
183
13.1M
      return Value.cast<Clobber>();
184
20.2M
    case Def:
185
1.34M
      return Value.cast<Def>();
186
20.2M
    case Other:
187
2.61M
      return nullptr;
188
0
    }
189
0
    llvm_unreachable("Unknown discriminant!");
190
0
  }
191
192
  bool operator==(const MemDepResult &M) const { return Value == M.Value; }
193
  bool operator!=(const MemDepResult &M) const { return Value != M.Value; }
194
  bool operator<(const MemDepResult &M) const { return Value < M.Value; }
195
  bool operator>(const MemDepResult &M) const { return Value > M.Value; }
196
197
private:
198
  friend class MemoryDependenceResults;
199
200
  /// Tests if this is a MemDepResult in its dirty/invalid. state.
201
11.7M
  bool isDirty() const { return Value.is<Invalid>(); }
202
203
347k
  static MemDepResult getDirty(Instruction *Inst) {
204
347k
    return MemDepResult(ValueTy::create<Invalid>(Inst));
205
347k
  }
206
};
207
208
/// This is an entry in the NonLocalDepInfo cache.
209
///
210
/// For each BasicBlock (the BB entry) it keeps a MemDepResult.
211
class NonLocalDepEntry {
212
  BasicBlock *BB;
213
  MemDepResult Result;
214
215
public:
216
  NonLocalDepEntry(BasicBlock *bb, MemDepResult result)
217
11.1M
      : BB(bb), Result(result) {}
218
219
  // This is used for searches.
220
13.3M
  NonLocalDepEntry(BasicBlock *bb) : BB(bb) {}
221
222
  // BB is the sort key, it can't be changed.
223
23.7M
  BasicBlock *getBB() const { return BB; }
224
225
34.9k
  void setResult(const MemDepResult &R) { Result = R; }
226
227
22.8M
  const MemDepResult &getResult() const { return Result; }
228
229
94.0M
  bool operator<(const NonLocalDepEntry &RHS) const { return BB < RHS.BB; }
230
};
231
232
/// This is a result from a NonLocal dependence query.
233
///
234
/// For each BasicBlock (the BB entry) it keeps a MemDepResult and the
235
/// (potentially phi translated) address that was live in the block.
236
class NonLocalDepResult {
237
  NonLocalDepEntry Entry;
238
  Value *Address;
239
240
public:
241
  NonLocalDepResult(BasicBlock *bb, MemDepResult result, Value *address)
242
5.33M
      : Entry(bb, result), Address(address) {}
243
244
  // BB is the sort key, it can't be changed.
245
4.72M
  BasicBlock *getBB() const { return Entry.getBB(); }
246
247
0
  void setResult(const MemDepResult &R, Value *Addr) {
248
0
    Entry.setResult(R);
249
0
    Address = Addr;
250
0
  }
251
252
6.43M
  const MemDepResult &getResult() const { return Entry.getResult(); }
253
254
  /// Returns the address of this pointer in this block.
255
  ///
256
  /// This can be different than the address queried for the non-local result
257
  /// because of phi translation.  This returns null if the address was not
258
  /// available in a block (i.e. because phi translation failed) or if this is
259
  /// a cached result and that address was deleted.
260
  ///
261
  /// The address is always null for a non-local 'call' dependence.
262
3.41M
  Value *getAddress() const { return Address; }
263
};
264
265
/// Provides a lazy, caching interface for making common memory aliasing
266
/// information queries, backed by LLVM's alias analysis passes.
267
///
268
/// The dependency information returned is somewhat unusual, but is pragmatic.
269
/// If queried about a store or call that might modify memory, the analysis
270
/// will return the instruction[s] that may either load from that memory or
271
/// store to it.  If queried with a load or call that can never modify memory,
272
/// the analysis will return calls and stores that might modify the pointer,
273
/// but generally does not return loads unless a) they are volatile, or
274
/// b) they load from *must-aliased* pointers.  Returning a dependence on
275
/// must-alias'd pointers instead of all pointers interacts well with the
276
/// internal caching mechanism.
277
class MemoryDependenceResults {
278
  // A map from instructions to their dependency.
279
  using LocalDepMapType = DenseMap<Instruction *, MemDepResult>;
280
  LocalDepMapType LocalDeps;
281
282
public:
283
  using NonLocalDepInfo = std::vector<NonLocalDepEntry>;
284
285
private:
286
  /// A pair<Value*, bool> where the bool is true if the dependence is a read
287
  /// only dependence, false if read/write.
288
  using ValueIsLoadPair = PointerIntPair<const Value *, 1, bool>;
289
290
  /// This pair is used when caching information for a block.
291
  ///
292
  /// If the pointer is null, the cache value is not a full query that starts
293
  /// at the specified block.  If non-null, the bool indicates whether or not
294
  /// the contents of the block was skipped.
295
  using BBSkipFirstBlockPair = PointerIntPair<BasicBlock *, 1, bool>;
296
297
  /// This record is the information kept for each (value, is load) pair.
298
  struct NonLocalPointerInfo {
299
    /// The pair of the block and the skip-first-block flag.
300
    BBSkipFirstBlockPair Pair;
301
    /// The results of the query for each relevant block.
302
    NonLocalDepInfo NonLocalDeps;
303
    /// The maximum size of the dereferences of the pointer.
304
    ///
305
    /// May be UnknownSize if the sizes are unknown.
306
    LocationSize Size = MemoryLocation::UnknownSize;
307
    /// The AA tags associated with dereferences of the pointer.
308
    ///
309
    /// The members may be null if there are no tags or conflicting tags.
310
    AAMDNodes AATags;
311
312
3.52M
    NonLocalPointerInfo() = default;
313
  };
314
315
  /// Cache storing single nonlocal def for the instruction.
316
  /// It is set when nonlocal def would be found in function returning only
317
  /// local dependencies.
318
  DenseMap<AssertingVH<const Value>, NonLocalDepResult> NonLocalDefsCache;
319
  using ReverseNonLocalDefsCacheTy =
320
    DenseMap<Instruction *, SmallPtrSet<const Value*, 4>>;
321
  ReverseNonLocalDefsCacheTy ReverseNonLocalDefsCache;
322
323
  /// This map stores the cached results of doing a pointer lookup at the
324
  /// bottom of a block.
325
  ///
326
  /// The key of this map is the pointer+isload bit, the value is a list of
327
  /// <bb->result> mappings.
328
  using CachedNonLocalPointerInfo =
329
      DenseMap<ValueIsLoadPair, NonLocalPointerInfo>;
330
  CachedNonLocalPointerInfo NonLocalPointerDeps;
331
332
  // A map from instructions to their non-local pointer dependencies.
333
  using ReverseNonLocalPtrDepTy =
334
      DenseMap<Instruction *, SmallPtrSet<ValueIsLoadPair, 4>>;
335
  ReverseNonLocalPtrDepTy ReverseNonLocalPtrDeps;
336
337
  /// This is the instruction we keep for each cached access that we have for
338
  /// an instruction.
339
  ///
340
  /// The pointer is an owning pointer and the bool indicates whether we have
341
  /// any dirty bits in the set.
342
  using PerInstNLInfo = std::pair<NonLocalDepInfo, bool>;
343
344
  // A map from instructions to their non-local dependencies.
345
  using NonLocalDepMapType = DenseMap<Instruction *, PerInstNLInfo>;
346
347
  NonLocalDepMapType NonLocalDeps;
348
349
  // A reverse mapping from dependencies to the dependees.  This is
350
  // used when removing instructions to keep the cache coherent.
351
  using ReverseDepMapType =
352
      DenseMap<Instruction *, SmallPtrSet<Instruction *, 4>>;
353
  ReverseDepMapType ReverseLocalDeps;
354
355
  // A reverse mapping from dependencies to the non-local dependees.
356
  ReverseDepMapType ReverseNonLocalDeps;
357
358
  /// Current AA implementation, just a cache.
359
  AliasAnalysis &AA;
360
  AssumptionCache &AC;
361
  const TargetLibraryInfo &TLI;
362
  DominatorTree &DT;
363
  PredIteratorCache PredCache;
364
365
public:
366
  MemoryDependenceResults(AliasAnalysis &AA, AssumptionCache &AC,
367
                          const TargetLibraryInfo &TLI,
368
                          DominatorTree &DT)
369
1.31M
      : AA(AA), AC(AC), TLI(TLI), DT(DT) {}
370
371
  /// Handle invalidation in the new PM.
372
  bool invalidate(Function &F, const PreservedAnalyses &PA,
373
                  FunctionAnalysisManager::Invalidator &Inv);
374
375
  /// Some methods limit the number of instructions they will examine.
376
  /// The return value of this method is the default limit that will be
377
  /// used if no limit is explicitly passed in.
378
  unsigned getDefaultBlockScanLimit() const;
379
380
  /// Returns the instruction on which a memory operation depends.
381
  ///
382
  /// See the class comment for more details. It is illegal to call this on
383
  /// non-memory instructions.
384
  MemDepResult getDependency(Instruction *QueryInst);
385
386
  /// Perform a full dependency query for the specified call, returning the set
387
  /// of blocks that the value is potentially live across.
388
  ///
389
  /// The returned set of results will include a "NonLocal" result for all
390
  /// blocks where the value is live across.
391
  ///
392
  /// This method assumes the instruction returns a "NonLocal" dependency
393
  /// within its own block.
394
  ///
395
  /// This returns a reference to an internal data structure that may be
396
  /// invalidated on the next non-local query or when an instruction is
397
  /// removed.  Clients must copy this data if they want it around longer than
398
  /// that.
399
  const NonLocalDepInfo &getNonLocalCallDependency(CallSite QueryCS);
400
401
  /// Perform a full dependency query for an access to the QueryInst's
402
  /// specified memory location, returning the set of instructions that either
403
  /// define or clobber the value.
404
  ///
405
  /// Warning: For a volatile query instruction, the dependencies will be
406
  /// accurate, and thus usable for reordering, but it is never legal to
407
  /// remove the query instruction.
408
  ///
409
  /// This method assumes the pointer has a "NonLocal" dependency within
410
  /// QueryInst's parent basic block.
411
  void getNonLocalPointerDependency(Instruction *QueryInst,
412
                                    SmallVectorImpl<NonLocalDepResult> &Result);
413
414
  /// Removes an instruction from the dependence analysis, updating the
415
  /// dependence of instructions that previously depended on it.
416
  void removeInstruction(Instruction *InstToRemove);
417
418
  /// Invalidates cached information about the specified pointer, because it
419
  /// may be too conservative in memdep.
420
  ///
421
  /// This is an optional call that can be used when the client detects an
422
  /// equivalence between the pointer and some other value and replaces the
423
  /// other value with ptr. This can make Ptr available in more places that
424
  /// cached info does not necessarily keep.
425
  void invalidateCachedPointerInfo(Value *Ptr);
426
427
  /// Clears the PredIteratorCache info.
428
  ///
429
  /// This needs to be done when the CFG changes, e.g., due to splitting
430
  /// critical edges.
431
  void invalidateCachedPredecessors();
432
433
  /// Returns the instruction on which a memory location depends.
434
  ///
435
  /// If isLoad is true, this routine ignores may-aliases with read-only
436
  /// operations.  If isLoad is false, this routine ignores may-aliases
437
  /// with reads from read-only locations. If possible, pass the query
438
  /// instruction as well; this function may take advantage of the metadata
439
  /// annotated to the query instruction to refine the result. \p Limit
440
  /// can be used to set the maximum number of instructions that will be
441
  /// examined to find the pointer dependency. On return, it will be set to
442
  /// the number of instructions left to examine. If a null pointer is passed
443
  /// in, the limit will default to the value of -memdep-block-scan-limit.
444
  ///
445
  /// Note that this is an uncached query, and thus may be inefficient.
446
  MemDepResult getPointerDependencyFrom(const MemoryLocation &Loc, bool isLoad,
447
                                        BasicBlock::iterator ScanIt,
448
                                        BasicBlock *BB,
449
                                        Instruction *QueryInst = nullptr,
450
                                        unsigned *Limit = nullptr);
451
452
  MemDepResult getSimplePointerDependencyFrom(const MemoryLocation &MemLoc,
453
                                              bool isLoad,
454
                                              BasicBlock::iterator ScanIt,
455
                                              BasicBlock *BB,
456
                                              Instruction *QueryInst,
457
                                              unsigned *Limit = nullptr);
458
459
  /// This analysis looks for other loads and stores with invariant.group
460
  /// metadata and the same pointer operand. Returns Unknown if it does not
461
  /// find anything, and Def if it can be assumed that 2 instructions load or
462
  /// store the same value and NonLocal which indicate that non-local Def was
463
  /// found, which can be retrieved by calling getNonLocalPointerDependency
464
  /// with the same queried instruction.
465
  MemDepResult getInvariantGroupPointerDependency(LoadInst *LI, BasicBlock *BB);
466
467
  /// Looks at a memory location for a load (specified by MemLocBase, Offs, and
468
  /// Size) and compares it against a load.
469
  ///
470
  /// If the specified load could be safely widened to a larger integer load
471
  /// that is 1) still efficient, 2) safe for the target, and 3) would provide
472
  /// the specified memory location value, then this function returns the size
473
  /// in bytes of the load width to use.  If not, this returns zero.
474
  static unsigned getLoadLoadClobberFullWidthSize(const Value *MemLocBase,
475
                                                  int64_t MemLocOffs,
476
                                                  unsigned MemLocSize,
477
                                                  const LoadInst *LI);
478
479
  /// Release memory in caches.
480
  void releaseMemory();
481
482
private:
483
  MemDepResult getCallSiteDependencyFrom(CallSite C, bool isReadOnlyCall,
484
                                         BasicBlock::iterator ScanIt,
485
                                         BasicBlock *BB);
486
  bool getNonLocalPointerDepFromBB(Instruction *QueryInst,
487
                                   const PHITransAddr &Pointer,
488
                                   const MemoryLocation &Loc, bool isLoad,
489
                                   BasicBlock *BB,
490
                                   SmallVectorImpl<NonLocalDepResult> &Result,
491
                                   DenseMap<BasicBlock *, Value *> &Visited,
492
                                   bool SkipFirstBlock = false);
493
  MemDepResult GetNonLocalInfoForBlock(Instruction *QueryInst,
494
                                       const MemoryLocation &Loc, bool isLoad,
495
                                       BasicBlock *BB, NonLocalDepInfo *Cache,
496
                                       unsigned NumSortedEntries);
497
498
  void RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair P);
499
500
  void verifyRemoved(Instruction *Inst) const;
501
};
502
503
/// An analysis that produces \c MemoryDependenceResults for a function.
504
///
505
/// This is essentially a no-op because the results are computed entirely
506
/// lazily.
507
class MemoryDependenceAnalysis
508
    : public AnalysisInfoMixin<MemoryDependenceAnalysis> {
509
  friend AnalysisInfoMixin<MemoryDependenceAnalysis>;
510
511
  static AnalysisKey Key;
512
513
public:
514
  using Result = MemoryDependenceResults;
515
516
  MemoryDependenceResults run(Function &F, FunctionAnalysisManager &AM);
517
};
518
519
/// A wrapper analysis pass for the legacy pass manager that exposes a \c
520
/// MemoryDepnedenceResults instance.
521
class MemoryDependenceWrapperPass : public FunctionPass {
522
  Optional<MemoryDependenceResults> MemDep;
523
524
public:
525
  static char ID;
526
527
  MemoryDependenceWrapperPass();
528
  ~MemoryDependenceWrapperPass() override;
529
530
  /// Pass Implementation stuff.  This doesn't do any analysis eagerly.
531
  bool runOnFunction(Function &) override;
532
533
  /// Clean up memory in between runs
534
  void releaseMemory() override;
535
536
  /// Does not modify anything.  It uses Value Numbering and Alias Analysis.
537
  void getAnalysisUsage(AnalysisUsage &AU) const override;
538
539
1.31M
  MemoryDependenceResults &getMemDep() { return *MemDep; }
540
};
541
542
} // end namespace llvm
543
544
#endif // LLVM_ANALYSIS_MEMORYDEPENDENCEANALYSIS_H