This debug info special case should no longer
[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/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/CallGraph.h"
28 #include "llvm/Analysis/CaptureTracking.h"
29 #include "llvm/ADT/SmallSet.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/ADT/UniqueVector.h"
32 #include "llvm/Support/Compiler.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 VISIBILITY_HIDDEN FunctionAttrs : public CallGraphSCCPass {
43     static char ID; // Pass identification, replacement for typeid
44     FunctionAttrs() : CallGraphSCCPass(&ID) {}
45
46     // runOnSCC - Analyze the SCC, performing the transformation if possible.
47     bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
48
49     // AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
50     bool AddReadAttrs(const std::vector<CallGraphNode *> &SCC);
51
52     // AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
53     bool AddNoCaptureAttrs(const std::vector<CallGraphNode *> &SCC);
54
55     // IsFunctionMallocLike - Does this function allocate new memory?
56     bool IsFunctionMallocLike(Function *F,
57                               SmallPtrSet<CallGraphNode*, 8> &) const;
58
59     // AddNoAliasAttrs - Deduce noalias attributes for the SCC.
60     bool AddNoAliasAttrs(const std::vector<CallGraphNode *> &SCC);
61
62     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
63       AU.setPreservesCFG();
64       CallGraphSCCPass::getAnalysisUsage(AU);
65     }
66
67     bool PointsToLocalMemory(Value *V);
68   };
69 }
70
71 char FunctionAttrs::ID = 0;
72 static RegisterPass<FunctionAttrs>
73 X("functionattrs", "Deduce function attributes");
74
75 Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
76
77
78 /// PointsToLocalMemory - Returns whether the given pointer value points to
79 /// memory that is local to the function.  Global constants are considered
80 /// local to all functions.
81 bool FunctionAttrs::PointsToLocalMemory(Value *V) {
82   V = V->getUnderlyingObject();
83   // An alloca instruction defines local memory.
84   if (isa<AllocaInst>(V))
85     return true;
86   // A global constant counts as local memory for our purposes.
87   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
88     return GV->isConstant();
89   // Could look through phi nodes and selects here, but it doesn't seem
90   // to be useful in practice.
91   return false;
92 }
93
94 /// AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
95 bool FunctionAttrs::AddReadAttrs(const std::vector<CallGraphNode *> &SCC) {
96   SmallPtrSet<CallGraphNode*, 8> SCCNodes;
97   CallGraph &CG = getAnalysis<CallGraph>();
98
99   // Fill SCCNodes with the elements of the SCC.  Used for quickly
100   // looking up whether a given CallGraphNode is in this SCC.
101   for (unsigned i = 0, e = SCC.size(); i != e; ++i)
102     SCCNodes.insert(SCC[i]);
103
104   // Check if any of the functions in the SCC read or write memory.  If they
105   // write memory then they can't be marked readnone or readonly.
106   bool ReadsMemory = false;
107   for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
108     Function *F = SCC[i]->getFunction();
109
110     if (F == 0)
111       // External node - may write memory.  Just give up.
112       return false;
113
114     if (F->doesNotAccessMemory())
115       // Already perfect!
116       continue;
117
118     // Definitions with weak linkage may be overridden at linktime with
119     // something that writes memory, so treat them like declarations.
120     if (F->isDeclaration() || F->mayBeOverridden()) {
121       if (!F->onlyReadsMemory())
122         // May write memory.  Just give up.
123         return false;
124
125       ReadsMemory = true;
126       continue;
127     }
128
129     // Scan the function body for instructions that may read or write memory.
130     for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
131       Instruction *I = &*II;
132
133       // Some instructions can be ignored even if they read or write memory.
134       // Detect these now, skipping to the next instruction if one is found.
135       CallSite CS = CallSite::get(I);
136       if (CS.getInstruction()) {
137         // Ignore calls to functions in the same SCC.
138         if (SCCNodes.count(CG[CS.getCalledFunction()]))
139           continue;
140       } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
141         // Ignore loads from local memory.
142         if (PointsToLocalMemory(LI->getPointerOperand()))
143           continue;
144       } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
145         // Ignore stores to local memory.
146         if (PointsToLocalMemory(SI->getPointerOperand()))
147           continue;
148       }
149
150       // Any remaining instructions need to be taken seriously!  Check if they
151       // read or write memory.
152       if (I->mayWriteToMemory())
153         // Writes memory.  Just give up.
154         return false;
155       // If this instruction may read memory, remember that.
156       ReadsMemory |= I->mayReadFromMemory();
157     }
158   }
159
160   // Success!  Functions in this SCC do not access memory, or only read memory.
161   // Give them the appropriate attribute.
162   bool MadeChange = false;
163   for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
164     Function *F = SCC[i]->getFunction();
165
166     if (F->doesNotAccessMemory())
167       // Already perfect!
168       continue;
169
170     if (F->onlyReadsMemory() && ReadsMemory)
171       // No change.
172       continue;
173
174     MadeChange = true;
175
176     // Clear out any existing attributes.
177     F->removeAttribute(~0, Attribute::ReadOnly | Attribute::ReadNone);
178
179     // Add in the new attribute.
180     F->addAttribute(~0, ReadsMemory? Attribute::ReadOnly : Attribute::ReadNone);
181
182     if (ReadsMemory)
183       ++NumReadOnly;
184     else
185       ++NumReadNone;
186   }
187
188   return MadeChange;
189 }
190
191 /// AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
192 bool FunctionAttrs::AddNoCaptureAttrs(const std::vector<CallGraphNode *> &SCC) {
193   bool Changed = false;
194
195   // Check each function in turn, determining which pointer arguments are not
196   // captured.
197   for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
198     Function *F = SCC[i]->getFunction();
199
200     if (F == 0)
201       // External node - skip it;
202       continue;
203
204     // Definitions with weak linkage may be overridden at linktime with
205     // something that writes memory, so treat them like declarations.
206     if (F->isDeclaration() || F->mayBeOverridden())
207       continue;
208
209     for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A!=E; ++A)
210       if (isa<PointerType>(A->getType()) && !A->hasNoCaptureAttr() &&
211           !PointerMayBeCaptured(A, true)) {
212         A->addAttr(Attribute::NoCapture);
213         ++NumNoCapture;
214         Changed = true;
215       }
216   }
217
218   return Changed;
219 }
220
221 /// IsFunctionMallocLike - A function is malloc-like if it returns either null
222 /// or a pointer that doesn't alias any other pointer visible to the caller.
223 bool FunctionAttrs::IsFunctionMallocLike(Function *F,
224                               SmallPtrSet<CallGraphNode*, 8> &SCCNodes) const {
225   CallGraph &CG = getAnalysis<CallGraph>();
226
227   UniqueVector<Value *> FlowsToReturn;
228   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
229     if (ReturnInst *Ret = dyn_cast<ReturnInst>(I->getTerminator()))
230       FlowsToReturn.insert(Ret->getReturnValue());
231
232   for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
233     Value *RetVal = FlowsToReturn[i+1];   // UniqueVector[0] is reserved.
234
235     if (Constant *C = dyn_cast<Constant>(RetVal)) {
236       if (!C->isNullValue() && !isa<UndefValue>(C))
237         return false;
238
239       continue;
240     }
241
242     if (isa<Argument>(RetVal))
243       return false;
244
245     if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
246       switch (RVI->getOpcode()) {
247         // Extend the analysis by looking upwards.
248         case Instruction::GetElementPtr:
249         case Instruction::BitCast:
250           FlowsToReturn.insert(RVI->getOperand(0));
251           continue;
252         case Instruction::Select: {
253           SelectInst *SI = cast<SelectInst>(RVI);
254           FlowsToReturn.insert(SI->getTrueValue());
255           FlowsToReturn.insert(SI->getFalseValue());
256         } continue;
257         case Instruction::PHI: {
258           PHINode *PN = cast<PHINode>(RVI);
259           for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
260             FlowsToReturn.insert(PN->getIncomingValue(i));
261         } continue;
262
263         // Check whether the pointer came from an allocation.
264         case Instruction::Alloca:
265         case Instruction::Malloc:
266           break;
267         case Instruction::Call:
268         case Instruction::Invoke: {
269           CallSite CS(RVI);
270           if (CS.paramHasAttr(0, Attribute::NoAlias))
271             break;
272           if (CS.getCalledFunction() &&
273               SCCNodes.count(CG[CS.getCalledFunction()]))
274             break;
275         } // fall-through
276         default:
277           return false;  // Did not come from an allocation.
278       }
279
280     if (PointerMayBeCaptured(RetVal, false))
281       return false;
282   }
283
284   return true;
285 }
286
287 /// AddNoAliasAttrs - Deduce noalias attributes for the SCC.
288 bool FunctionAttrs::AddNoAliasAttrs(const std::vector<CallGraphNode *> &SCC) {
289   SmallPtrSet<CallGraphNode*, 8> SCCNodes;
290
291   // Fill SCCNodes with the elements of the SCC.  Used for quickly
292   // looking up whether a given CallGraphNode is in this SCC.
293   for (unsigned i = 0, e = SCC.size(); i != e; ++i)
294     SCCNodes.insert(SCC[i]);
295
296   // Check each function in turn, determining which functions return noalias
297   // pointers.
298   for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
299     Function *F = SCC[i]->getFunction();
300
301     if (F == 0)
302       // External node - skip it;
303       return false;
304
305     // Already noalias.
306     if (F->doesNotAlias(0))
307       continue;
308
309     // Definitions with weak linkage may be overridden at linktime, so
310     // treat them like declarations.
311     if (F->isDeclaration() || F->mayBeOverridden())
312       return false;
313
314     // We annotate noalias return values, which are only applicable to 
315     // pointer types.
316     if (!isa<PointerType>(F->getReturnType()))
317       continue;
318
319     if (!IsFunctionMallocLike(F, SCCNodes))
320       return false;
321   }
322
323   bool MadeChange = false;
324   for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
325     Function *F = SCC[i]->getFunction();
326     if (F->doesNotAlias(0) || !isa<PointerType>(F->getReturnType()))
327       continue;
328
329     F->setDoesNotAlias(0);
330     ++NumNoAlias;
331     MadeChange = true;
332   }
333
334   return MadeChange;
335 }
336
337 bool FunctionAttrs::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
338   bool Changed = AddReadAttrs(SCC);
339   Changed |= AddNoCaptureAttrs(SCC);
340   Changed |= AddNoAliasAttrs(SCC);
341   return Changed;
342 }