Mention that this pass does escape analysis in the
[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.  It addition,
13 // it deduces which function arguments (of pointer type) do not escape,
14 // and marks them nocapture.  It implements this as a bottom-up traversal
15 // of the call-graph.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #define DEBUG_TYPE "functionattrs"
20 #include "llvm/Transforms/IPO.h"
21 #include "llvm/CallGraphSCCPass.h"
22 #include "llvm/GlobalVariable.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Analysis/CallGraph.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Support/Compiler.h"
28 #include "llvm/Support/InstIterator.h"
29 using namespace llvm;
30
31 STATISTIC(NumReadNone, "Number of functions marked readnone");
32 STATISTIC(NumReadOnly, "Number of functions marked readonly");
33 STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
34
35 namespace {
36   struct VISIBILITY_HIDDEN FunctionAttrs : public CallGraphSCCPass {
37     static char ID; // Pass identification, replacement for typeid
38     FunctionAttrs() : CallGraphSCCPass(&ID) {}
39
40     // runOnSCC - Analyze the SCC, performing the transformation if possible.
41     bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
42
43     // AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
44     bool AddReadAttrs(const std::vector<CallGraphNode *> &SCC);
45
46     // AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
47     bool AddNoCaptureAttrs(const std::vector<CallGraphNode *> &SCC);
48
49     // isCaptured - Returns true if this pointer value escapes.
50     bool isCaptured(Function &F, Value *V);
51
52     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
53       AU.setPreservesCFG();
54       CallGraphSCCPass::getAnalysisUsage(AU);
55     }
56
57     bool PointsToLocalMemory(Value *V);
58   };
59 }
60
61 char FunctionAttrs::ID = 0;
62 static RegisterPass<FunctionAttrs>
63 X("functionattrs", "Deduce function attributes");
64
65 Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
66
67
68 /// PointsToLocalMemory - Returns whether the given pointer value points to
69 /// memory that is local to the function.  Global constants are considered
70 /// local to all functions.
71 bool FunctionAttrs::PointsToLocalMemory(Value *V) {
72   V = V->getUnderlyingObject();
73   // An alloca instruction defines local memory.
74   if (isa<AllocaInst>(V))
75     return true;
76   // A global constant counts as local memory for our purposes.
77   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
78     return GV->isConstant();
79   // Could look through phi nodes and selects here, but it doesn't seem
80   // to be useful in practice.
81   return false;
82 }
83
84 /// AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
85 bool FunctionAttrs::AddReadAttrs(const std::vector<CallGraphNode *> &SCC) {
86   SmallPtrSet<CallGraphNode*, 8> SCCNodes;
87   CallGraph &CG = getAnalysis<CallGraph>();
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 (unsigned i = 0, e = SCC.size(); i != e; ++i)
92     SCCNodes.insert(SCC[i]);
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 (unsigned i = 0, e = SCC.size(); i != e; ++i) {
98     Function *F = SCC[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 = CallSite::get(I);
126       if (CS.getInstruction()) {
127         // Ignore calls to functions in the same SCC.
128         if (SCCNodes.count(CG[CS.getCalledFunction()]))
129           continue;
130       } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
131         // Ignore loads from local memory.
132         if (PointsToLocalMemory(LI->getPointerOperand()))
133           continue;
134       } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
135         // Ignore stores to local memory.
136         if (PointsToLocalMemory(SI->getPointerOperand()))
137           continue;
138       }
139
140       // Any remaining instructions need to be taken seriously!  Check if they
141       // read or write memory.
142       if (I->mayWriteToMemory())
143         // Writes memory.  Just give up.
144         return false;
145       // If this instruction may read memory, remember that.
146       ReadsMemory |= I->mayReadFromMemory();
147     }
148   }
149
150   // Success!  Functions in this SCC do not access memory, or only read memory.
151   // Give them the appropriate attribute.
152   bool MadeChange = false;
153   for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
154     Function *F = SCC[i]->getFunction();
155
156     if (F->doesNotAccessMemory())
157       // Already perfect!
158       continue;
159
160     if (F->onlyReadsMemory() && ReadsMemory)
161       // No change.
162       continue;
163
164     MadeChange = true;
165
166     // Clear out any existing attributes.
167     F->removeAttribute(~0, Attribute::ReadOnly | Attribute::ReadNone);
168
169     // Add in the new attribute.
170     F->addAttribute(~0, ReadsMemory? Attribute::ReadOnly : Attribute::ReadNone);
171
172     if (ReadsMemory)
173       NumReadOnly++;
174     else
175       NumReadNone++;
176   }
177
178   return MadeChange;
179 }
180
181 /// isCaptured - Returns whether this pointer value is captured.
182 bool FunctionAttrs::isCaptured(Function &F, Value *V) {
183   SmallVector<Use*, 16> Worklist;
184   SmallPtrSet<Use*, 16> Visited;
185
186   for (Value::use_iterator UI = V->use_begin(), UE = V->use_end(); UI != UE;
187        ++UI) {
188     Use *U = &UI.getUse();
189     Visited.insert(U);
190     Worklist.push_back(U);
191   }
192
193   while (!Worklist.empty()) {
194     Use *U = Worklist.pop_back_val();
195     Instruction *I = cast<Instruction>(U->getUser());
196     V = U->get();
197
198     if (isa<LoadInst>(I)) {
199       // Loading a pointer does not cause it to escape.
200       continue;
201     }
202
203     if (isa<StoreInst>(I)) {
204       if (V == I->getOperand(0))
205         // Stored the pointer - escapes.  TODO: improve this.
206         return true;
207       // Storing to the pointee does not cause the pointer to escape.
208       continue;
209     }
210
211     CallSite CS = CallSite::get(I);
212     if (CS.getInstruction()) {
213       // Does not escape if only passed via 'nocapture' arguments.  Note
214       // that calling a function pointer does not in itself cause that
215       // function pointer to escape.  This is a subtle point considering
216       // that (for example) the callee might return its own address.  It
217       // is analogous to saying that loading a value from a pointer does
218       // not cause the pointer to escape, even though the loaded value
219       // might be the pointer itself (think of self-referential objects).
220       CallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
221       for (CallSite::arg_iterator A = B; A != E; ++A)
222         if (A->get() == V && !CS.paramHasAttr(A-B+1, Attribute::NoCapture))
223           // The parameter is not marked 'nocapture' - escapes.
224           return true;
225       // Only passed via 'nocapture' arguments, or is the called function.
226       // Does not escape.
227       continue;
228     }
229
230     if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I) ||
231         isa<PHINode>(I) || isa<SelectInst>(I)) {
232       // Type conversion, calculating an offset, or merging values.
233       // The original value does not escape via this if the new value doesn't.
234       // Note that in the case of a select instruction it is important that
235       // the value not be used as the condition, since otherwise one bit of
236       // information might escape.  It cannot be the condition because it has
237       // the wrong type.
238       for (Instruction::use_iterator UI = I->use_begin(), UE = I->use_end();
239            UI != UE; ++UI) {
240         Use *U = &UI.getUse();
241         if (Visited.insert(U))
242           Worklist.push_back(U);
243       }
244       continue;
245     }
246
247     // Something else - be conservative and say it escapes.
248     return true;
249   }
250
251   return false;
252 }
253
254 /// AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
255 bool FunctionAttrs::AddNoCaptureAttrs(const std::vector<CallGraphNode *> &SCC) {
256   bool Changed = false;
257
258   // Check each function in turn, determining which pointer arguments are not
259   // captured.
260   for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
261     Function *F = SCC[i]->getFunction();
262
263     if (F == 0)
264       // External node - skip it;
265       continue;
266
267     // Definitions with weak linkage may be overridden at linktime with
268     // something that writes memory, so treat them like declarations.
269     if (F->isDeclaration() || F->mayBeOverridden())
270       continue;
271
272     for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A!=E; ++A)
273       if (isa<PointerType>(A->getType()) && !A->hasNoCaptureAttr() &&
274           !isCaptured(*F, A)) {
275         A->addAttr(Attribute::NoCapture);
276         NumNoCapture++;
277         Changed = true;
278       }
279   }
280
281   return Changed;
282 }
283
284 bool FunctionAttrs::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
285   bool Changed = AddReadAttrs(SCC);
286   Changed |= AddNoCaptureAttrs(SCC);
287   return Changed;
288 }