1 //===- FunctionAttrs.cpp - Pass which marks functions readnone or readonly ===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
19 //===----------------------------------------------------------------------===//
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/Analysis/MallocHelper.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/UniqueVector.h"
33 #include "llvm/Support/Compiler.h"
34 #include "llvm/Support/InstIterator.h"
37 STATISTIC(NumReadNone, "Number of functions marked readnone");
38 STATISTIC(NumReadOnly, "Number of functions marked readonly");
39 STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
40 STATISTIC(NumNoAlias, "Number of function returns marked noalias");
43 struct VISIBILITY_HIDDEN FunctionAttrs : public CallGraphSCCPass {
44 static char ID; // Pass identification, replacement for typeid
45 FunctionAttrs() : CallGraphSCCPass(&ID) {}
47 // runOnSCC - Analyze the SCC, performing the transformation if possible.
48 bool runOnSCC(std::vector<CallGraphNode *> &SCC);
50 // AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
51 bool AddReadAttrs(const std::vector<CallGraphNode *> &SCC);
53 // AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
54 bool AddNoCaptureAttrs(const std::vector<CallGraphNode *> &SCC);
56 // IsFunctionMallocLike - Does this function allocate new memory?
57 bool IsFunctionMallocLike(Function *F,
58 SmallPtrSet<Function*, 8> &) const;
60 // AddNoAliasAttrs - Deduce noalias attributes for the SCC.
61 bool AddNoAliasAttrs(const std::vector<CallGraphNode *> &SCC);
63 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
65 CallGraphSCCPass::getAnalysisUsage(AU);
68 bool PointsToLocalMemory(Value *V);
72 char FunctionAttrs::ID = 0;
73 static RegisterPass<FunctionAttrs>
74 X("functionattrs", "Deduce function attributes");
76 Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
79 /// PointsToLocalMemory - Returns whether the given pointer value points to
80 /// memory that is local to the function. Global constants are considered
81 /// local to all functions.
82 bool FunctionAttrs::PointsToLocalMemory(Value *V) {
83 V = V->getUnderlyingObject();
84 // An alloca instruction defines local memory.
85 if (isa<AllocaInst>(V))
87 // A global constant counts as local memory for our purposes.
88 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
89 return GV->isConstant();
90 // Could look through phi nodes and selects here, but it doesn't seem
91 // to be useful in practice.
95 /// AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
96 bool FunctionAttrs::AddReadAttrs(const std::vector<CallGraphNode *> &SCC) {
97 SmallPtrSet<Function*, 8> SCCNodes;
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]->getFunction());
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();
111 // External node - may write memory. Just give up.
114 if (F->doesNotAccessMemory())
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.
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;
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() && CS.getCalledFunction()) {
137 // Ignore calls to functions in the same SCC.
138 if (SCCNodes.count(CS.getCalledFunction()))
140 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
141 // Ignore loads from local memory.
142 if (PointsToLocalMemory(LI->getPointerOperand()))
144 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
145 // Ignore stores to local memory.
146 if (PointsToLocalMemory(SI->getPointerOperand()))
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.
156 if (isa<MallocInst>(I) || isMalloc(I))
157 // malloc claims not to write memory! PR3754.
160 // If this instruction may read memory, remember that.
161 ReadsMemory |= I->mayReadFromMemory();
165 // Success! Functions in this SCC do not access memory, or only read memory.
166 // Give them the appropriate attribute.
167 bool MadeChange = false;
168 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
169 Function *F = SCC[i]->getFunction();
171 if (F->doesNotAccessMemory())
175 if (F->onlyReadsMemory() && ReadsMemory)
181 // Clear out any existing attributes.
182 F->removeAttribute(~0, Attribute::ReadOnly | Attribute::ReadNone);
184 // Add in the new attribute.
185 F->addAttribute(~0, ReadsMemory? Attribute::ReadOnly : Attribute::ReadNone);
196 /// AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
197 bool FunctionAttrs::AddNoCaptureAttrs(const std::vector<CallGraphNode *> &SCC) {
198 bool Changed = false;
200 // Check each function in turn, determining which pointer arguments are not
202 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
203 Function *F = SCC[i]->getFunction();
206 // External node - skip it;
209 // Definitions with weak linkage may be overridden at linktime with
210 // something that writes memory, so treat them like declarations.
211 if (F->isDeclaration() || F->mayBeOverridden())
214 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A!=E; ++A)
215 if (isa<PointerType>(A->getType()) && !A->hasNoCaptureAttr() &&
216 !PointerMayBeCaptured(A, true)) {
217 A->addAttr(Attribute::NoCapture);
226 /// IsFunctionMallocLike - A function is malloc-like if it returns either null
227 /// or a pointer that doesn't alias any other pointer visible to the caller.
228 bool FunctionAttrs::IsFunctionMallocLike(Function *F,
229 SmallPtrSet<Function*, 8> &SCCNodes) const {
230 UniqueVector<Value *> FlowsToReturn;
231 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
232 if (ReturnInst *Ret = dyn_cast<ReturnInst>(I->getTerminator()))
233 FlowsToReturn.insert(Ret->getReturnValue());
235 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
236 Value *RetVal = FlowsToReturn[i+1]; // UniqueVector[0] is reserved.
238 if (Constant *C = dyn_cast<Constant>(RetVal)) {
239 if (!C->isNullValue() && !isa<UndefValue>(C))
245 if (isa<Argument>(RetVal))
248 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
249 switch (RVI->getOpcode()) {
250 // Extend the analysis by looking upwards.
251 case Instruction::BitCast:
255 case Instruction::GetElementPtr:
256 FlowsToReturn.insert(RVI->getOperand(0));
258 case Instruction::Select: {
259 SelectInst *SI = cast<SelectInst>(RVI);
260 FlowsToReturn.insert(SI->getTrueValue());
261 FlowsToReturn.insert(SI->getFalseValue());
263 case Instruction::PHI: {
264 PHINode *PN = cast<PHINode>(RVI);
265 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
266 FlowsToReturn.insert(PN->getIncomingValue(i));
269 // Check whether the pointer came from an allocation.
270 case Instruction::Alloca:
271 case Instruction::Malloc:
273 case Instruction::Call:
276 case Instruction::Invoke: {
278 if (CS.paramHasAttr(0, Attribute::NoAlias))
280 if (CS.getCalledFunction() &&
281 SCCNodes.count(CS.getCalledFunction()))
285 return false; // Did not come from an allocation.
288 if (PointerMayBeCaptured(RetVal, false))
295 /// AddNoAliasAttrs - Deduce noalias attributes for the SCC.
296 bool FunctionAttrs::AddNoAliasAttrs(const std::vector<CallGraphNode *> &SCC) {
297 SmallPtrSet<Function*, 8> SCCNodes;
299 // Fill SCCNodes with the elements of the SCC. Used for quickly
300 // looking up whether a given CallGraphNode is in this SCC.
301 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
302 SCCNodes.insert(SCC[i]->getFunction());
304 // Check each function in turn, determining which functions return noalias
306 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
307 Function *F = SCC[i]->getFunction();
310 // External node - skip it;
314 if (F->doesNotAlias(0))
317 // Definitions with weak linkage may be overridden at linktime, so
318 // treat them like declarations.
319 if (F->isDeclaration() || F->mayBeOverridden())
322 // We annotate noalias return values, which are only applicable to
324 if (!isa<PointerType>(F->getReturnType()))
327 if (!IsFunctionMallocLike(F, SCCNodes))
331 bool MadeChange = false;
332 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
333 Function *F = SCC[i]->getFunction();
334 if (F->doesNotAlias(0) || !isa<PointerType>(F->getReturnType()))
337 F->setDoesNotAlias(0);
345 bool FunctionAttrs::runOnSCC(std::vector<CallGraphNode *> &SCC) {
346 bool Changed = AddReadAttrs(SCC);
347 Changed |= AddNoCaptureAttrs(SCC);
348 Changed |= AddNoAliasAttrs(SCC);