blob: 14c94da55951fec4f4d5a5fda14a55ec1ae9fd43 [file] [log] [blame]
Duncan Sands9e89ba32008-12-31 16:14:43 +00001//===- 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
Duncan Sandsb2f22792009-01-02 11:46:24 +000012// 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.
Duncan Sands9e89ba32008-12-31 16:14:43 +000018//
19//===----------------------------------------------------------------------===//
20
21#define DEBUG_TYPE "functionattrs"
22#include "llvm/Transforms/IPO.h"
23#include "llvm/CallGraphSCCPass.h"
24#include "llvm/GlobalVariable.h"
Devang Patelcd119912009-03-03 00:28:44 +000025#include "llvm/IntrinsicInst.h"
Nick Lewycky199aa3c2009-03-08 06:20:47 +000026#include "llvm/Analysis/AliasAnalysis.h"
Duncan Sands9e89ba32008-12-31 16:14:43 +000027#include "llvm/Analysis/CallGraph.h"
Duncan Sands8556d2a2009-01-18 12:19:30 +000028#include "llvm/Analysis/CaptureTracking.h"
Victor Hernandez83d63912009-09-18 22:35:49 +000029#include "llvm/Analysis/MallocHelper.h"
Duncan Sands338cd6b2009-01-02 11:54:37 +000030#include "llvm/ADT/SmallSet.h"
Duncan Sands9e89ba32008-12-31 16:14:43 +000031#include "llvm/ADT/Statistic.h"
Nick Lewycky199aa3c2009-03-08 06:20:47 +000032#include "llvm/ADT/UniqueVector.h"
Duncan Sands9e89ba32008-12-31 16:14:43 +000033#include "llvm/Support/Compiler.h"
34#include "llvm/Support/InstIterator.h"
35using namespace llvm;
36
37STATISTIC(NumReadNone, "Number of functions marked readnone");
38STATISTIC(NumReadOnly, "Number of functions marked readonly");
39STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
Nick Lewycky199aa3c2009-03-08 06:20:47 +000040STATISTIC(NumNoAlias, "Number of function returns marked noalias");
Duncan Sands9e89ba32008-12-31 16:14:43 +000041
42namespace {
43 struct VISIBILITY_HIDDEN FunctionAttrs : public CallGraphSCCPass {
44 static char ID; // Pass identification, replacement for typeid
45 FunctionAttrs() : CallGraphSCCPass(&ID) {}
46
47 // runOnSCC - Analyze the SCC, performing the transformation if possible.
Chris Lattner5095e3d2009-08-31 00:19:58 +000048 bool runOnSCC(std::vector<CallGraphNode *> &SCC);
Duncan Sands9e89ba32008-12-31 16:14:43 +000049
50 // AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
51 bool AddReadAttrs(const std::vector<CallGraphNode *> &SCC);
52
53 // AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
54 bool AddNoCaptureAttrs(const std::vector<CallGraphNode *> &SCC);
55
Nick Lewycky199aa3c2009-03-08 06:20:47 +000056 // IsFunctionMallocLike - Does this function allocate new memory?
57 bool IsFunctionMallocLike(Function *F,
Chris Lattner98a27ce2009-08-31 04:09:04 +000058 SmallPtrSet<Function*, 8> &) const;
Nick Lewycky199aa3c2009-03-08 06:20:47 +000059
60 // AddNoAliasAttrs - Deduce noalias attributes for the SCC.
61 bool AddNoAliasAttrs(const std::vector<CallGraphNode *> &SCC);
62
Duncan Sands9e89ba32008-12-31 16:14:43 +000063 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
64 AU.setPreservesCFG();
65 CallGraphSCCPass::getAnalysisUsage(AU);
66 }
67
68 bool PointsToLocalMemory(Value *V);
69 };
70}
71
72char FunctionAttrs::ID = 0;
73static RegisterPass<FunctionAttrs>
74X("functionattrs", "Deduce function attributes");
75
76Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
77
78
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.
82bool FunctionAttrs::PointsToLocalMemory(Value *V) {
83 V = V->getUnderlyingObject();
84 // An alloca instruction defines local memory.
85 if (isa<AllocaInst>(V))
86 return true;
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.
92 return false;
93}
94
95/// AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
96bool FunctionAttrs::AddReadAttrs(const std::vector<CallGraphNode *> &SCC) {
Chris Lattner98a27ce2009-08-31 04:09:04 +000097 SmallPtrSet<Function*, 8> SCCNodes;
Duncan Sands9e89ba32008-12-31 16:14:43 +000098
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)
Chris Lattner98a27ce2009-08-31 04:09:04 +0000102 SCCNodes.insert(SCC[i]->getFunction());
Duncan Sands9e89ba32008-12-31 16:14:43 +0000103
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);
Chris Lattner98a27ce2009-08-31 04:09:04 +0000136 if (CS.getInstruction() && CS.getCalledFunction()) {
Duncan Sands9e89ba32008-12-31 16:14:43 +0000137 // Ignore calls to functions in the same SCC.
Chris Lattner98a27ce2009-08-31 04:09:04 +0000138 if (SCCNodes.count(CS.getCalledFunction()))
Duncan Sands9e89ba32008-12-31 16:14:43 +0000139 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;
Duncan Sandscfd0ebe2009-05-06 08:42:00 +0000155
Victor Hernandez83d63912009-09-18 22:35:49 +0000156 if (isa<MallocInst>(I) || isMalloc(I))
157 // malloc claims not to write memory! PR3754.
Duncan Sandscfd0ebe2009-05-06 08:42:00 +0000158 return false;
159
Duncan Sands9e89ba32008-12-31 16:14:43 +0000160 // If this instruction may read memory, remember that.
161 ReadsMemory |= I->mayReadFromMemory();
162 }
163 }
164
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();
170
171 if (F->doesNotAccessMemory())
172 // Already perfect!
173 continue;
174
175 if (F->onlyReadsMemory() && ReadsMemory)
176 // No change.
177 continue;
178
179 MadeChange = true;
180
181 // Clear out any existing attributes.
182 F->removeAttribute(~0, Attribute::ReadOnly | Attribute::ReadNone);
183
184 // Add in the new attribute.
185 F->addAttribute(~0, ReadsMemory? Attribute::ReadOnly : Attribute::ReadNone);
186
187 if (ReadsMemory)
Duncan Sandsb2f22792009-01-02 11:46:24 +0000188 ++NumReadOnly;
Duncan Sands9e89ba32008-12-31 16:14:43 +0000189 else
Duncan Sandsb2f22792009-01-02 11:46:24 +0000190 ++NumReadNone;
Duncan Sands9e89ba32008-12-31 16:14:43 +0000191 }
192
193 return MadeChange;
194}
195
Duncan Sands9e89ba32008-12-31 16:14:43 +0000196/// AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
197bool FunctionAttrs::AddNoCaptureAttrs(const std::vector<CallGraphNode *> &SCC) {
198 bool Changed = false;
199
200 // Check each function in turn, determining which pointer arguments are not
201 // captured.
202 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
203 Function *F = SCC[i]->getFunction();
204
205 if (F == 0)
206 // External node - skip it;
207 continue;
208
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())
212 continue;
213
214 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A!=E; ++A)
Duncan Sands17da06f2008-12-31 18:08:59 +0000215 if (isa<PointerType>(A->getType()) && !A->hasNoCaptureAttr() &&
Duncan Sands8556d2a2009-01-18 12:19:30 +0000216 !PointerMayBeCaptured(A, true)) {
Duncan Sands9e89ba32008-12-31 16:14:43 +0000217 A->addAttr(Attribute::NoCapture);
Nick Lewycky6b056862009-01-02 03:46:56 +0000218 ++NumNoCapture;
Duncan Sands9e89ba32008-12-31 16:14:43 +0000219 Changed = true;
220 }
221 }
222
223 return Changed;
224}
225
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000226/// IsFunctionMallocLike - A function is malloc-like if it returns either null
Nick Lewycky4bfba9d2009-03-08 17:08:09 +0000227/// or a pointer that doesn't alias any other pointer visible to the caller.
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000228bool FunctionAttrs::IsFunctionMallocLike(Function *F,
Chris Lattner98a27ce2009-08-31 04:09:04 +0000229 SmallPtrSet<Function*, 8> &SCCNodes) const {
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000230 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());
234
235 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
236 Value *RetVal = FlowsToReturn[i+1]; // UniqueVector[0] is reserved.
237
238 if (Constant *C = dyn_cast<Constant>(RetVal)) {
239 if (!C->isNullValue() && !isa<UndefValue>(C))
240 return false;
241
242 continue;
243 }
244
245 if (isa<Argument>(RetVal))
246 return false;
247
248 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
249 switch (RVI->getOpcode()) {
250 // Extend the analysis by looking upwards.
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000251 case Instruction::BitCast:
Victor Hernandez83d63912009-09-18 22:35:49 +0000252 if (isMalloc(RVI))
253 break;
254 // fall through
255 case Instruction::GetElementPtr:
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000256 FlowsToReturn.insert(RVI->getOperand(0));
257 continue;
258 case Instruction::Select: {
259 SelectInst *SI = cast<SelectInst>(RVI);
260 FlowsToReturn.insert(SI->getTrueValue());
261 FlowsToReturn.insert(SI->getFalseValue());
262 } continue;
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));
267 } continue;
268
269 // Check whether the pointer came from an allocation.
270 case Instruction::Alloca:
271 case Instruction::Malloc:
272 break;
273 case Instruction::Call:
Victor Hernandez83d63912009-09-18 22:35:49 +0000274 if (isMalloc(RVI))
275 break;
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000276 case Instruction::Invoke: {
277 CallSite CS(RVI);
278 if (CS.paramHasAttr(0, Attribute::NoAlias))
279 break;
280 if (CS.getCalledFunction() &&
Chris Lattner98a27ce2009-08-31 04:09:04 +0000281 SCCNodes.count(CS.getCalledFunction()))
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000282 break;
283 } // fall-through
284 default:
285 return false; // Did not come from an allocation.
286 }
287
288 if (PointerMayBeCaptured(RetVal, false))
289 return false;
290 }
291
292 return true;
293}
294
295/// AddNoAliasAttrs - Deduce noalias attributes for the SCC.
296bool FunctionAttrs::AddNoAliasAttrs(const std::vector<CallGraphNode *> &SCC) {
Chris Lattner98a27ce2009-08-31 04:09:04 +0000297 SmallPtrSet<Function*, 8> SCCNodes;
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000298
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)
Chris Lattner98a27ce2009-08-31 04:09:04 +0000302 SCCNodes.insert(SCC[i]->getFunction());
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000303
Nick Lewycky4bfba9d2009-03-08 17:08:09 +0000304 // Check each function in turn, determining which functions return noalias
305 // pointers.
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000306 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
307 Function *F = SCC[i]->getFunction();
308
309 if (F == 0)
310 // External node - skip it;
311 return false;
312
313 // Already noalias.
314 if (F->doesNotAlias(0))
315 continue;
316
317 // Definitions with weak linkage may be overridden at linktime, so
318 // treat them like declarations.
319 if (F->isDeclaration() || F->mayBeOverridden())
320 return false;
321
322 // We annotate noalias return values, which are only applicable to
323 // pointer types.
324 if (!isa<PointerType>(F->getReturnType()))
325 continue;
326
327 if (!IsFunctionMallocLike(F, SCCNodes))
328 return false;
329 }
330
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()))
335 continue;
336
337 F->setDoesNotAlias(0);
338 ++NumNoAlias;
339 MadeChange = true;
340 }
341
342 return MadeChange;
343}
344
Chris Lattner5095e3d2009-08-31 00:19:58 +0000345bool FunctionAttrs::runOnSCC(std::vector<CallGraphNode *> &SCC) {
Duncan Sands9e89ba32008-12-31 16:14:43 +0000346 bool Changed = AddReadAttrs(SCC);
347 Changed |= AddNoCaptureAttrs(SCC);
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000348 Changed |= AddNoAliasAttrs(SCC);
Duncan Sands9e89ba32008-12-31 16:14:43 +0000349 return Changed;
350}