[PM/AA] Completely remove the AliasAnalysis::copyValue interface.
[oota-llvm.git] / lib / Analysis / AliasAnalysis.cpp
1 //===- AliasAnalysis.cpp - Generic Alias Analysis Interface Implementation -==//
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 implements the generic AliasAnalysis interface which is used as the
11 // common interface used by all clients and implementations of alias analysis.
12 //
13 // This file also implements the default version of the AliasAnalysis interface
14 // that is to be used when no other implementation is specified.  This does some
15 // simple tests that detect obvious cases: two different global pointers cannot
16 // alias, a global cannot alias a malloc, two different mallocs cannot alias,
17 // etc.
18 //
19 // This alias analysis implementation really isn't very good for anything, but
20 // it is very fast, and makes a nice clean default implementation.  Because it
21 // handles lots of little corner cases, other, more complex, alias analysis
22 // implementations may choose to rely on this pass to resolve these simple and
23 // easy cases.
24 //
25 //===----------------------------------------------------------------------===//
26
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/Analysis/CFG.h"
29 #include "llvm/Analysis/CaptureTracking.h"
30 #include "llvm/Analysis/TargetLibraryInfo.h"
31 #include "llvm/Analysis/ValueTracking.h"
32 #include "llvm/IR/BasicBlock.h"
33 #include "llvm/IR/DataLayout.h"
34 #include "llvm/IR/Dominators.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/Instructions.h"
37 #include "llvm/IR/IntrinsicInst.h"
38 #include "llvm/IR/LLVMContext.h"
39 #include "llvm/IR/Type.h"
40 #include "llvm/Pass.h"
41 using namespace llvm;
42
43 // Register the AliasAnalysis interface, providing a nice name to refer to.
44 INITIALIZE_ANALYSIS_GROUP(AliasAnalysis, "Alias Analysis", NoAA)
45 char AliasAnalysis::ID = 0;
46
47 //===----------------------------------------------------------------------===//
48 // Default chaining methods
49 //===----------------------------------------------------------------------===//
50
51 AliasResult AliasAnalysis::alias(const MemoryLocation &LocA,
52                                  const MemoryLocation &LocB) {
53   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
54   return AA->alias(LocA, LocB);
55 }
56
57 bool AliasAnalysis::pointsToConstantMemory(const MemoryLocation &Loc,
58                                            bool OrLocal) {
59   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
60   return AA->pointsToConstantMemory(Loc, OrLocal);
61 }
62
63 AliasAnalysis::ModRefResult
64 AliasAnalysis::getArgModRefInfo(ImmutableCallSite CS, unsigned ArgIdx) {
65   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
66   return AA->getArgModRefInfo(CS, ArgIdx);
67 }
68
69 void AliasAnalysis::deleteValue(Value *V) {
70   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
71   AA->deleteValue(V);
72 }
73
74 void AliasAnalysis::addEscapingUse(Use &U) {
75   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
76   AA->addEscapingUse(U);
77 }
78
79 AliasAnalysis::ModRefResult
80 AliasAnalysis::getModRefInfo(Instruction *I, ImmutableCallSite Call) {
81   // We may have two calls
82   if (auto CS = ImmutableCallSite(I)) {
83     // Check if the two calls modify the same memory
84     return getModRefInfo(Call, CS);
85   } else {
86     // Otherwise, check if the call modifies or references the
87     // location this memory access defines.  The best we can say
88     // is that if the call references what this instruction
89     // defines, it must be clobbered by this location.
90     const MemoryLocation DefLoc = MemoryLocation::get(I);
91     if (getModRefInfo(Call, DefLoc) != AliasAnalysis::NoModRef)
92       return AliasAnalysis::ModRef;
93   }
94   return AliasAnalysis::NoModRef;
95 }
96
97 AliasAnalysis::ModRefResult
98 AliasAnalysis::getModRefInfo(ImmutableCallSite CS, const MemoryLocation &Loc) {
99   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
100
101   ModRefBehavior MRB = getModRefBehavior(CS);
102   if (MRB == DoesNotAccessMemory)
103     return NoModRef;
104
105   ModRefResult Mask = ModRef;
106   if (onlyReadsMemory(MRB))
107     Mask = Ref;
108
109   if (onlyAccessesArgPointees(MRB)) {
110     bool doesAlias = false;
111     ModRefResult AllArgsMask = NoModRef;
112     if (doesAccessArgPointees(MRB)) {
113       for (ImmutableCallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
114            AI != AE; ++AI) {
115         const Value *Arg = *AI;
116         if (!Arg->getType()->isPointerTy())
117           continue;
118         unsigned ArgIdx = std::distance(CS.arg_begin(), AI);
119         MemoryLocation ArgLoc =
120             MemoryLocation::getForArgument(CS, ArgIdx, *TLI);
121         if (!isNoAlias(ArgLoc, Loc)) {
122           ModRefResult ArgMask = getArgModRefInfo(CS, ArgIdx);
123           doesAlias = true;
124           AllArgsMask = ModRefResult(AllArgsMask | ArgMask);
125         }
126       }
127     }
128     if (!doesAlias)
129       return NoModRef;
130     Mask = ModRefResult(Mask & AllArgsMask);
131   }
132
133   // If Loc is a constant memory location, the call definitely could not
134   // modify the memory location.
135   if ((Mask & Mod) && pointsToConstantMemory(Loc))
136     Mask = ModRefResult(Mask & ~Mod);
137
138   // If this is the end of the chain, don't forward.
139   if (!AA) return Mask;
140
141   // Otherwise, fall back to the next AA in the chain. But we can merge
142   // in any mask we've managed to compute.
143   return ModRefResult(AA->getModRefInfo(CS, Loc) & Mask);
144 }
145
146 AliasAnalysis::ModRefResult
147 AliasAnalysis::getModRefInfo(ImmutableCallSite CS1, ImmutableCallSite CS2) {
148   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
149
150   // If CS1 or CS2 are readnone, they don't interact.
151   ModRefBehavior CS1B = getModRefBehavior(CS1);
152   if (CS1B == DoesNotAccessMemory) return NoModRef;
153
154   ModRefBehavior CS2B = getModRefBehavior(CS2);
155   if (CS2B == DoesNotAccessMemory) return NoModRef;
156
157   // If they both only read from memory, there is no dependence.
158   if (onlyReadsMemory(CS1B) && onlyReadsMemory(CS2B))
159     return NoModRef;
160
161   AliasAnalysis::ModRefResult Mask = ModRef;
162
163   // If CS1 only reads memory, the only dependence on CS2 can be
164   // from CS1 reading memory written by CS2.
165   if (onlyReadsMemory(CS1B))
166     Mask = ModRefResult(Mask & Ref);
167
168   // If CS2 only access memory through arguments, accumulate the mod/ref
169   // information from CS1's references to the memory referenced by
170   // CS2's arguments.
171   if (onlyAccessesArgPointees(CS2B)) {
172     AliasAnalysis::ModRefResult R = NoModRef;
173     if (doesAccessArgPointees(CS2B)) {
174       for (ImmutableCallSite::arg_iterator
175            I = CS2.arg_begin(), E = CS2.arg_end(); I != E; ++I) {
176         const Value *Arg = *I;
177         if (!Arg->getType()->isPointerTy())
178           continue;
179         unsigned CS2ArgIdx = std::distance(CS2.arg_begin(), I);
180         auto CS2ArgLoc = MemoryLocation::getForArgument(CS2, CS2ArgIdx, *TLI);
181
182         // ArgMask indicates what CS2 might do to CS2ArgLoc, and the dependence of
183         // CS1 on that location is the inverse.
184         ModRefResult ArgMask = getArgModRefInfo(CS2, CS2ArgIdx);
185         if (ArgMask == Mod)
186           ArgMask = ModRef;
187         else if (ArgMask == Ref)
188           ArgMask = Mod;
189
190         R = ModRefResult((R | (getModRefInfo(CS1, CS2ArgLoc) & ArgMask)) & Mask);
191         if (R == Mask)
192           break;
193       }
194     }
195     return R;
196   }
197
198   // If CS1 only accesses memory through arguments, check if CS2 references
199   // any of the memory referenced by CS1's arguments. If not, return NoModRef.
200   if (onlyAccessesArgPointees(CS1B)) {
201     AliasAnalysis::ModRefResult R = NoModRef;
202     if (doesAccessArgPointees(CS1B)) {
203       for (ImmutableCallSite::arg_iterator
204            I = CS1.arg_begin(), E = CS1.arg_end(); I != E; ++I) {
205         const Value *Arg = *I;
206         if (!Arg->getType()->isPointerTy())
207           continue;
208         unsigned CS1ArgIdx = std::distance(CS1.arg_begin(), I);
209         auto CS1ArgLoc = MemoryLocation::getForArgument(CS1, CS1ArgIdx, *TLI);
210
211         // ArgMask indicates what CS1 might do to CS1ArgLoc; if CS1 might Mod
212         // CS1ArgLoc, then we care about either a Mod or a Ref by CS2. If CS1
213         // might Ref, then we care only about a Mod by CS2.
214         ModRefResult ArgMask = getArgModRefInfo(CS1, CS1ArgIdx);
215         ModRefResult ArgR = getModRefInfo(CS2, CS1ArgLoc);
216         if (((ArgMask & Mod) != NoModRef && (ArgR & ModRef) != NoModRef) ||
217             ((ArgMask & Ref) != NoModRef && (ArgR & Mod)    != NoModRef))
218           R = ModRefResult((R | ArgMask) & Mask);
219
220         if (R == Mask)
221           break;
222       }
223     }
224     return R;
225   }
226
227   // If this is the end of the chain, don't forward.
228   if (!AA) return Mask;
229
230   // Otherwise, fall back to the next AA in the chain. But we can merge
231   // in any mask we've managed to compute.
232   return ModRefResult(AA->getModRefInfo(CS1, CS2) & Mask);
233 }
234
235 AliasAnalysis::ModRefBehavior
236 AliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
237   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
238
239   ModRefBehavior Min = UnknownModRefBehavior;
240
241   // Call back into the alias analysis with the other form of getModRefBehavior
242   // to see if it can give a better response.
243   if (const Function *F = CS.getCalledFunction())
244     Min = getModRefBehavior(F);
245
246   // If this is the end of the chain, don't forward.
247   if (!AA) return Min;
248
249   // Otherwise, fall back to the next AA in the chain. But we can merge
250   // in any result we've managed to compute.
251   return ModRefBehavior(AA->getModRefBehavior(CS) & Min);
252 }
253
254 AliasAnalysis::ModRefBehavior
255 AliasAnalysis::getModRefBehavior(const Function *F) {
256   assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
257   return AA->getModRefBehavior(F);
258 }
259
260 //===----------------------------------------------------------------------===//
261 // AliasAnalysis non-virtual helper method implementation
262 //===----------------------------------------------------------------------===//
263
264 AliasAnalysis::ModRefResult
265 AliasAnalysis::getModRefInfo(const LoadInst *L, const MemoryLocation &Loc) {
266   // Be conservative in the face of volatile/atomic.
267   if (!L->isUnordered())
268     return ModRef;
269
270   // If the load address doesn't alias the given address, it doesn't read
271   // or write the specified memory.
272   if (Loc.Ptr && !alias(MemoryLocation::get(L), Loc))
273     return NoModRef;
274
275   // Otherwise, a load just reads.
276   return Ref;
277 }
278
279 AliasAnalysis::ModRefResult
280 AliasAnalysis::getModRefInfo(const StoreInst *S, const MemoryLocation &Loc) {
281   // Be conservative in the face of volatile/atomic.
282   if (!S->isUnordered())
283     return ModRef;
284
285   if (Loc.Ptr) {
286     // If the store address cannot alias the pointer in question, then the
287     // specified memory cannot be modified by the store.
288     if (!alias(MemoryLocation::get(S), Loc))
289       return NoModRef;
290
291     // If the pointer is a pointer to constant memory, then it could not have
292     // been modified by this store.
293     if (pointsToConstantMemory(Loc))
294       return NoModRef;
295
296   }
297
298   // Otherwise, a store just writes.
299   return Mod;
300 }
301
302 AliasAnalysis::ModRefResult
303 AliasAnalysis::getModRefInfo(const VAArgInst *V, const MemoryLocation &Loc) {
304
305   if (Loc.Ptr) {
306     // If the va_arg address cannot alias the pointer in question, then the
307     // specified memory cannot be accessed by the va_arg.
308     if (!alias(MemoryLocation::get(V), Loc))
309       return NoModRef;
310
311     // If the pointer is a pointer to constant memory, then it could not have
312     // been modified by this va_arg.
313     if (pointsToConstantMemory(Loc))
314       return NoModRef;
315   }
316
317   // Otherwise, a va_arg reads and writes.
318   return ModRef;
319 }
320
321 AliasAnalysis::ModRefResult
322 AliasAnalysis::getModRefInfo(const AtomicCmpXchgInst *CX,
323                              const MemoryLocation &Loc) {
324   // Acquire/Release cmpxchg has properties that matter for arbitrary addresses.
325   if (CX->getSuccessOrdering() > Monotonic)
326     return ModRef;
327
328   // If the cmpxchg address does not alias the location, it does not access it.
329   if (Loc.Ptr && !alias(MemoryLocation::get(CX), Loc))
330     return NoModRef;
331
332   return ModRef;
333 }
334
335 AliasAnalysis::ModRefResult
336 AliasAnalysis::getModRefInfo(const AtomicRMWInst *RMW,
337                              const MemoryLocation &Loc) {
338   // Acquire/Release atomicrmw has properties that matter for arbitrary addresses.
339   if (RMW->getOrdering() > Monotonic)
340     return ModRef;
341
342   // If the atomicrmw address does not alias the location, it does not access it.
343   if (Loc.Ptr && !alias(MemoryLocation::get(RMW), Loc))
344     return NoModRef;
345
346   return ModRef;
347 }
348
349 // FIXME: this is really just shoring-up a deficiency in alias analysis.
350 // BasicAA isn't willing to spend linear time determining whether an alloca
351 // was captured before or after this particular call, while we are. However,
352 // with a smarter AA in place, this test is just wasting compile time.
353 AliasAnalysis::ModRefResult AliasAnalysis::callCapturesBefore(
354     const Instruction *I, const MemoryLocation &MemLoc, DominatorTree *DT) {
355   if (!DT)
356     return AliasAnalysis::ModRef;
357
358   const Value *Object = GetUnderlyingObject(MemLoc.Ptr, *DL);
359   if (!isIdentifiedObject(Object) || isa<GlobalValue>(Object) ||
360       isa<Constant>(Object))
361     return AliasAnalysis::ModRef;
362
363   ImmutableCallSite CS(I);
364   if (!CS.getInstruction() || CS.getInstruction() == Object)
365     return AliasAnalysis::ModRef;
366
367   if (llvm::PointerMayBeCapturedBefore(Object, /* ReturnCaptures */ true,
368                                        /* StoreCaptures */ true, I, DT,
369                                        /* include Object */ true))
370     return AliasAnalysis::ModRef;
371
372   unsigned ArgNo = 0;
373   AliasAnalysis::ModRefResult R = AliasAnalysis::NoModRef;
374   for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
375        CI != CE; ++CI, ++ArgNo) {
376     // Only look at the no-capture or byval pointer arguments.  If this
377     // pointer were passed to arguments that were neither of these, then it
378     // couldn't be no-capture.
379     if (!(*CI)->getType()->isPointerTy() ||
380         (!CS.doesNotCapture(ArgNo) && !CS.isByValArgument(ArgNo)))
381       continue;
382
383     // If this is a no-capture pointer argument, see if we can tell that it
384     // is impossible to alias the pointer we're checking.  If not, we have to
385     // assume that the call could touch the pointer, even though it doesn't
386     // escape.
387     if (isNoAlias(MemoryLocation(*CI), MemoryLocation(Object)))
388       continue;
389     if (CS.doesNotAccessMemory(ArgNo))
390       continue;
391     if (CS.onlyReadsMemory(ArgNo)) {
392       R = AliasAnalysis::Ref;
393       continue;
394     }
395     return AliasAnalysis::ModRef;
396   }
397   return R;
398 }
399
400 // AliasAnalysis destructor: DO NOT move this to the header file for
401 // AliasAnalysis or else clients of the AliasAnalysis class may not depend on
402 // the AliasAnalysis.o file in the current .a file, causing alias analysis
403 // support to not be included in the tool correctly!
404 //
405 AliasAnalysis::~AliasAnalysis() {}
406
407 /// InitializeAliasAnalysis - Subclasses must call this method to initialize the
408 /// AliasAnalysis interface before any other methods are called.
409 ///
410 void AliasAnalysis::InitializeAliasAnalysis(Pass *P, const DataLayout *NewDL) {
411   DL = NewDL;
412   auto *TLIP = P->getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
413   TLI = TLIP ? &TLIP->getTLI() : nullptr;
414   AA = &P->getAnalysis<AliasAnalysis>();
415 }
416
417 // getAnalysisUsage - All alias analysis implementations should invoke this
418 // directly (using AliasAnalysis::getAnalysisUsage(AU)).
419 void AliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
420   AU.addRequired<AliasAnalysis>();         // All AA's chain
421 }
422
423 /// getTypeStoreSize - Return the DataLayout store size for the given type,
424 /// if known, or a conservative value otherwise.
425 ///
426 uint64_t AliasAnalysis::getTypeStoreSize(Type *Ty) {
427   return DL ? DL->getTypeStoreSize(Ty) : MemoryLocation::UnknownSize;
428 }
429
430 /// canBasicBlockModify - Return true if it is possible for execution of the
431 /// specified basic block to modify the location Loc.
432 ///
433 bool AliasAnalysis::canBasicBlockModify(const BasicBlock &BB,
434                                         const MemoryLocation &Loc) {
435   return canInstructionRangeModRef(BB.front(), BB.back(), Loc, Mod);
436 }
437
438 /// canInstructionRangeModRef - Return true if it is possible for the
439 /// execution of the specified instructions to mod\ref (according to the
440 /// mode) the location Loc. The instructions to consider are all
441 /// of the instructions in the range of [I1,I2] INCLUSIVE.
442 /// I1 and I2 must be in the same basic block.
443 bool AliasAnalysis::canInstructionRangeModRef(const Instruction &I1,
444                                               const Instruction &I2,
445                                               const MemoryLocation &Loc,
446                                               const ModRefResult Mode) {
447   assert(I1.getParent() == I2.getParent() &&
448          "Instructions not in same basic block!");
449   BasicBlock::const_iterator I = &I1;
450   BasicBlock::const_iterator E = &I2;
451   ++E;  // Convert from inclusive to exclusive range.
452
453   for (; I != E; ++I) // Check every instruction in range
454     if (getModRefInfo(I, Loc) & Mode)
455       return true;
456   return false;
457 }
458
459 /// isNoAliasCall - Return true if this pointer is returned by a noalias
460 /// function.
461 bool llvm::isNoAliasCall(const Value *V) {
462   if (isa<CallInst>(V) || isa<InvokeInst>(V))
463     return ImmutableCallSite(cast<Instruction>(V))
464       .paramHasAttr(0, Attribute::NoAlias);
465   return false;
466 }
467
468 /// isNoAliasArgument - Return true if this is an argument with the noalias
469 /// attribute.
470 bool llvm::isNoAliasArgument(const Value *V)
471 {
472   if (const Argument *A = dyn_cast<Argument>(V))
473     return A->hasNoAliasAttr();
474   return false;
475 }
476
477 /// isIdentifiedObject - Return true if this pointer refers to a distinct and
478 /// identifiable object.  This returns true for:
479 ///    Global Variables and Functions (but not Global Aliases)
480 ///    Allocas and Mallocs
481 ///    ByVal and NoAlias Arguments
482 ///    NoAlias returns
483 ///
484 bool llvm::isIdentifiedObject(const Value *V) {
485   if (isa<AllocaInst>(V))
486     return true;
487   if (isa<GlobalValue>(V) && !isa<GlobalAlias>(V))
488     return true;
489   if (isNoAliasCall(V))
490     return true;
491   if (const Argument *A = dyn_cast<Argument>(V))
492     return A->hasNoAliasAttr() || A->hasByValAttr();
493   return false;
494 }
495
496 /// isIdentifiedFunctionLocal - Return true if V is umabigously identified
497 /// at the function-level. Different IdentifiedFunctionLocals can't alias.
498 /// Further, an IdentifiedFunctionLocal can not alias with any function
499 /// arguments other than itself, which is not necessarily true for
500 /// IdentifiedObjects.
501 bool llvm::isIdentifiedFunctionLocal(const Value *V)
502 {
503   return isa<AllocaInst>(V) || isNoAliasCall(V) || isNoAliasArgument(V);
504 }