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/MemoryBuiltins.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/UniqueVector.h"
33 #include "llvm/Support/InstIterator.h"
36 STATISTIC(NumReadNone, "Number of functions marked readnone");
37 STATISTIC(NumReadOnly, "Number of functions marked readonly");
38 STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
39 STATISTIC(NumNoAlias, "Number of function returns marked noalias");
42 struct FunctionAttrs : public CallGraphSCCPass {
43 static char ID; // Pass identification, replacement for typeid
44 FunctionAttrs() : CallGraphSCCPass(ID) {
45 initializeFunctionAttrsPass(*PassRegistry::getPassRegistry());
48 // runOnSCC - Analyze the SCC, performing the transformation if possible.
49 bool runOnSCC(CallGraphSCC &SCC);
51 // AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
52 bool AddReadAttrs(const CallGraphSCC &SCC);
54 // AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
55 bool AddNoCaptureAttrs(const CallGraphSCC &SCC);
57 // IsFunctionMallocLike - Does this function allocate new memory?
58 bool IsFunctionMallocLike(Function *F,
59 SmallPtrSet<Function*, 8> &) const;
61 // AddNoAliasAttrs - Deduce noalias attributes for the SCC.
62 bool AddNoAliasAttrs(const CallGraphSCC &SCC);
64 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
66 CallGraphSCCPass::getAnalysisUsage(AU);
69 bool PointsToLocalMemory(Value *V);
73 char FunctionAttrs::ID = 0;
74 INITIALIZE_PASS_BEGIN(FunctionAttrs, "functionattrs",
75 "Deduce function attributes", false, false)
76 INITIALIZE_AG_DEPENDENCY(CallGraph)
77 INITIALIZE_PASS_END(FunctionAttrs, "functionattrs",
78 "Deduce function attributes", false, false)
80 Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
83 /// PointsToLocalMemory - Returns whether the given pointer value points to
84 /// memory that is local to the function. Global constants are considered
85 /// local to all functions.
86 bool FunctionAttrs::PointsToLocalMemory(Value *V) {
87 SmallVector<Value*, 16> Worklist;
88 unsigned MaxLookup = 8;
90 Worklist.push_back(V);
93 V = Worklist.pop_back_val()->getUnderlyingObject();
95 // An alloca instruction defines local memory.
96 if (isa<AllocaInst>(V))
99 // A global constant counts as local memory for our purposes.
100 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
101 if (!GV->isConstant())
106 // If both select values point to local memory, then so does the select.
107 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
108 Worklist.push_back(SI->getTrueValue());
109 Worklist.push_back(SI->getFalseValue());
113 // If all values incoming to a phi node point to local memory, then so does
115 if (PHINode *PN = dyn_cast<PHINode>(V)) {
116 // Don't bother inspecting phi nodes with many operands.
117 if (PN->getNumIncomingValues() > MaxLookup)
119 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
120 Worklist.push_back(PN->getIncomingValue(i));
125 } while (!Worklist.empty() && --MaxLookup);
127 return Worklist.empty();
130 /// AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
131 bool FunctionAttrs::AddReadAttrs(const CallGraphSCC &SCC) {
132 SmallPtrSet<Function*, 8> SCCNodes;
134 // Fill SCCNodes with the elements of the SCC. Used for quickly
135 // looking up whether a given CallGraphNode is in this SCC.
136 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
137 SCCNodes.insert((*I)->getFunction());
139 // Check if any of the functions in the SCC read or write memory. If they
140 // write memory then they can't be marked readnone or readonly.
141 bool ReadsMemory = false;
142 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
143 Function *F = (*I)->getFunction();
146 // External node - may write memory. Just give up.
149 if (F->doesNotAccessMemory())
153 // Definitions with weak linkage may be overridden at linktime with
154 // something that writes memory, so treat them like declarations.
155 if (F->isDeclaration() || F->mayBeOverridden()) {
156 if (!F->onlyReadsMemory())
157 // May write memory. Just give up.
164 // Scan the function body for instructions that may read or write memory.
165 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
166 Instruction *I = &*II;
168 // Some instructions can be ignored even if they read or write memory.
169 // Detect these now, skipping to the next instruction if one is found.
170 CallSite CS(cast<Value>(I));
171 if (CS && CS.getCalledFunction()) {
172 // Ignore calls to functions in the same SCC.
173 if (SCCNodes.count(CS.getCalledFunction()))
175 // Ignore intrinsics that only access local memory.
176 if (unsigned id = CS.getCalledFunction()->getIntrinsicID())
177 if (AliasAnalysis::getIntrinsicModRefBehavior(id) ==
178 AliasAnalysis::AccessesArguments) {
179 // Check that all pointer arguments point to local memory.
180 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
183 if (Arg->getType()->isPointerTy() && !PointsToLocalMemory(Arg))
184 // Writes memory. Just give up.
187 // Only reads and writes local memory.
190 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
191 // Ignore loads from local memory.
192 if (PointsToLocalMemory(LI->getPointerOperand()))
194 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
195 // Ignore stores to local memory.
196 if (PointsToLocalMemory(SI->getPointerOperand()))
200 // Any remaining instructions need to be taken seriously! Check if they
201 // read or write memory.
202 if (I->mayWriteToMemory())
203 // Writes memory. Just give up.
207 // malloc claims not to write memory! PR3754.
210 // If this instruction may read memory, remember that.
211 ReadsMemory |= I->mayReadFromMemory();
215 // Success! Functions in this SCC do not access memory, or only read memory.
216 // Give them the appropriate attribute.
217 bool MadeChange = false;
218 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
219 Function *F = (*I)->getFunction();
221 if (F->doesNotAccessMemory())
225 if (F->onlyReadsMemory() && ReadsMemory)
231 // Clear out any existing attributes.
232 F->removeAttribute(~0, Attribute::ReadOnly | Attribute::ReadNone);
234 // Add in the new attribute.
235 F->addAttribute(~0, ReadsMemory? Attribute::ReadOnly : Attribute::ReadNone);
246 /// AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
247 bool FunctionAttrs::AddNoCaptureAttrs(const CallGraphSCC &SCC) {
248 bool Changed = false;
250 // Check each function in turn, determining which pointer arguments are not
252 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
253 Function *F = (*I)->getFunction();
256 // External node - skip it;
259 // Definitions with weak linkage may be overridden at linktime with
260 // something that writes memory, so treat them like declarations.
261 if (F->isDeclaration() || F->mayBeOverridden())
264 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A!=E; ++A)
265 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr() &&
266 !PointerMayBeCaptured(A, true, /*StoreCaptures=*/false)) {
267 A->addAttr(Attribute::NoCapture);
276 /// IsFunctionMallocLike - A function is malloc-like if it returns either null
277 /// or a pointer that doesn't alias any other pointer visible to the caller.
278 bool FunctionAttrs::IsFunctionMallocLike(Function *F,
279 SmallPtrSet<Function*, 8> &SCCNodes) const {
280 UniqueVector<Value *> FlowsToReturn;
281 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
282 if (ReturnInst *Ret = dyn_cast<ReturnInst>(I->getTerminator()))
283 FlowsToReturn.insert(Ret->getReturnValue());
285 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
286 Value *RetVal = FlowsToReturn[i+1]; // UniqueVector[0] is reserved.
288 if (Constant *C = dyn_cast<Constant>(RetVal)) {
289 if (!C->isNullValue() && !isa<UndefValue>(C))
295 if (isa<Argument>(RetVal))
298 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
299 switch (RVI->getOpcode()) {
300 // Extend the analysis by looking upwards.
301 case Instruction::BitCast:
302 case Instruction::GetElementPtr:
303 FlowsToReturn.insert(RVI->getOperand(0));
305 case Instruction::Select: {
306 SelectInst *SI = cast<SelectInst>(RVI);
307 FlowsToReturn.insert(SI->getTrueValue());
308 FlowsToReturn.insert(SI->getFalseValue());
311 case Instruction::PHI: {
312 PHINode *PN = cast<PHINode>(RVI);
313 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
314 FlowsToReturn.insert(PN->getIncomingValue(i));
318 // Check whether the pointer came from an allocation.
319 case Instruction::Alloca:
321 case Instruction::Call:
322 case Instruction::Invoke: {
324 if (CS.paramHasAttr(0, Attribute::NoAlias))
326 if (CS.getCalledFunction() &&
327 SCCNodes.count(CS.getCalledFunction()))
331 return false; // Did not come from an allocation.
334 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
341 /// AddNoAliasAttrs - Deduce noalias attributes for the SCC.
342 bool FunctionAttrs::AddNoAliasAttrs(const CallGraphSCC &SCC) {
343 SmallPtrSet<Function*, 8> SCCNodes;
345 // Fill SCCNodes with the elements of the SCC. Used for quickly
346 // looking up whether a given CallGraphNode is in this SCC.
347 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
348 SCCNodes.insert((*I)->getFunction());
350 // Check each function in turn, determining which functions return noalias
352 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
353 Function *F = (*I)->getFunction();
356 // External node - skip it;
360 if (F->doesNotAlias(0))
363 // Definitions with weak linkage may be overridden at linktime, so
364 // treat them like declarations.
365 if (F->isDeclaration() || F->mayBeOverridden())
368 // We annotate noalias return values, which are only applicable to
370 if (!F->getReturnType()->isPointerTy())
373 if (!IsFunctionMallocLike(F, SCCNodes))
377 bool MadeChange = false;
378 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
379 Function *F = (*I)->getFunction();
380 if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())
383 F->setDoesNotAlias(0);
391 bool FunctionAttrs::runOnSCC(CallGraphSCC &SCC) {
392 bool Changed = AddReadAttrs(SCC);
393 Changed |= AddNoCaptureAttrs(SCC);
394 Changed |= AddNoAliasAttrs(SCC);