blob: 9e117daa68eb912c2fa85237bf4650f7465d52e8 [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"
Duncan Sands338cd6b2009-01-02 11:54:37 +000029#include "llvm/ADT/SmallSet.h"
Duncan Sands9e89ba32008-12-31 16:14:43 +000030#include "llvm/ADT/Statistic.h"
Nick Lewycky199aa3c2009-03-08 06:20:47 +000031#include "llvm/ADT/UniqueVector.h"
Duncan Sands9e89ba32008-12-31 16:14:43 +000032#include "llvm/Support/InstIterator.h"
33using namespace llvm;
34
35STATISTIC(NumReadNone, "Number of functions marked readnone");
36STATISTIC(NumReadOnly, "Number of functions marked readonly");
37STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
Nick Lewycky199aa3c2009-03-08 06:20:47 +000038STATISTIC(NumNoAlias, "Number of function returns marked noalias");
Duncan Sands9e89ba32008-12-31 16:14:43 +000039
40namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000041 struct FunctionAttrs : public CallGraphSCCPass {
Duncan Sands9e89ba32008-12-31 16:14:43 +000042 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +000043 FunctionAttrs() : CallGraphSCCPass(ID) {
44 initializeFunctionAttrsPass(*PassRegistry::getPassRegistry());
45 }
Duncan Sands9e89ba32008-12-31 16:14:43 +000046
47 // runOnSCC - Analyze the SCC, performing the transformation if possible.
Chris Lattner2decb222010-04-16 22:42:17 +000048 bool runOnSCC(CallGraphSCC &SCC);
Duncan Sands9e89ba32008-12-31 16:14:43 +000049
50 // AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
Chris Lattner2decb222010-04-16 22:42:17 +000051 bool AddReadAttrs(const CallGraphSCC &SCC);
Duncan Sands9e89ba32008-12-31 16:14:43 +000052
53 // AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
Chris Lattner2decb222010-04-16 22:42:17 +000054 bool AddNoCaptureAttrs(const CallGraphSCC &SCC);
Duncan Sands9e89ba32008-12-31 16:14:43 +000055
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.
Chris Lattner2decb222010-04-16 22:42:17 +000061 bool AddNoAliasAttrs(const CallGraphSCC &SCC);
Nick Lewycky199aa3c2009-03-08 06:20:47 +000062
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;
Owen Andersonae0a7bc2010-10-13 22:00:45 +000073INITIALIZE_PASS_BEGIN(FunctionAttrs, "functionattrs",
74 "Deduce function attributes", false, false)
75INITIALIZE_AG_DEPENDENCY(CallGraph)
76INITIALIZE_PASS_END(FunctionAttrs, "functionattrs",
Owen Andersonce665bd2010-10-07 22:25:06 +000077 "Deduce function attributes", false, false)
Duncan Sands9e89ba32008-12-31 16:14:43 +000078
79Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
80
81
82/// PointsToLocalMemory - Returns whether the given pointer value points to
83/// memory that is local to the function. Global constants are considered
84/// local to all functions.
85bool FunctionAttrs::PointsToLocalMemory(Value *V) {
Duncan Sands5d8ea112010-01-07 05:48:42 +000086 SmallVector<Value*, 16> Worklist;
87 unsigned MaxLookup = 8;
Duncan Sandse10920d2010-01-06 15:37:47 +000088
89 Worklist.push_back(V);
90
91 do {
92 V = Worklist.pop_back_val()->getUnderlyingObject();
93
94 // An alloca instruction defines local memory.
95 if (isa<AllocaInst>(V))
96 continue;
97
98 // A global constant counts as local memory for our purposes.
99 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
100 if (!GV->isConstant())
101 return false;
102 continue;
103 }
104
105 // If both select values point to local memory, then so does the select.
106 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
107 Worklist.push_back(SI->getTrueValue());
108 Worklist.push_back(SI->getFalseValue());
109 continue;
110 }
111
112 // If all values incoming to a phi node point to local memory, then so does
113 // the phi.
114 if (PHINode *PN = dyn_cast<PHINode>(V)) {
115 // Don't bother inspecting phi nodes with many operands.
116 if (PN->getNumIncomingValues() > MaxLookup)
117 return false;
118 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
119 Worklist.push_back(PN->getIncomingValue(i));
120 continue;
121 }
122
123 return false;
124 } while (!Worklist.empty() && --MaxLookup);
125
126 return Worklist.empty();
Duncan Sands9e89ba32008-12-31 16:14:43 +0000127}
128
129/// AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
Chris Lattner2decb222010-04-16 22:42:17 +0000130bool FunctionAttrs::AddReadAttrs(const CallGraphSCC &SCC) {
Chris Lattner98a27ce2009-08-31 04:09:04 +0000131 SmallPtrSet<Function*, 8> SCCNodes;
Duncan Sands9e89ba32008-12-31 16:14:43 +0000132
133 // Fill SCCNodes with the elements of the SCC. Used for quickly
134 // looking up whether a given CallGraphNode is in this SCC.
Chris Lattner2decb222010-04-16 22:42:17 +0000135 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
136 SCCNodes.insert((*I)->getFunction());
Duncan Sands9e89ba32008-12-31 16:14:43 +0000137
138 // Check if any of the functions in the SCC read or write memory. If they
139 // write memory then they can't be marked readnone or readonly.
140 bool ReadsMemory = false;
Chris Lattner2decb222010-04-16 22:42:17 +0000141 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
142 Function *F = (*I)->getFunction();
Duncan Sands9e89ba32008-12-31 16:14:43 +0000143
144 if (F == 0)
145 // External node - may write memory. Just give up.
146 return false;
147
148 if (F->doesNotAccessMemory())
149 // Already perfect!
150 continue;
151
152 // Definitions with weak linkage may be overridden at linktime with
153 // something that writes memory, so treat them like declarations.
154 if (F->isDeclaration() || F->mayBeOverridden()) {
155 if (!F->onlyReadsMemory())
156 // May write memory. Just give up.
157 return false;
158
159 ReadsMemory = true;
160 continue;
161 }
162
163 // Scan the function body for instructions that may read or write memory.
164 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
165 Instruction *I = &*II;
166
167 // Some instructions can be ignored even if they read or write memory.
168 // Detect these now, skipping to the next instruction if one is found.
Gabor Greif7d3056b2010-07-28 22:50:26 +0000169 CallSite CS(cast<Value>(I));
170 if (CS && CS.getCalledFunction()) {
Duncan Sands9e89ba32008-12-31 16:14:43 +0000171 // Ignore calls to functions in the same SCC.
Chris Lattner98a27ce2009-08-31 04:09:04 +0000172 if (SCCNodes.count(CS.getCalledFunction()))
Duncan Sands9e89ba32008-12-31 16:14:43 +0000173 continue;
Duncan Sands7c422ac2010-01-06 08:45:52 +0000174 // Ignore intrinsics that only access local memory.
175 if (unsigned id = CS.getCalledFunction()->getIntrinsicID())
Dan Gohman79fca6f2010-08-03 21:48:53 +0000176 if (AliasAnalysis::getIntrinsicModRefBehavior(id) ==
Duncan Sands7c422ac2010-01-06 08:45:52 +0000177 AliasAnalysis::AccessesArguments) {
178 // Check that all pointer arguments point to local memory.
179 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
180 CI != CE; ++CI) {
181 Value *Arg = *CI;
Duncan Sands1df98592010-02-16 11:11:14 +0000182 if (Arg->getType()->isPointerTy() && !PointsToLocalMemory(Arg))
Duncan Sands7c422ac2010-01-06 08:45:52 +0000183 // Writes memory. Just give up.
184 return false;
185 }
186 // Only reads and writes local memory.
187 continue;
188 }
Duncan Sands9e89ba32008-12-31 16:14:43 +0000189 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Duncan Sandsad6f5412010-10-30 12:59:44 +0000190 // Ignore non-volatile loads from local memory.
191 if (!LI->isVolatile() && PointsToLocalMemory(LI->getPointerOperand()))
Duncan Sands9e89ba32008-12-31 16:14:43 +0000192 continue;
193 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Duncan Sandsad6f5412010-10-30 12:59:44 +0000194 // Ignore non-volatile stores to local memory.
195 if (!SI->isVolatile() && PointsToLocalMemory(SI->getPointerOperand()))
Duncan Sands9e89ba32008-12-31 16:14:43 +0000196 continue;
197 }
198
199 // Any remaining instructions need to be taken seriously! Check if they
200 // read or write memory.
201 if (I->mayWriteToMemory())
202 // Writes memory. Just give up.
203 return false;
Duncan Sandscfd0ebe2009-05-06 08:42:00 +0000204
Duncan Sands9e89ba32008-12-31 16:14:43 +0000205 // If this instruction may read memory, remember that.
206 ReadsMemory |= I->mayReadFromMemory();
207 }
208 }
209
210 // Success! Functions in this SCC do not access memory, or only read memory.
211 // Give them the appropriate attribute.
212 bool MadeChange = false;
Chris Lattner2decb222010-04-16 22:42:17 +0000213 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
214 Function *F = (*I)->getFunction();
Duncan Sands9e89ba32008-12-31 16:14:43 +0000215
216 if (F->doesNotAccessMemory())
217 // Already perfect!
218 continue;
219
220 if (F->onlyReadsMemory() && ReadsMemory)
221 // No change.
222 continue;
223
224 MadeChange = true;
225
226 // Clear out any existing attributes.
227 F->removeAttribute(~0, Attribute::ReadOnly | Attribute::ReadNone);
228
229 // Add in the new attribute.
230 F->addAttribute(~0, ReadsMemory? Attribute::ReadOnly : Attribute::ReadNone);
231
232 if (ReadsMemory)
Duncan Sandsb2f22792009-01-02 11:46:24 +0000233 ++NumReadOnly;
Duncan Sands9e89ba32008-12-31 16:14:43 +0000234 else
Duncan Sandsb2f22792009-01-02 11:46:24 +0000235 ++NumReadNone;
Duncan Sands9e89ba32008-12-31 16:14:43 +0000236 }
237
238 return MadeChange;
239}
240
Duncan Sands9e89ba32008-12-31 16:14:43 +0000241/// AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
Chris Lattner2decb222010-04-16 22:42:17 +0000242bool FunctionAttrs::AddNoCaptureAttrs(const CallGraphSCC &SCC) {
Duncan Sands9e89ba32008-12-31 16:14:43 +0000243 bool Changed = false;
244
245 // Check each function in turn, determining which pointer arguments are not
246 // captured.
Chris Lattner2decb222010-04-16 22:42:17 +0000247 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
248 Function *F = (*I)->getFunction();
Duncan Sands9e89ba32008-12-31 16:14:43 +0000249
250 if (F == 0)
251 // External node - skip it;
252 continue;
253
254 // Definitions with weak linkage may be overridden at linktime with
255 // something that writes memory, so treat them like declarations.
256 if (F->isDeclaration() || F->mayBeOverridden())
257 continue;
258
259 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A!=E; ++A)
Duncan Sands1df98592010-02-16 11:11:14 +0000260 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr() &&
Dan Gohmanf94b5ed2009-11-19 21:57:48 +0000261 !PointerMayBeCaptured(A, true, /*StoreCaptures=*/false)) {
Duncan Sands9e89ba32008-12-31 16:14:43 +0000262 A->addAttr(Attribute::NoCapture);
Nick Lewycky6b056862009-01-02 03:46:56 +0000263 ++NumNoCapture;
Duncan Sands9e89ba32008-12-31 16:14:43 +0000264 Changed = true;
265 }
266 }
267
268 return Changed;
269}
270
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000271/// IsFunctionMallocLike - A function is malloc-like if it returns either null
Nick Lewycky4bfba9d2009-03-08 17:08:09 +0000272/// or a pointer that doesn't alias any other pointer visible to the caller.
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000273bool FunctionAttrs::IsFunctionMallocLike(Function *F,
Chris Lattner98a27ce2009-08-31 04:09:04 +0000274 SmallPtrSet<Function*, 8> &SCCNodes) const {
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000275 UniqueVector<Value *> FlowsToReturn;
276 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
277 if (ReturnInst *Ret = dyn_cast<ReturnInst>(I->getTerminator()))
278 FlowsToReturn.insert(Ret->getReturnValue());
279
280 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
281 Value *RetVal = FlowsToReturn[i+1]; // UniqueVector[0] is reserved.
282
283 if (Constant *C = dyn_cast<Constant>(RetVal)) {
284 if (!C->isNullValue() && !isa<UndefValue>(C))
285 return false;
286
287 continue;
288 }
289
290 if (isa<Argument>(RetVal))
291 return false;
292
293 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
294 switch (RVI->getOpcode()) {
295 // Extend the analysis by looking upwards.
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000296 case Instruction::BitCast:
Victor Hernandez83d63912009-09-18 22:35:49 +0000297 case Instruction::GetElementPtr:
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000298 FlowsToReturn.insert(RVI->getOperand(0));
299 continue;
300 case Instruction::Select: {
301 SelectInst *SI = cast<SelectInst>(RVI);
302 FlowsToReturn.insert(SI->getTrueValue());
303 FlowsToReturn.insert(SI->getFalseValue());
Chris Lattner439044f2009-09-27 21:29:28 +0000304 continue;
305 }
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000306 case Instruction::PHI: {
307 PHINode *PN = cast<PHINode>(RVI);
308 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
309 FlowsToReturn.insert(PN->getIncomingValue(i));
Chris Lattner439044f2009-09-27 21:29:28 +0000310 continue;
311 }
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000312
313 // Check whether the pointer came from an allocation.
314 case Instruction::Alloca:
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000315 break;
316 case Instruction::Call:
317 case Instruction::Invoke: {
318 CallSite CS(RVI);
319 if (CS.paramHasAttr(0, Attribute::NoAlias))
320 break;
321 if (CS.getCalledFunction() &&
Chris Lattner98a27ce2009-08-31 04:09:04 +0000322 SCCNodes.count(CS.getCalledFunction()))
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000323 break;
324 } // fall-through
325 default:
326 return false; // Did not come from an allocation.
327 }
328
Dan Gohmanf94b5ed2009-11-19 21:57:48 +0000329 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000330 return false;
331 }
332
333 return true;
334}
335
336/// AddNoAliasAttrs - Deduce noalias attributes for the SCC.
Chris Lattner2decb222010-04-16 22:42:17 +0000337bool FunctionAttrs::AddNoAliasAttrs(const CallGraphSCC &SCC) {
Chris Lattner98a27ce2009-08-31 04:09:04 +0000338 SmallPtrSet<Function*, 8> SCCNodes;
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000339
340 // Fill SCCNodes with the elements of the SCC. Used for quickly
341 // looking up whether a given CallGraphNode is in this SCC.
Chris Lattner2decb222010-04-16 22:42:17 +0000342 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
343 SCCNodes.insert((*I)->getFunction());
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000344
Nick Lewycky4bfba9d2009-03-08 17:08:09 +0000345 // Check each function in turn, determining which functions return noalias
346 // pointers.
Chris Lattner2decb222010-04-16 22:42:17 +0000347 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
348 Function *F = (*I)->getFunction();
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000349
350 if (F == 0)
351 // External node - skip it;
352 return false;
353
354 // Already noalias.
355 if (F->doesNotAlias(0))
356 continue;
357
358 // Definitions with weak linkage may be overridden at linktime, so
359 // treat them like declarations.
360 if (F->isDeclaration() || F->mayBeOverridden())
361 return false;
362
363 // We annotate noalias return values, which are only applicable to
364 // pointer types.
Duncan Sands1df98592010-02-16 11:11:14 +0000365 if (!F->getReturnType()->isPointerTy())
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000366 continue;
367
368 if (!IsFunctionMallocLike(F, SCCNodes))
369 return false;
370 }
371
372 bool MadeChange = false;
Chris Lattner2decb222010-04-16 22:42:17 +0000373 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
374 Function *F = (*I)->getFunction();
Duncan Sands1df98592010-02-16 11:11:14 +0000375 if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000376 continue;
377
378 F->setDoesNotAlias(0);
379 ++NumNoAlias;
380 MadeChange = true;
381 }
382
383 return MadeChange;
384}
385
Chris Lattner2decb222010-04-16 22:42:17 +0000386bool FunctionAttrs::runOnSCC(CallGraphSCC &SCC) {
Duncan Sands9e89ba32008-12-31 16:14:43 +0000387 bool Changed = AddReadAttrs(SCC);
388 Changed |= AddNoCaptureAttrs(SCC);
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000389 Changed |= AddNoAliasAttrs(SCC);
Duncan Sands9e89ba32008-12-31 16:14:43 +0000390 return Changed;
391}