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. 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
17 //===----------------------------------------------------------------------===//
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"
31 STATISTIC(NumReadNone, "Number of functions marked readnone");
32 STATISTIC(NumReadOnly, "Number of functions marked readonly");
33 STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
36 struct VISIBILITY_HIDDEN FunctionAttrs : public CallGraphSCCPass {
37 static char ID; // Pass identification, replacement for typeid
38 FunctionAttrs() : CallGraphSCCPass(&ID) {}
40 // runOnSCC - Analyze the SCC, performing the transformation if possible.
41 bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
43 // AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
44 bool AddReadAttrs(const std::vector<CallGraphNode *> &SCC);
46 // AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
47 bool AddNoCaptureAttrs(const std::vector<CallGraphNode *> &SCC);
49 // isCaptured - Returns true if this pointer value escapes.
50 bool isCaptured(Function &F, Value *V);
52 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
54 CallGraphSCCPass::getAnalysisUsage(AU);
57 bool PointsToLocalMemory(Value *V);
61 char FunctionAttrs::ID = 0;
62 static RegisterPass<FunctionAttrs>
63 X("functionattrs", "Deduce function attributes");
65 Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
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))
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.
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>();
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]);
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();
101 // External node - may write memory. Just give up.
104 if (F->doesNotAccessMemory())
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.
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;
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()]))
130 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
131 // Ignore loads from local memory.
132 if (PointsToLocalMemory(LI->getPointerOperand()))
134 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
135 // Ignore stores to local memory.
136 if (PointsToLocalMemory(SI->getPointerOperand()))
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.
145 // If this instruction may read memory, remember that.
146 ReadsMemory |= I->mayReadFromMemory();
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();
156 if (F->doesNotAccessMemory())
160 if (F->onlyReadsMemory() && ReadsMemory)
166 // Clear out any existing attributes.
167 F->removeAttribute(~0, Attribute::ReadOnly | Attribute::ReadNone);
169 // Add in the new attribute.
170 F->addAttribute(~0, ReadsMemory? Attribute::ReadOnly : Attribute::ReadNone);
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;
186 for (Value::use_iterator UI = V->use_begin(), UE = V->use_end(); UI != UE;
188 Use *U = &UI.getUse();
190 Worklist.push_back(U);
193 while (!Worklist.empty()) {
194 Use *U = Worklist.pop_back_val();
195 Instruction *I = cast<Instruction>(U->getUser());
198 if (isa<LoadInst>(I)) {
199 // Loading a pointer does not cause it to escape.
203 if (isa<StoreInst>(I)) {
204 if (V == I->getOperand(0))
205 // Stored the pointer - escapes. TODO: improve this.
207 // Storing to the pointee does not cause the pointer to escape.
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.
225 // Only passed via 'nocapture' arguments, or is the called function.
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
238 for (Instruction::use_iterator UI = I->use_begin(), UE = I->use_end();
240 Use *U = &UI.getUse();
241 if (Visited.insert(U))
242 Worklist.push_back(U);
247 // Something else - be conservative and say it escapes.
254 /// AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
255 bool FunctionAttrs::AddNoCaptureAttrs(const std::vector<CallGraphNode *> &SCC) {
256 bool Changed = false;
258 // Check each function in turn, determining which pointer arguments are not
260 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
261 Function *F = SCC[i]->getFunction();
264 // External node - skip it;
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())
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);
284 bool FunctionAttrs::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
285 bool Changed = AddReadAttrs(SCC);
286 Changed |= AddNoCaptureAttrs(SCC);