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