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/LLVMContext.h"
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/Analysis/CallGraph.h"
29 #include "llvm/Analysis/CaptureTracking.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), AA(0) {
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 AU.addRequired<AliasAnalysis>();
67 CallGraphSCCPass::getAnalysisUsage(AU);
75 char FunctionAttrs::ID = 0;
76 INITIALIZE_PASS_BEGIN(FunctionAttrs, "functionattrs",
77 "Deduce function attributes", false, false)
78 INITIALIZE_AG_DEPENDENCY(CallGraph)
79 INITIALIZE_PASS_END(FunctionAttrs, "functionattrs",
80 "Deduce function attributes", false, false)
82 Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
85 /// AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
86 bool FunctionAttrs::AddReadAttrs(const CallGraphSCC &SCC) {
87 SmallPtrSet<Function*, 8> SCCNodes;
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 (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
92 SCCNodes.insert((*I)->getFunction());
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 (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
98 Function *F = (*I)->getFunction();
101 // External node - may write memory. Just give up.
104 AliasAnalysis::ModRefBehavior MRB = AA->getModRefBehavior(F);
105 if (MRB == AliasAnalysis::DoesNotAccessMemory)
109 // Definitions with weak linkage may be overridden at linktime with
110 // something that writes memory, so treat them like declarations.
111 if (F->isDeclaration() || F->mayBeOverridden()) {
112 if (!AliasAnalysis::onlyReadsMemory(MRB))
113 // May write memory. Just give up.
120 // Scan the function body for instructions that may read or write memory.
121 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
122 Instruction *I = &*II;
124 // Some instructions can be ignored even if they read or write memory.
125 // Detect these now, skipping to the next instruction if one is found.
126 CallSite CS(cast<Value>(I));
128 // Ignore calls to functions in the same SCC.
129 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
131 AliasAnalysis::ModRefBehavior MRB = AA->getModRefBehavior(CS);
132 // If the call doesn't access arbitrary memory, we may be able to
133 // figure out something.
134 if (!(MRB & AliasAnalysis::Anywhere &
135 ~AliasAnalysis::ArgumentPointees)) {
136 // If the call accesses argument pointees, check each argument.
137 if (MRB & AliasAnalysis::AccessesArguments)
138 // Check whether all pointer arguments point to local memory, and
139 // ignore calls that only access local memory.
140 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
143 if (Arg->getType()->isPointerTy()) {
144 AliasAnalysis::Location Loc(Arg,
145 AliasAnalysis::UnknownSize,
146 I->getMetadata(LLVMContext::MD_tbaa));
147 if (!AA->pointsToConstantMemory(Loc, /*OrLocal=*/true)) {
148 if (MRB & AliasAnalysis::Mod)
149 // Writes non-local memory. Give up.
151 if (MRB & AliasAnalysis::Ref)
152 // Ok, it reads non-local memory.
159 // The call could access any memory. If that includes writes, give up.
160 if (MRB & AliasAnalysis::Mod)
162 // If it reads, note it.
163 if (MRB & AliasAnalysis::Ref)
166 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
167 // Ignore non-volatile loads from local memory.
168 if (!LI->isVolatile()) {
169 AliasAnalysis::Location Loc(LI->getPointerOperand(),
170 AA->getTypeStoreSize(LI->getType()),
171 LI->getMetadata(LLVMContext::MD_tbaa));
172 if (AA->pointsToConstantMemory(Loc, /*OrLocal=*/true))
175 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
176 // Ignore non-volatile stores to local memory.
177 if (!SI->isVolatile()) {
178 const Type *StoredType = SI->getValueOperand()->getType();
179 AliasAnalysis::Location Loc(SI->getPointerOperand(),
180 AA->getTypeStoreSize(StoredType),
181 SI->getMetadata(LLVMContext::MD_tbaa));
182 if (AA->pointsToConstantMemory(Loc, /*OrLocal=*/true))
185 } else if (VAArgInst *VI = dyn_cast<VAArgInst>(I)) {
186 // Ignore vaargs on local memory.
187 AliasAnalysis::Location Loc(VI->getPointerOperand(),
188 AliasAnalysis::UnknownSize,
189 VI->getMetadata(LLVMContext::MD_tbaa));
190 if (AA->pointsToConstantMemory(Loc, /*OrLocal=*/true))
194 // Any remaining instructions need to be taken seriously! Check if they
195 // read or write memory.
196 if (I->mayWriteToMemory())
197 // Writes memory. Just give up.
200 // If this instruction may read memory, remember that.
201 ReadsMemory |= I->mayReadFromMemory();
205 // Success! Functions in this SCC do not access memory, or only read memory.
206 // Give them the appropriate attribute.
207 bool MadeChange = false;
208 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
209 Function *F = (*I)->getFunction();
211 if (F->doesNotAccessMemory())
215 if (F->onlyReadsMemory() && ReadsMemory)
221 // Clear out any existing attributes.
222 F->removeAttribute(~0, Attribute::ReadOnly | Attribute::ReadNone);
224 // Add in the new attribute.
225 F->addAttribute(~0, ReadsMemory? Attribute::ReadOnly : Attribute::ReadNone);
236 /// AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
237 bool FunctionAttrs::AddNoCaptureAttrs(const CallGraphSCC &SCC) {
238 bool Changed = false;
240 // Check each function in turn, determining which pointer arguments are not
242 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
243 Function *F = (*I)->getFunction();
246 // External node - skip it;
249 // Definitions with weak linkage may be overridden at linktime with
250 // something that writes memory, so treat them like declarations.
251 if (F->isDeclaration() || F->mayBeOverridden())
254 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A!=E; ++A)
255 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr() &&
256 !PointerMayBeCaptured(A, true, /*StoreCaptures=*/false)) {
257 A->addAttr(Attribute::NoCapture);
266 /// IsFunctionMallocLike - A function is malloc-like if it returns either null
267 /// or a pointer that doesn't alias any other pointer visible to the caller.
268 bool FunctionAttrs::IsFunctionMallocLike(Function *F,
269 SmallPtrSet<Function*, 8> &SCCNodes) const {
270 UniqueVector<Value *> FlowsToReturn;
271 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
272 if (ReturnInst *Ret = dyn_cast<ReturnInst>(I->getTerminator()))
273 FlowsToReturn.insert(Ret->getReturnValue());
275 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
276 Value *RetVal = FlowsToReturn[i+1]; // UniqueVector[0] is reserved.
278 if (Constant *C = dyn_cast<Constant>(RetVal)) {
279 if (!C->isNullValue() && !isa<UndefValue>(C))
285 if (isa<Argument>(RetVal))
288 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
289 switch (RVI->getOpcode()) {
290 // Extend the analysis by looking upwards.
291 case Instruction::BitCast:
292 case Instruction::GetElementPtr:
293 FlowsToReturn.insert(RVI->getOperand(0));
295 case Instruction::Select: {
296 SelectInst *SI = cast<SelectInst>(RVI);
297 FlowsToReturn.insert(SI->getTrueValue());
298 FlowsToReturn.insert(SI->getFalseValue());
301 case Instruction::PHI: {
302 PHINode *PN = cast<PHINode>(RVI);
303 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
304 FlowsToReturn.insert(PN->getIncomingValue(i));
308 // Check whether the pointer came from an allocation.
309 case Instruction::Alloca:
311 case Instruction::Call:
312 case Instruction::Invoke: {
314 if (CS.paramHasAttr(0, Attribute::NoAlias))
316 if (CS.getCalledFunction() &&
317 SCCNodes.count(CS.getCalledFunction()))
321 return false; // Did not come from an allocation.
324 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
331 /// AddNoAliasAttrs - Deduce noalias attributes for the SCC.
332 bool FunctionAttrs::AddNoAliasAttrs(const CallGraphSCC &SCC) {
333 SmallPtrSet<Function*, 8> SCCNodes;
335 // Fill SCCNodes with the elements of the SCC. Used for quickly
336 // looking up whether a given CallGraphNode is in this SCC.
337 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
338 SCCNodes.insert((*I)->getFunction());
340 // Check each function in turn, determining which functions return noalias
342 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
343 Function *F = (*I)->getFunction();
346 // External node - skip it;
350 if (F->doesNotAlias(0))
353 // Definitions with weak linkage may be overridden at linktime, so
354 // treat them like declarations.
355 if (F->isDeclaration() || F->mayBeOverridden())
358 // We annotate noalias return values, which are only applicable to
360 if (!F->getReturnType()->isPointerTy())
363 if (!IsFunctionMallocLike(F, SCCNodes))
367 bool MadeChange = false;
368 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
369 Function *F = (*I)->getFunction();
370 if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())
373 F->setDoesNotAlias(0);
381 bool FunctionAttrs::runOnSCC(CallGraphSCC &SCC) {
382 AA = &getAnalysis<AliasAnalysis>();
384 bool Changed = AddReadAttrs(SCC);
385 Changed |= AddNoCaptureAttrs(SCC);
386 Changed |= AddNoAliasAttrs(SCC);