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/Pass.h"
29 #include "llvm/BasicBlock.h"
30 #include "llvm/Function.h"
31 #include "llvm/IntrinsicInst.h"
32 #include "llvm/Instructions.h"
33 #include "llvm/LLVMContext.h"
34 #include "llvm/Type.h"
35 #include "llvm/Target/TargetData.h"
36 using namespace llvm;
37
38 // Register the AliasAnalysis interface, providing a nice name to refer to.
39 INITIALIZE_ANALYSIS_GROUP(AliasAnalysis, "Alias Analysis", NoAA)
40 char AliasAnalysis::ID = 0;
41
42 //===----------------------------------------------------------------------===//
43 // Default chaining methods
44 //===----------------------------------------------------------------------===//
45
46 AliasAnalysis::AliasResult
alias(const Location & LocA,const Location & LocB)47 AliasAnalysis::alias(const Location &LocA, const Location &LocB) {
48 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
49 return AA->alias(LocA, LocB);
50 }
51
pointsToConstantMemory(const Location & Loc,bool OrLocal)52 bool AliasAnalysis::pointsToConstantMemory(const Location &Loc,
53 bool OrLocal) {
54 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
55 return AA->pointsToConstantMemory(Loc, OrLocal);
56 }
57
deleteValue(Value * V)58 void AliasAnalysis::deleteValue(Value *V) {
59 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
60 AA->deleteValue(V);
61 }
62
copyValue(Value * From,Value * To)63 void AliasAnalysis::copyValue(Value *From, Value *To) {
64 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
65 AA->copyValue(From, To);
66 }
67
addEscapingUse(Use & U)68 void AliasAnalysis::addEscapingUse(Use &U) {
69 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
70 AA->addEscapingUse(U);
71 }
72
73
74 AliasAnalysis::ModRefResult
getModRefInfo(ImmutableCallSite CS,const Location & Loc)75 AliasAnalysis::getModRefInfo(ImmutableCallSite CS,
76 const Location &Loc) {
77 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
78
79 ModRefBehavior MRB = getModRefBehavior(CS);
80 if (MRB == DoesNotAccessMemory)
81 return NoModRef;
82
83 ModRefResult Mask = ModRef;
84 if (onlyReadsMemory(MRB))
85 Mask = Ref;
86
87 if (onlyAccessesArgPointees(MRB)) {
88 bool doesAlias = false;
89 if (doesAccessArgPointees(MRB)) {
90 MDNode *CSTag = CS.getInstruction()->getMetadata(LLVMContext::MD_tbaa);
91 for (ImmutableCallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
92 AI != AE; ++AI) {
93 const Value *Arg = *AI;
94 if (!Arg->getType()->isPointerTy())
95 continue;
96 Location CSLoc(Arg, UnknownSize, CSTag);
97 if (!isNoAlias(CSLoc, Loc)) {
98 doesAlias = true;
99 break;
100 }
101 }
102 }
103 if (!doesAlias)
104 return NoModRef;
105 }
106
107 // If Loc is a constant memory location, the call definitely could not
108 // modify the memory location.
109 if ((Mask & Mod) && pointsToConstantMemory(Loc))
110 Mask = ModRefResult(Mask & ~Mod);
111
112 // If this is the end of the chain, don't forward.
113 if (!AA) return Mask;
114
115 // Otherwise, fall back to the next AA in the chain. But we can merge
116 // in any mask we've managed to compute.
117 return ModRefResult(AA->getModRefInfo(CS, Loc) & Mask);
118 }
119
120 AliasAnalysis::ModRefResult
getModRefInfo(ImmutableCallSite CS1,ImmutableCallSite CS2)121 AliasAnalysis::getModRefInfo(ImmutableCallSite CS1, ImmutableCallSite CS2) {
122 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
123
124 // If CS1 or CS2 are readnone, they don't interact.
125 ModRefBehavior CS1B = getModRefBehavior(CS1);
126 if (CS1B == DoesNotAccessMemory) return NoModRef;
127
128 ModRefBehavior CS2B = getModRefBehavior(CS2);
129 if (CS2B == DoesNotAccessMemory) return NoModRef;
130
131 // If they both only read from memory, there is no dependence.
132 if (onlyReadsMemory(CS1B) && onlyReadsMemory(CS2B))
133 return NoModRef;
134
135 AliasAnalysis::ModRefResult Mask = ModRef;
136
137 // If CS1 only reads memory, the only dependence on CS2 can be
138 // from CS1 reading memory written by CS2.
139 if (onlyReadsMemory(CS1B))
140 Mask = ModRefResult(Mask & Ref);
141
142 // If CS2 only access memory through arguments, accumulate the mod/ref
143 // information from CS1's references to the memory referenced by
144 // CS2's arguments.
145 if (onlyAccessesArgPointees(CS2B)) {
146 AliasAnalysis::ModRefResult R = NoModRef;
147 if (doesAccessArgPointees(CS2B)) {
148 MDNode *CS2Tag = CS2.getInstruction()->getMetadata(LLVMContext::MD_tbaa);
149 for (ImmutableCallSite::arg_iterator
150 I = CS2.arg_begin(), E = CS2.arg_end(); I != E; ++I) {
151 const Value *Arg = *I;
152 if (!Arg->getType()->isPointerTy())
153 continue;
154 Location CS2Loc(Arg, UnknownSize, CS2Tag);
155 R = ModRefResult((R | getModRefInfo(CS1, CS2Loc)) & Mask);
156 if (R == Mask)
157 break;
158 }
159 }
160 return R;
161 }
162
163 // If CS1 only accesses memory through arguments, check if CS2 references
164 // any of the memory referenced by CS1's arguments. If not, return NoModRef.
165 if (onlyAccessesArgPointees(CS1B)) {
166 AliasAnalysis::ModRefResult R = NoModRef;
167 if (doesAccessArgPointees(CS1B)) {
168 MDNode *CS1Tag = CS1.getInstruction()->getMetadata(LLVMContext::MD_tbaa);
169 for (ImmutableCallSite::arg_iterator
170 I = CS1.arg_begin(), E = CS1.arg_end(); I != E; ++I) {
171 const Value *Arg = *I;
172 if (!Arg->getType()->isPointerTy())
173 continue;
174 Location CS1Loc(Arg, UnknownSize, CS1Tag);
175 if (getModRefInfo(CS2, CS1Loc) != NoModRef) {
176 R = Mask;
177 break;
178 }
179 }
180 }
181 if (R == NoModRef)
182 return R;
183 }
184
185 // If this is the end of the chain, don't forward.
186 if (!AA) return Mask;
187
188 // Otherwise, fall back to the next AA in the chain. But we can merge
189 // in any mask we've managed to compute.
190 return ModRefResult(AA->getModRefInfo(CS1, CS2) & Mask);
191 }
192
193 AliasAnalysis::ModRefBehavior
getModRefBehavior(ImmutableCallSite CS)194 AliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
195 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
196
197 ModRefBehavior Min = UnknownModRefBehavior;
198
199 // Call back into the alias analysis with the other form of getModRefBehavior
200 // to see if it can give a better response.
201 if (const Function *F = CS.getCalledFunction())
202 Min = getModRefBehavior(F);
203
204 // If this is the end of the chain, don't forward.
205 if (!AA) return Min;
206
207 // Otherwise, fall back to the next AA in the chain. But we can merge
208 // in any result we've managed to compute.
209 return ModRefBehavior(AA->getModRefBehavior(CS) & Min);
210 }
211
212 AliasAnalysis::ModRefBehavior
getModRefBehavior(const Function * F)213 AliasAnalysis::getModRefBehavior(const Function *F) {
214 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
215 return AA->getModRefBehavior(F);
216 }
217
218 //===----------------------------------------------------------------------===//
219 // AliasAnalysis non-virtual helper method implementation
220 //===----------------------------------------------------------------------===//
221
getLocation(const LoadInst * LI)222 AliasAnalysis::Location AliasAnalysis::getLocation(const LoadInst *LI) {
223 return Location(LI->getPointerOperand(),
224 getTypeStoreSize(LI->getType()),
225 LI->getMetadata(LLVMContext::MD_tbaa));
226 }
227
getLocation(const StoreInst * SI)228 AliasAnalysis::Location AliasAnalysis::getLocation(const StoreInst *SI) {
229 return Location(SI->getPointerOperand(),
230 getTypeStoreSize(SI->getValueOperand()->getType()),
231 SI->getMetadata(LLVMContext::MD_tbaa));
232 }
233
getLocation(const VAArgInst * VI)234 AliasAnalysis::Location AliasAnalysis::getLocation(const VAArgInst *VI) {
235 return Location(VI->getPointerOperand(),
236 UnknownSize,
237 VI->getMetadata(LLVMContext::MD_tbaa));
238 }
239
240
241 AliasAnalysis::Location
getLocationForSource(const MemTransferInst * MTI)242 AliasAnalysis::getLocationForSource(const MemTransferInst *MTI) {
243 uint64_t Size = UnknownSize;
244 if (ConstantInt *C = dyn_cast<ConstantInt>(MTI->getLength()))
245 Size = C->getValue().getZExtValue();
246
247 // memcpy/memmove can have TBAA tags. For memcpy, they apply
248 // to both the source and the destination.
249 MDNode *TBAATag = MTI->getMetadata(LLVMContext::MD_tbaa);
250
251 return Location(MTI->getRawSource(), Size, TBAATag);
252 }
253
254 AliasAnalysis::Location
getLocationForDest(const MemIntrinsic * MTI)255 AliasAnalysis::getLocationForDest(const MemIntrinsic *MTI) {
256 uint64_t Size = UnknownSize;
257 if (ConstantInt *C = dyn_cast<ConstantInt>(MTI->getLength()))
258 Size = C->getValue().getZExtValue();
259
260 // memcpy/memmove can have TBAA tags. For memcpy, they apply
261 // to both the source and the destination.
262 MDNode *TBAATag = MTI->getMetadata(LLVMContext::MD_tbaa);
263
264 return Location(MTI->getRawDest(), Size, TBAATag);
265 }
266
267
268
269 AliasAnalysis::ModRefResult
getModRefInfo(const LoadInst * L,const Location & Loc)270 AliasAnalysis::getModRefInfo(const LoadInst *L, const Location &Loc) {
271 // Be conservative in the face of volatile.
272 if (L->isVolatile())
273 return ModRef;
274
275 // If the load address doesn't alias the given address, it doesn't read
276 // or write the specified memory.
277 if (!alias(getLocation(L), Loc))
278 return NoModRef;
279
280 // Otherwise, a load just reads.
281 return Ref;
282 }
283
284 AliasAnalysis::ModRefResult
getModRefInfo(const StoreInst * S,const Location & Loc)285 AliasAnalysis::getModRefInfo(const StoreInst *S, const Location &Loc) {
286 // Be conservative in the face of volatile.
287 if (S->isVolatile())
288 return ModRef;
289
290 // If the store address cannot alias the pointer in question, then the
291 // specified memory cannot be modified by the store.
292 if (!alias(getLocation(S), Loc))
293 return NoModRef;
294
295 // If the pointer is a pointer to constant memory, then it could not have been
296 // modified by this store.
297 if (pointsToConstantMemory(Loc))
298 return NoModRef;
299
300 // Otherwise, a store just writes.
301 return Mod;
302 }
303
304 AliasAnalysis::ModRefResult
getModRefInfo(const VAArgInst * V,const Location & Loc)305 AliasAnalysis::getModRefInfo(const VAArgInst *V, const Location &Loc) {
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(getLocation(V), Loc))
309 return NoModRef;
310
311 // If the pointer is a pointer to constant memory, then it could not have been
312 // modified by this va_arg.
313 if (pointsToConstantMemory(Loc))
314 return NoModRef;
315
316 // Otherwise, a va_arg reads and writes.
317 return ModRef;
318 }
319
320 // AliasAnalysis destructor: DO NOT move this to the header file for
321 // AliasAnalysis or else clients of the AliasAnalysis class may not depend on
322 // the AliasAnalysis.o file in the current .a file, causing alias analysis
323 // support to not be included in the tool correctly!
324 //
~AliasAnalysis()325 AliasAnalysis::~AliasAnalysis() {}
326
327 /// InitializeAliasAnalysis - Subclasses must call this method to initialize the
328 /// AliasAnalysis interface before any other methods are called.
329 ///
InitializeAliasAnalysis(Pass * P)330 void AliasAnalysis::InitializeAliasAnalysis(Pass *P) {
331 TD = P->getAnalysisIfAvailable<TargetData>();
332 AA = &P->getAnalysis<AliasAnalysis>();
333 }
334
335 // getAnalysisUsage - All alias analysis implementations should invoke this
336 // directly (using AliasAnalysis::getAnalysisUsage(AU)).
getAnalysisUsage(AnalysisUsage & AU) const337 void AliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
338 AU.addRequired<AliasAnalysis>(); // All AA's chain
339 }
340
341 /// getTypeStoreSize - Return the TargetData store size for the given type,
342 /// if known, or a conservative value otherwise.
343 ///
getTypeStoreSize(Type * Ty)344 uint64_t AliasAnalysis::getTypeStoreSize(Type *Ty) {
345 return TD ? TD->getTypeStoreSize(Ty) : UnknownSize;
346 }
347
348 /// canBasicBlockModify - Return true if it is possible for execution of the
349 /// specified basic block to modify the value pointed to by Ptr.
350 ///
canBasicBlockModify(const BasicBlock & BB,const Location & Loc)351 bool AliasAnalysis::canBasicBlockModify(const BasicBlock &BB,
352 const Location &Loc) {
353 return canInstructionRangeModify(BB.front(), BB.back(), Loc);
354 }
355
356 /// canInstructionRangeModify - Return true if it is possible for the execution
357 /// of the specified instructions to modify the value pointed to by Ptr. The
358 /// instructions to consider are all of the instructions in the range of [I1,I2]
359 /// INCLUSIVE. I1 and I2 must be in the same basic block.
360 ///
canInstructionRangeModify(const Instruction & I1,const Instruction & I2,const Location & Loc)361 bool AliasAnalysis::canInstructionRangeModify(const Instruction &I1,
362 const Instruction &I2,
363 const Location &Loc) {
364 assert(I1.getParent() == I2.getParent() &&
365 "Instructions not in same basic block!");
366 BasicBlock::const_iterator I = &I1;
367 BasicBlock::const_iterator E = &I2;
368 ++E; // Convert from inclusive to exclusive range.
369
370 for (; I != E; ++I) // Check every instruction in range
371 if (getModRefInfo(I, Loc) & Mod)
372 return true;
373 return false;
374 }
375
376 /// isNoAliasCall - Return true if this pointer is returned by a noalias
377 /// function.
isNoAliasCall(const Value * V)378 bool llvm::isNoAliasCall(const Value *V) {
379 if (isa<CallInst>(V) || isa<InvokeInst>(V))
380 return ImmutableCallSite(cast<Instruction>(V))
381 .paramHasAttr(0, Attribute::NoAlias);
382 return false;
383 }
384
385 /// isIdentifiedObject - Return true if this pointer refers to a distinct and
386 /// identifiable object. This returns true for:
387 /// Global Variables and Functions (but not Global Aliases)
388 /// Allocas and Mallocs
389 /// ByVal and NoAlias Arguments
390 /// NoAlias returns
391 ///
isIdentifiedObject(const Value * V)392 bool llvm::isIdentifiedObject(const Value *V) {
393 if (isa<AllocaInst>(V))
394 return true;
395 if (isa<GlobalValue>(V) && !isa<GlobalAlias>(V))
396 return true;
397 if (isNoAliasCall(V))
398 return true;
399 if (const Argument *A = dyn_cast<Argument>(V))
400 return A->hasNoAliasAttr() || A->hasByValAttr();
401 return false;
402 }
403