Teach FunctionAttrs about AccessesArgumentsReadonly.
[oota-llvm.git] / lib / Transforms / IPO / FunctionAttrs.cpp
1 //===- FunctionAttrs.cpp - Pass which marks functions readnone or readonly ===//
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 a simple interprocedural pass which walks the
11 // call-graph, looking for functions which do not access or only read
12 // non-local memory, and marking them readnone/readonly.  In addition,
13 // it marks function arguments (of pointer type) 'nocapture' if a call
14 // to the function does not create any copies of the pointer value that
15 // outlive the call.  This more or less means that the pointer is only
16 // dereferenced, and not returned from the function or stored in a global.
17 // This pass is implemented as a bottom-up traversal of the call-graph.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #define DEBUG_TYPE "functionattrs"
22 #include "llvm/Transforms/IPO.h"
23 #include "llvm/CallGraphSCCPass.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/IntrinsicInst.h"
26 #include "llvm/LLVMContext.h"
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/Analysis/CallGraph.h"
29 #include "llvm/Analysis/CaptureTracking.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/UniqueVector.h"
33 #include "llvm/Support/InstIterator.h"
34 using namespace llvm;
35
36 STATISTIC(NumReadNone, "Number of functions marked readnone");
37 STATISTIC(NumReadOnly, "Number of functions marked readonly");
38 STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
39 STATISTIC(NumNoAlias, "Number of function returns marked noalias");
40
41 namespace {
42   struct FunctionAttrs : public CallGraphSCCPass {
43     static char ID; // Pass identification, replacement for typeid
44     FunctionAttrs() : CallGraphSCCPass(ID), AA(0) {
45       initializeFunctionAttrsPass(*PassRegistry::getPassRegistry());
46     }
47
48     // runOnSCC - Analyze the SCC, performing the transformation if possible.
49     bool runOnSCC(CallGraphSCC &SCC);
50
51     // AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
52     bool AddReadAttrs(const CallGraphSCC &SCC);
53
54     // AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
55     bool AddNoCaptureAttrs(const CallGraphSCC &SCC);
56
57     // IsFunctionMallocLike - Does this function allocate new memory?
58     bool IsFunctionMallocLike(Function *F,
59                               SmallPtrSet<Function*, 8> &) const;
60
61     // AddNoAliasAttrs - Deduce noalias attributes for the SCC.
62     bool AddNoAliasAttrs(const CallGraphSCC &SCC);
63
64     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
65       AU.setPreservesCFG();
66       AU.addRequired<AliasAnalysis>();
67       CallGraphSCCPass::getAnalysisUsage(AU);
68     }
69
70   private:
71     AliasAnalysis *AA;
72   };
73 }
74
75 char FunctionAttrs::ID = 0;
76 INITIALIZE_PASS_BEGIN(FunctionAttrs, "functionattrs",
77                 "Deduce function attributes", false, false)
78 INITIALIZE_AG_DEPENDENCY(CallGraph)
79 INITIALIZE_PASS_END(FunctionAttrs, "functionattrs",
80                 "Deduce function attributes", false, false)
81
82 Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
83
84
85 /// AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
86 bool FunctionAttrs::AddReadAttrs(const CallGraphSCC &SCC) {
87   SmallPtrSet<Function*, 8> SCCNodes;
88
89   // Fill SCCNodes with the elements of the SCC.  Used for quickly
90   // looking up whether a given CallGraphNode is in this SCC.
91   for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
92     SCCNodes.insert((*I)->getFunction());
93
94   // Check if any of the functions in the SCC read or write memory.  If they
95   // write memory then they can't be marked readnone or readonly.
96   bool ReadsMemory = false;
97   for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
98     Function *F = (*I)->getFunction();
99
100     if (F == 0)
101       // External node - may write memory.  Just give up.
102       return false;
103
104     if (F->doesNotAccessMemory())
105       // Already perfect!
106       continue;
107
108     // Definitions with weak linkage may be overridden at linktime with
109     // something that writes memory, so treat them like declarations.
110     if (F->isDeclaration() || F->mayBeOverridden()) {
111       if (!F->onlyReadsMemory())
112         // May write memory.  Just give up.
113         return false;
114
115       ReadsMemory = true;
116       continue;
117     }
118
119     // Scan the function body for instructions that may read or write memory.
120     for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
121       Instruction *I = &*II;
122
123       // Some instructions can be ignored even if they read or write memory.
124       // Detect these now, skipping to the next instruction if one is found.
125       CallSite CS(cast<Value>(I));
126       if (CS) {
127         // Ignore calls to functions in the same SCC.
128         if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
129           continue;
130         switch (AA->getModRefBehavior(CS)) {
131         case AliasAnalysis::DoesNotAccessMemory:
132           // Ignore calls that don't access memory.
133           continue;
134         case AliasAnalysis::OnlyReadsMemory:
135           // Handle calls that only read from memory.
136           ReadsMemory = true;
137           continue;
138         case AliasAnalysis::AccessesArguments:
139           // Check whether all pointer arguments point to local memory, and
140           // ignore calls that only access local memory.
141           for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
142                CI != CE; ++CI) {
143             Value *Arg = *CI;
144             if (Arg->getType()->isPointerTy()) {
145               AliasAnalysis::Location Loc(Arg,
146                                           AliasAnalysis::UnknownSize,
147                                           I->getMetadata(LLVMContext::MD_tbaa));
148               if (!AA->pointsToConstantMemory(Loc, /*OrLocal=*/true))
149                 // Writes memory.  Just give up.
150                 return false;
151             }
152           }
153           // Only reads and writes local memory.
154           continue;
155         case AliasAnalysis::AccessesArgumentsReadonly:
156           // Check whether all pointer arguments point to local memory, and
157           // ignore calls that only access local memory.
158           for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
159                CI != CE; ++CI) {
160             Value *Arg = *CI;
161             if (Arg->getType()->isPointerTy()) {
162               AliasAnalysis::Location Loc(Arg,
163                                           AliasAnalysis::UnknownSize,
164                                           I->getMetadata(LLVMContext::MD_tbaa));
165               if (!AA->pointsToConstantMemory(Loc, /*OrLocal=*/true)) {
166                 // Reads non-local memory.
167                 ReadsMemory = true;
168                 break;
169               }
170             }
171           }
172           // Only reads memory.
173           continue;
174         default:
175           // Otherwise, be conservative.
176           break;
177         }
178       } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
179         // Ignore non-volatile loads from local memory.
180         if (!LI->isVolatile()) {
181           AliasAnalysis::Location Loc(LI->getPointerOperand(),
182                                         AA->getTypeStoreSize(LI->getType()),
183                                         LI->getMetadata(LLVMContext::MD_tbaa));
184           if (AA->pointsToConstantMemory(Loc, /*OrLocal=*/true))
185             continue;
186         }
187       } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
188         // Ignore non-volatile stores to local memory.
189         if (!SI->isVolatile()) {
190           const Type *StoredType = SI->getValueOperand()->getType();
191           AliasAnalysis::Location Loc(SI->getPointerOperand(),
192                                       AA->getTypeStoreSize(StoredType),
193                                       SI->getMetadata(LLVMContext::MD_tbaa));
194           if (AA->pointsToConstantMemory(Loc, /*OrLocal=*/true))
195             continue;
196         }
197       }
198
199       // Any remaining instructions need to be taken seriously!  Check if they
200       // read or write memory.
201       if (I->mayWriteToMemory())
202         // Writes memory.  Just give up.
203         return false;
204
205       // If this instruction may read memory, remember that.
206       ReadsMemory |= I->mayReadFromMemory();
207     }
208   }
209
210   // Success!  Functions in this SCC do not access memory, or only read memory.
211   // Give them the appropriate attribute.
212   bool MadeChange = false;
213   for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
214     Function *F = (*I)->getFunction();
215
216     if (F->doesNotAccessMemory())
217       // Already perfect!
218       continue;
219
220     if (F->onlyReadsMemory() && ReadsMemory)
221       // No change.
222       continue;
223
224     MadeChange = true;
225
226     // Clear out any existing attributes.
227     F->removeAttribute(~0, Attribute::ReadOnly | Attribute::ReadNone);
228
229     // Add in the new attribute.
230     F->addAttribute(~0, ReadsMemory? Attribute::ReadOnly : Attribute::ReadNone);
231
232     if (ReadsMemory)
233       ++NumReadOnly;
234     else
235       ++NumReadNone;
236   }
237
238   return MadeChange;
239 }
240
241 /// AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
242 bool FunctionAttrs::AddNoCaptureAttrs(const CallGraphSCC &SCC) {
243   bool Changed = false;
244
245   // Check each function in turn, determining which pointer arguments are not
246   // captured.
247   for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
248     Function *F = (*I)->getFunction();
249
250     if (F == 0)
251       // External node - skip it;
252       continue;
253
254     // Definitions with weak linkage may be overridden at linktime with
255     // something that writes memory, so treat them like declarations.
256     if (F->isDeclaration() || F->mayBeOverridden())
257       continue;
258
259     for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A!=E; ++A)
260       if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr() &&
261           !PointerMayBeCaptured(A, true, /*StoreCaptures=*/false)) {
262         A->addAttr(Attribute::NoCapture);
263         ++NumNoCapture;
264         Changed = true;
265       }
266   }
267
268   return Changed;
269 }
270
271 /// IsFunctionMallocLike - A function is malloc-like if it returns either null
272 /// or a pointer that doesn't alias any other pointer visible to the caller.
273 bool FunctionAttrs::IsFunctionMallocLike(Function *F,
274                               SmallPtrSet<Function*, 8> &SCCNodes) const {
275   UniqueVector<Value *> FlowsToReturn;
276   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
277     if (ReturnInst *Ret = dyn_cast<ReturnInst>(I->getTerminator()))
278       FlowsToReturn.insert(Ret->getReturnValue());
279
280   for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
281     Value *RetVal = FlowsToReturn[i+1];   // UniqueVector[0] is reserved.
282
283     if (Constant *C = dyn_cast<Constant>(RetVal)) {
284       if (!C->isNullValue() && !isa<UndefValue>(C))
285         return false;
286
287       continue;
288     }
289
290     if (isa<Argument>(RetVal))
291       return false;
292
293     if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
294       switch (RVI->getOpcode()) {
295         // Extend the analysis by looking upwards.
296         case Instruction::BitCast:
297         case Instruction::GetElementPtr:
298           FlowsToReturn.insert(RVI->getOperand(0));
299           continue;
300         case Instruction::Select: {
301           SelectInst *SI = cast<SelectInst>(RVI);
302           FlowsToReturn.insert(SI->getTrueValue());
303           FlowsToReturn.insert(SI->getFalseValue());
304           continue;
305         }
306         case Instruction::PHI: {
307           PHINode *PN = cast<PHINode>(RVI);
308           for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
309             FlowsToReturn.insert(PN->getIncomingValue(i));
310           continue;
311         }
312
313         // Check whether the pointer came from an allocation.
314         case Instruction::Alloca:
315           break;
316         case Instruction::Call:
317         case Instruction::Invoke: {
318           CallSite CS(RVI);
319           if (CS.paramHasAttr(0, Attribute::NoAlias))
320             break;
321           if (CS.getCalledFunction() &&
322               SCCNodes.count(CS.getCalledFunction()))
323             break;
324         } // fall-through
325         default:
326           return false;  // Did not come from an allocation.
327       }
328
329     if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
330       return false;
331   }
332
333   return true;
334 }
335
336 /// AddNoAliasAttrs - Deduce noalias attributes for the SCC.
337 bool FunctionAttrs::AddNoAliasAttrs(const CallGraphSCC &SCC) {
338   SmallPtrSet<Function*, 8> SCCNodes;
339
340   // Fill SCCNodes with the elements of the SCC.  Used for quickly
341   // looking up whether a given CallGraphNode is in this SCC.
342   for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
343     SCCNodes.insert((*I)->getFunction());
344
345   // Check each function in turn, determining which functions return noalias
346   // pointers.
347   for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
348     Function *F = (*I)->getFunction();
349
350     if (F == 0)
351       // External node - skip it;
352       return false;
353
354     // Already noalias.
355     if (F->doesNotAlias(0))
356       continue;
357
358     // Definitions with weak linkage may be overridden at linktime, so
359     // treat them like declarations.
360     if (F->isDeclaration() || F->mayBeOverridden())
361       return false;
362
363     // We annotate noalias return values, which are only applicable to 
364     // pointer types.
365     if (!F->getReturnType()->isPointerTy())
366       continue;
367
368     if (!IsFunctionMallocLike(F, SCCNodes))
369       return false;
370   }
371
372   bool MadeChange = false;
373   for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
374     Function *F = (*I)->getFunction();
375     if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())
376       continue;
377
378     F->setDoesNotAlias(0);
379     ++NumNoAlias;
380     MadeChange = true;
381   }
382
383   return MadeChange;
384 }
385
386 bool FunctionAttrs::runOnSCC(CallGraphSCC &SCC) {
387   AA = &getAnalysis<AliasAnalysis>();
388
389   bool Changed = AddReadAttrs(SCC);
390   Changed |= AddNoCaptureAttrs(SCC);
391   Changed |= AddNoAliasAttrs(SCC);
392   return Changed;
393 }